-
Notifications
You must be signed in to change notification settings - Fork 10
/
Copy pathunityx3d.cs
1531 lines (1219 loc) · 55.5 KB
/
unityx3d.cs
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/*
* UnityX3D
*
* Copyright (c) 2017 Tobias Alexander Franke
* http://www.tobias-franke.eu
*
* Copyright (c) 2019 John Grime, ETL, University of Oklahoma
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/
using UnityEngine;
using UnityEditor;
using System.IO;
using System.Xml;
using System.Linq;
using System.Text;
using System.Collections.Generic;
namespace UnityX3D
{
#if UNITY_EDITOR
[InitializeOnLoad]
#endif
public class Preferences
{
protected static bool loaded = false;
public static bool useCommonSurfaceShader = true;
public static bool bakedLightsAmbient = true;
public static bool disableHeadlight = false;
public static bool savePNGlightmaps = false;
public static bool lightmapUnlitFaceSets = false;
public static bool saveIndividualShapes = false;
public static bool exportLightmaps = true;
static Preferences()
{
Load();
}
#if UNITY_EDITOR
[PreferenceItem("UnityX3D")]
static void PreferenceGUI()
{
if(!loaded)
Load();
useCommonSurfaceShader = EditorGUILayout.Toggle("Use CommonSurfaceShader", useCommonSurfaceShader);
bakedLightsAmbient = EditorGUILayout.Toggle("Export static lights as ambient", bakedLightsAmbient);
disableHeadlight = EditorGUILayout.Toggle("Disable X3D headlight", disableHeadlight);
exportLightmaps = EditorGUILayout.Toggle("Export Lightmaps", exportLightmaps);
savePNGlightmaps = EditorGUILayout.Toggle("Save Lightmaps as PNG", savePNGlightmaps);
lightmapUnlitFaceSets = EditorGUILayout.Toggle("Set Facesets unlit if lightmapped", lightmapUnlitFaceSets);
if(GUI.changed)
Save();
}
static void Load()
{
useCommonSurfaceShader = EditorPrefs.GetBool("UnityX3D.useCommonSurfaceShader", true);
bakedLightsAmbient = EditorPrefs.GetBool("UnityX3D.bakedLightsAmbient", true);
disableHeadlight = EditorPrefs.GetBool("UnityX3D.disableHeadlight", false);
exportLightmaps = EditorPrefs.GetBool("UnityX3D.exportLightmaps", true);
savePNGlightmaps = EditorPrefs.GetBool("UnityX3D.savePNGlightmaps", false);
lightmapUnlitFaceSets = EditorPrefs.GetBool("Unlit Facesets if lightmapped?", false);
loaded = true;
}
static void Save()
{
EditorPrefs.SetBool("UnityX3D.useCommonSurfaceShader", useCommonSurfaceShader);
EditorPrefs.SetBool("UnityX3D.bakedLightsAmbient", bakedLightsAmbient);
EditorPrefs.SetBool("UnityX3D.disableHeadlight", disableHeadlight);
EditorPrefs.SetBool("UnityX3D.exportLightmaps", exportLightmaps);
EditorPrefs.SetBool("UnityX3D.savePNGlightmaps", savePNGlightmaps);
EditorPrefs.SetBool("UnityX3D.lightmapUnlitFaceSets", lightmapUnlitFaceSets);
}
#else
// Just a dummy routine.
static void Load()
{
loaded = true;
}
#endif
}
class Tools
{
public static void ClearConsole()
{
Debug.ClearDeveloperConsole();
}
//
// String helper routines
//
public static string ToString(Vector2 v)
{
return v.x + " " + v.y;
}
public static string ToString(Vector3 v)
{
return v.x + " " + v.y + " " + v.z;
}
public static string[] TokensFromString(string v)
{
if (!string.IsNullOrEmpty(v))
{
char[] delimiters = new char[] { ',', ' ' };
string[] tokens = v.Split(delimiters);
return tokens.Where(x => !string.IsNullOrEmpty(x)).ToArray();
}
return new string[] { };
}
public static int[] IntArrayFromString(string v)
{
string[] tokens = TokensFromString(v);
return tokens.Select(int.Parse).ToArray();
}
public static float[] FloatArrayFromString(string v)
{
string[] tokens = TokensFromString(v);
return tokens.Select(float.Parse).ToArray();
}
public static Vector3 Vector3FromString(string v, float defaultScalar = 0)
{
float[] floatTokens = FloatArrayFromString(v);
if (floatTokens.Length >= 3)
return new Vector3(floatTokens[0], floatTokens[1], floatTokens[2]);
if (floatTokens.Length == 1)
return new Vector3(floatTokens[0], floatTokens[0], floatTokens[0]);
return new Vector3(defaultScalar, defaultScalar, defaultScalar);
}
public static Vector4 Vector4FromString(string v, float defaultScalar = 0)
{
float[] floatTokens = FloatArrayFromString(v);
if (floatTokens.Length >= 4)
return new Vector4(floatTokens[0], floatTokens[1], floatTokens[2], floatTokens[3]);
if (floatTokens.Length == 1)
return new Vector4(floatTokens[0], floatTokens[0], floatTokens[0], floatTokens[0]);
return new Vector4(defaultScalar, defaultScalar, defaultScalar, defaultScalar);
}
//
// XML node attribute helper routines
//
public static string GetAttribute(XmlNode node, string attrib)
{
if (node.Attributes != null)
{
var a = node.Attributes[attrib];
if (a != null)
return a.Value;
}
return "";
}
public static Vector3 Vector3FromAttribute(XmlNode node, string attrib, float defaultScalar = 0)
{
return Vector3FromString(GetAttribute(node, attrib), defaultScalar);
}
public static Vector4 Vector4FromAttribute(XmlNode node, string attrib, float defaultScalar = 0)
{
return Vector4FromString(GetAttribute(node, attrib), defaultScalar);
}
public static float FloatFromAttribute(XmlNode node, string attrib)
{
string v = GetAttribute(node, attrib);
if (v == "")
return 0;
return float.Parse(v);
}
//
// Misc. helper routines
//
public static string ToString(Color c)
{
return c.r + " " + c.g + " " + c.b;
}
public static double ToRadians(double degrees)
{
return Mathf.Deg2Rad * degrees;
}
public static float ToDegrees(float radians)
{
return Mathf.Rad2Deg * radians;
}
}
/*
* This is the main class responsible for importing an X3D document
*/
#if UNITY_EDITOR
class X3DImporter : AssetPostprocessor
#else
class X3DImporter
#endif
{
//
// Data containers, output of processing specific X3D nodes
//
class MaterialInfo
{
// Per-material
public float smoothness, metalness;
public Color diffuseColor, emissiveColor;
// This is actually a global render setting
public float ambientIntensity;
}
class AppearanceInfo
{
public MaterialInfo material = null;
public Texture2D texture = null;
}
class TransformInfo
{
public Vector3 translation, scale;
public Quaternion rotation;
}
//
// Map to help implement DEF/USE in X3D's "Shape" nodes
//
Dictionary<string, GameObject> DefToObjMap = new Dictionary<string, GameObject>();
//
// Extract node name (if present), populating DefToObj map as we go.
//
string GetName(XmlNode node, GameObject obj)
{
if (node.Attributes != null)
{
XmlAttribute name = node.Attributes["DEF"];
if (name != null)
{
DefToObjMap[name.Value] = obj;
return name.Value;
}
}
return node.Name ?? "Unnamed";
}
//
// Mesh generation
//
GameObject ReadBox(XmlNode boxNode, GameObject parent)
{
Vector3 size = Tools.Vector3FromAttribute(boxNode, "size", 1);
GameObject cube = GameObject.CreatePrimitive(PrimitiveType.Cube);
GameObject obj = new GameObject("Box");
obj.transform.SetParent(parent.transform);
obj.transform.localScale = size;
MeshFilter meshFilter = obj.AddComponent<MeshFilter>();
meshFilter.mesh = cube.GetComponent<MeshFilter>().sharedMesh;
GameObject.DestroyImmediate(cube);
return obj;
}
List<GameObject> ReadIndexedFaceSet(XmlNode indexedFaceSetNode, GameObject parent)
{
List<GameObject> components = new List<GameObject>();
float[] vtx = null, uv = null, nrm = null, rgba = null;
//
// Both of the following contain per-triangle indices into flat coord / tex coord arrays;
// each set of triangle info is stored as a 4-tuple, with the 4th element ignored (it's a
// sentinel with value -1 denoting the end of polygonal faces; we obviously assume triangles).
//
int[] triVtxIdx = Tools.IntArrayFromString(Tools.GetAttribute(indexedFaceSetNode, "coordIndex"));
int[] triUvIdx = Tools.IntArrayFromString(Tools.GetAttribute(indexedFaceSetNode, "texCoordIndex"));
// If we have no triangle vertices, we can't really do anything; return empty list.
if (triVtxIdx.Length == 0) return components;
// Extract raw data arrays
foreach (XmlNode child in indexedFaceSetNode)
{
if (child.Name == "Coordinate")
vtx = Tools.FloatArrayFromString(Tools.GetAttribute(child, "point"));
if (child.Name == "TextureCoordinate")
uv = Tools.FloatArrayFromString(Tools.GetAttribute(child, "point"));
if (child.Name == "Normal")
nrm = Tools.FloatArrayFromString(Tools.GetAttribute(child, "vector"));
if (child.Name == "ColorRGBA")
rgba = Tools.FloatArrayFromString(Tools.GetAttribute(child, "color"));
}
// This should probably be treated as an error: We expect at least one vertex!
if (vtx == null) return components;
//
// Each triangle has per-vertex indices into the arrays containing the coordinate,
// uv, normal, and rgba data. Walk the triangles, creating UNIQUE vertex data for
// each triangle; Unity meshes assume separate per-vertex data for eg texture
// coords etc (this is not guaranteed in X3D files).
//
// Unity also typically limits vertex count in a mesh due to using 16 bit indices
// (x < 2^16, so x < 65,536); if this limit is reached, add remaining data to a new,
// different mesh. Unity GameObjects can only have one mesh, so meshes are assigned
// to child objects (with new child objects created as and when needed).
//
// 65535 % 3 == 0, so (x >= max_mesh_vtx) OK for adding sets of 3 vertices
const int maxMeshVtx = 65535;
// Current mesh to which we're adding vertex and triangle information
Mesh mesh = null;
// Current mesh data is accumulated into these Lists
List<int> triList = new List<int>();
List<Vector3> vtxList = new List<Vector3>();
List<Vector3> nrmList = new List<Vector3>();
List<Vector2> uvList = new List<Vector2>();
List<Color> rgbaList = new List<Color>();
// Raw index arrays are sequential integer 4-tuples, so n_tri = length/4
int nTri = triVtxIdx.Length / 4;
// Set up new triangle data, creating unique vertex data as we go
for (int triIdx = 0; triIdx < nTri; triIdx++)
{
int triOffset = triIdx * 4; // as indices are per-triangle 4-tuples (4th element ignored)
// Create new mesh object if needed; we'll only see this in the first loop iteration,
// or immediately after adding a full mesh and clearing the previous accumulators.
if (vtxList.Count() < 1)
{
GameObject obj = new GameObject("Mesh");
obj.transform.SetParent(parent.transform);
mesh = new Mesh();
MeshFilter meshFilter = obj.AddComponent<MeshFilter>();
meshFilter.mesh = mesh;
components.Add(obj); // <- ensure new object reference is returned to the caller
}
// Generate new per-vertex data for each of the 3 vertices in the triangle
for (int vtxOffset=0; vtxOffset < 3; vtxOffset++)
{
int i = triVtxIdx[triOffset + vtxOffset];
// Create new per-vertex coordinate
{
int j = (i * 3);
vtxList.Add(new Vector3(vtx[j + 0], vtx[j + 1], vtx[j + 2]));
}
// Create new per-vertex normal
if (nrm != null)
{
int j = (i * 3);
nrmList.Add(new Vector3(nrm[j + 0], nrm[j + 1], nrm[j + 2]));
}
// Create new per-vertex rgba color value
if (rgba != null)
{
int j = (i * 4);
rgbaList.Add(new Vector4(rgba[j + 0], rgba[j + 1], rgba[j + 2], rgba[j + 3]));
}
// Create new per-vertex texture coordinate
if (uv != null)
{
i = triUvIdx[triOffset + vtxOffset];
int j = (i * 2);
uvList.Add(new Vector2(uv[j + 0], uv[j + 1]));
}
}
// Set new triangle vertex indices; simply sequential.
triList.Add(triList.Count());
triList.Add(triList.Count());
triList.Add(triList.Count());
// Have we reached the limit of what a single mesh can contain?
if (vtxList.Count() >= maxMeshVtx)
{
// Set mesh data
mesh.SetVertices(vtxList);
if (nrm != null) mesh.SetNormals(nrmList);
if (rgba != null) mesh.SetColors(rgbaList);
if (uv != null) mesh.SetUVs(0, uvList);
mesh.SetTriangles(triList, 0);
// Clear accumulators; triggers new mesh creation if loop continues.
triList.Clear();
vtxList.Clear();
nrmList.Clear();
uvList.Clear();
rgbaList.Clear();
}
}
// Populate the final mesh, if needed
if (vtxList.Count() > 0)
{
mesh.SetVertices(vtxList);
if (nrm != null) mesh.SetNormals(nrmList);
if (rgba != null) mesh.SetColors(rgbaList);
if (uv != null) mesh.SetUVs(0, uvList);
mesh.SetTriangles(triList, 0);
}
return components;
}
//
// Material / texture generation
//
MaterialInfo ReadMaterial(XmlNode node, bool isCommonSurfaceShader = false)
{
float shininess;
Vector3 specular, diffuse, emissive;
float ambientIntensity;
if (isCommonSurfaceShader)
{
shininess = Tools.FloatFromAttribute(node, "shininessFactor");
specular = Tools.Vector3FromAttribute(node, "specularFactor");
diffuse = Tools.Vector3FromAttribute(node, "diffuseFactor");
emissive = Tools.Vector3FromAttribute(node, "emissionColor");
Vector3 ambientFactor = Tools.Vector3FromAttribute(node, "ambientFactor");
ambientIntensity = ambientFactor.magnitude;
}
else
{
shininess = Tools.FloatFromAttribute(node, "shininess");
specular = Tools.Vector3FromAttribute(node, "specularColor");
diffuse = Tools.Vector3FromAttribute(node, "diffuseColor");
emissive = Tools.Vector3FromAttribute(node, "emissiveColor");
ambientIntensity = Tools.FloatFromAttribute(node, "ambientIntensity");
}
return new MaterialInfo {
smoothness = Mathf.Sqrt(shininess),
metalness = specular.magnitude,
diffuseColor = new Color(diffuse[0], diffuse[1], diffuse[2]),
emissiveColor = new Color(emissive[0], emissive[1], emissive[2]),
ambientIntensity = ambientIntensity
};
// TODO: textures
}
Texture2D ReadImageTexture(XmlNode imageTextureNode, string filepathPrefix)
{
string url = Tools.GetAttribute(imageTextureNode, "url");
string localPath;
//
// Use ImageTexture URL to create object texture. Here, I assume:
//
// 1. URL refers to a local file (remote data fetch via http/ftp/etc currently unsupported)
//
// 2. There is only one texture path defined; in principle, the "url" attribute is an
// "MFString" - which can be a comma-delineated array of (quoted) strings:
//
// https://doc.x3dom.org/author/Texturing/ImageTexture.html
// http://www.web3d.org/specifications/X3dSchemaDocumentation3.3/x3d-3.3_MFString.html
//
try
{
System.Uri uri = new System.Uri(Tools.GetAttribute(imageTextureNode, "url"));
if (!uri.IsFile)
{
Debug.LogWarning($"ImageTexture URI scheme '{uri.Scheme}' is not currently supported.");
return null;
}
localPath = uri.LocalPath;
}
catch (System.Exception)
{
Debug.LogWarning($"ImageTexture parse failure for '{url}' as URI; assuming local file path.");
if (string.IsNullOrEmpty(url))
{
Debug.LogWarning($"ImageTexture url is null or empty; texture will not be applied.");
return null;
}
localPath = url;
}
string path = System.IO.Path.Combine(filepathPrefix, localPath);
if (!File.Exists(path))
{
Debug.LogWarning($"ImageTexture file path '{path}' not found; texture will not be applied.");
return null;
}
// Read specified image data from file into a Unity texture
byte[] imageBytes = File.ReadAllBytes(path);
Texture2D texture = new Texture2D(2, 2);
texture.LoadImage(imageBytes);
return texture;
}
AppearanceInfo ReadAppearance(XmlNode appearanceNode, string filepathPrefix)
{
AppearanceInfo appearance = new AppearanceInfo();
// Detect some kind of material & texture (if present)
foreach (XmlNode child in appearanceNode.ChildNodes)
{
bool isCSS = (child.Name == "CommonSurfaceShader");
if (isCSS || child.Name == "Material")
{
appearance.material = ReadMaterial(child, isCommonSurfaceShader: isCSS);
}
else if (child.Name == "ImageTexture")
{
appearance.texture = ReadImageTexture(child, filepathPrefix);
}
}
return appearance;
}
//
// Shapes are a combination of mesh data and the material properties applied to the mesh
//
void ReadShape(XmlNode shapeNode, GameObject parent, string filepathPrefix)
{
List<GameObject> components = new List<GameObject>();
AppearanceInfo appearance = null;
// Extract mesh components and appearance data
foreach (XmlNode child in shapeNode.ChildNodes)
{
if (child.Name == "Box")
{
GameObject box = ReadBox(child, parent);
components.Add(box);
}
else if (child.Name == "IndexedFaceSet")
{
components.AddRange(ReadIndexedFaceSet(child, parent));
}
else if (child.Name == "Appearance")
{
appearance = ReadAppearance(child, filepathPrefix);
}
}
// Apply appearance data to all mesh components of the shape.
foreach (GameObject obj in components)
{
Renderer renderer = obj.GetComponent<MeshRenderer>();
if (renderer == null)
renderer = obj.AddComponent<MeshRenderer>();
// Add a default material, will be modified below if needed.
renderer.material = new Material(Shader.Find("Standard"));
if (appearance == null) continue;
// Apply material properties
if (appearance.material != null)
{
MaterialInfo m = appearance.material;
renderer.sharedMaterial.SetFloat("_Metallic", m.metalness);
renderer.sharedMaterial.SetFloat("_Glossiness", m.smoothness);
renderer.sharedMaterial.SetColor("_Color", m.diffuseColor * 1.0f / (1 - m.metalness));
renderer.sharedMaterial.SetColor("_EmissionColor", m.emissiveColor);
RenderSettings.ambientIntensity = m.ambientIntensity;
}
// Apply texture
if (appearance.texture != null)
renderer.material.mainTexture = appearance.texture;
}
}
TransformInfo ReadTransform(XmlNode transformNode)
{
TransformInfo ti = new TransformInfo();
// Translation
ti.translation = Tools.Vector3FromAttribute(transformNode, "translation");
// Convert axis/angle rotation into quaternion
{
Vector4 values = Tools.Vector4FromAttribute(transformNode, "rotation");
Vector3 axis = new Vector3(values[0], values[1], values[2]);
float angle = Tools.ToDegrees(values[3]);
ti.rotation = Quaternion.AngleAxis(angle, axis);
}
// scaling
ti.scale = Tools.Vector3FromAttribute(transformNode, "scale", 1);
return ti;
}
void ReadX3D(XmlNode node, GameObject parent, string filepathPrefix)
{
foreach (XmlNode childNode in node)
{
// Filter out comments
if (childNode.Name == "#comment")
continue;
// Re-use object? TODO: Wait until whole document is actually parsed
string use = Tools.GetAttribute(childNode, "USE");
if (use != "" && DefToObjMap.Keys.Contains(use))
{
Object.Instantiate(DefToObjMap[use], parent.transform, false);
continue;
}
GameObject newObj = new GameObject();
newObj.name = GetName(childNode, newObj);
// Set parent of new object, if specified
if (parent != null)
newObj.transform.parent = parent.transform;
// What does the current node suggest we do?
if (childNode.Name == "Transform")
{
TransformInfo ti = ReadTransform(childNode);
newObj.transform.localPosition = ti.translation;
newObj.transform.rotation = ti.rotation;
newObj.transform.localScale = ti.scale;
ReadX3D(childNode, newObj, filepathPrefix); // Recurse into any child nodes under this transform
}
else if (childNode.Name == "Shape")
{
ReadShape(childNode, newObj, filepathPrefix);
}
}
}
//
// Public entry point into X3D parsing; returns root GameObject for scene, populates XmlDocument.
//
public GameObject ReadX3D(string path, out XmlDocument xml, string filepathPrefix = null)
{
xml = null;
Tools.ClearConsole();
// We can't do much with a bad path.
if (string.IsNullOrEmpty(path))
{
Debug.LogWarning( $"ReadX3D(): path is null or empty." );
return null;
}
// No user-defined filepath prefix? Attempt to infer from path.
if (filepathPrefix == null)
{
var fileInfo = new System.IO.FileInfo(path);
filepathPrefix = fileInfo.Directory.FullName;
}
xml = new XmlDocument();
xml.Load(path);
// Get to Scene node
XmlNode x3dNode = xml.SelectSingleNode("X3D");
XmlNode sceneNode = x3dNode.SelectSingleNode("Scene");
// Process scene node
GameObject scene = new GameObject("Scene");
ReadX3D(sceneNode, scene, filepathPrefix);
#if UNITY_EDITOR
EditorUtility.ClearProgressBar();
#endif
return scene;
}
static void OnPostprocessAllAssets(string[] importedAssets, string[] deletedAssets, string[] movedAssets, string[] movedFromAssetPaths)
{
foreach (string path in importedAssets.Where(x => x.EndsWith(".x3d")))
{
XmlDocument xml;
X3DImporter imp = new X3DImporter();
imp.ReadX3D(path, out xml);
}
}
}
/*
* This is the main class responsible for exporting the selected scene to an X3D document
*/
public class X3DExporter : MonoBehaviour
{
static protected XmlDocument xml;
static protected string outputPath;
static protected XmlNode sceneNode;
static protected XmlNode X3DNode;
static protected List<string> defNamesInUse;
static protected int currentNodeIndex;
static protected int numNodesToExport;
// create a safe-to-use ID
static string ToSafeDEF(string def)
{
string uDef = def.Replace(" ", "_");
string safeDef = uDef;
int i = 1;
while(defNamesInUse.Contains(safeDef))
{
safeDef = uDef + "_" + i;
i++;
}
defNamesInUse.Add(safeDef);
return safeDef;
}
// helper function to add an attribute with a name and value to a node
static XmlAttribute AddXmlAttribute(XmlNode node, string name, string value)
{
XmlAttribute attr = xml.CreateAttribute(name);
attr.Value = value;
node.Attributes.Append(attr);
return attr;
}
static XmlNode CreateNode(string name)
{
return xml.CreateElement(name);
}
// convert a Unity Camera to X3D
static XmlNode CameraToX3D(Camera camera, Transform transform = null)
{
XmlNode viewpointNode;
viewpointNode = CreateNode("Viewpoint");
AddXmlAttribute(viewpointNode, "DEF", ToSafeDEF(camera.name));
double fov = camera.fieldOfView * Mathf.PI / 180;
AddXmlAttribute(viewpointNode, "fieldOfView", fov.ToString());
if(transform != null)
{
AddXmlAttribute(viewpointNode, "position", Tools.ToString(transform.transform.localPosition));
float angle = 0F;
Vector3 axis = Vector3.zero;
transform.transform.localRotation.ToAngleAxis(out angle, out axis);
AddXmlAttribute(viewpointNode, "orientation", Tools.ToString(axis) + " " + Tools.ToRadians(angle).ToString());
}
return viewpointNode;
}
// convert a Mesh and accompanying Renderer to X3D
static XmlNode ObjectToX3D(string name, Mesh mesh, Renderer renderer)
{
if(mesh == null)
{
Debug.LogWarning("UnityX3D Warning: SharedMesh reference of " + name + " is null.");
return null;
}
XmlNode shapeNode = ObjectToX3D(mesh, renderer);
return shapeNode;
}
// convert a Mesh and accompanying Renderer with its Materials to X3D
static XmlNode ObjectToX3D(Mesh mesh, Renderer renderer)
{
XmlNode shapeNode;
shapeNode = CreateNode("Shape");
AddXmlAttribute(shapeNode, "DEF", ToSafeDEF(mesh.name));
shapeNode.AppendChild(RendererToX3D(renderer));
shapeNode.AppendChild(MeshToX3D(mesh, renderer.lightmapScaleOffset, renderer.lightmapIndex != -1));
return shapeNode;
}
// convert a Unity Mesh to X3D
static XmlNode MeshToX3D(Mesh mesh, Vector4 lightmapScaleOffset, bool hasLightmap)
{
XmlNode geometryNode;
// TODO: Predefined geometries and MultiTextureCoordiantes for lightmaps
/*
if(mesh.name == "Sphere Instance")
{
geometryNode = CreateNode("Sphere");
AddXmlAttribute(geometryNode, "radius",(0.5).Tools.ToString());
}
else if(mesh.name == "Cylinder Instance")
{
geometryNode = CreateNode("Cylinder");
}
else if(mesh.name == "Cube")
{
geometryNode = CreateNode("Box");
AddXmlAttribute(geometryNode, "size", Tools.ToString(Vector3.one));
}
else
*/
{
geometryNode = CreateNode("IndexedFaceSet");
if (hasLightmap && Preferences.lightmapUnlitFaceSets)
AddXmlAttribute(geometryNode, "lit", "FALSE");
// process indices
XmlAttribute coordIndex = xml.CreateAttribute("coordIndex");
geometryNode.Attributes.Append(coordIndex);
System.Text.StringBuilder sbCoordIndexValue = new System.Text.StringBuilder();
for(int i = 0; i < mesh.triangles.Length; i += 3)
{
sbCoordIndexValue.Append(mesh.triangles[i + 0].ToString() + " ");
sbCoordIndexValue.Append(mesh.triangles[i + 1].ToString() + " ");
sbCoordIndexValue.Append(mesh.triangles[i + 2].ToString() + " ");
sbCoordIndexValue.Append(" -1 ");
}
coordIndex.Value = sbCoordIndexValue.ToString();
// process normals
if(mesh.normals.Length > 0)
{
XmlNode normalNode = CreateNode("Normal");
XmlAttribute vector = xml.CreateAttribute("vector");
normalNode.Attributes.Append(vector);
System.Text.StringBuilder sbVectorValue = new System.Text.StringBuilder();
foreach(Vector3 n in mesh.normals)
sbVectorValue.Append(Tools.ToString(n) + " ");
vector.Value = sbVectorValue.ToString();
geometryNode.AppendChild(normalNode);
}
XmlNode multiTextureCoordinateNode = CreateNode("MultiTextureCoordinate");
// process vertices
if(mesh.vertices.Length > 0)
{
XmlNode coordinateNode = CreateNode("Coordinate");
XmlAttribute point = xml.CreateAttribute("point");
coordinateNode.Attributes.Append(point);
System.Text.StringBuilder sbPointValue = new System.Text.StringBuilder();
foreach(Vector3 v in mesh.vertices)
sbPointValue.Append(Tools.ToString(v) + " ");
point.Value = sbPointValue.ToString();
geometryNode.AppendChild(coordinateNode);
}
// process lightmap UV coordinates
Vector2[] lightmapUVs = mesh.uv2;
if (lightmapUVs.Length == 0 && hasLightmap)
{
lightmapUVs = mesh.uv;
}
if (lightmapUVs.Length > 0 && Preferences.exportLightmaps)
{
XmlNode textureCoordinateNode = CreateNode("TextureCoordinate");
XmlAttribute point = xml.CreateAttribute("point");
textureCoordinateNode.Attributes.Append(point);
System.Text.StringBuilder sbPointValue = new System.Text.StringBuilder();
foreach (Vector2 v in lightmapUVs)
{
Vector2 vv = v;
vv.x *= lightmapScaleOffset.x;
vv.y *= lightmapScaleOffset.y;
vv.x += lightmapScaleOffset.z;
vv.y += lightmapScaleOffset.w;
sbPointValue.Append(Tools.ToString(vv) + " ");
}
point.Value = sbPointValue.ToString();
multiTextureCoordinateNode.AppendChild(textureCoordinateNode);
}
// process UV coordinates
if(mesh.uv.Length > 0 && lightmapUVs != mesh.uv)
{
XmlNode textureCoordinateNode = CreateNode("TextureCoordinate");
XmlAttribute point = xml.CreateAttribute("point");
textureCoordinateNode.Attributes.Append(point);
System.Text.StringBuilder sbPointValue = new System.Text.StringBuilder();
foreach (Vector2 v in mesh.uv)
{
sbPointValue.Append(Tools.ToString(v) + " ");
}
point.Value = sbPointValue.ToString();
multiTextureCoordinateNode.AppendChild(textureCoordinateNode);
}
if (multiTextureCoordinateNode.HasChildNodes)