/
FbxExporter.cs
5011 lines (4361 loc) · 201 KB
/
FbxExporter.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
using System.IO;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.Animations;
using UnityEngine.Timeline;
using System.Linq;
using Autodesk.Fbx;
using System.Runtime.CompilerServices;
using System.Runtime.Serialization;
using UnityEditor.Formats.Fbx.Exporter.Visitors;
using UnityEngine.Playables;
[assembly: InternalsVisibleTo("Unity.Formats.Fbx.Editor.Tests")]
[assembly: InternalsVisibleTo("Unity.ProBuilder.AddOns.Editor")]
namespace UnityEditor.Formats.Fbx.Exporter
{
/// <summary>
/// If your MonoBehaviour knows about some custom geometry that
/// isn't in a MeshFilter or SkinnedMeshRenderer, use
/// RegisterMeshCallback to get a callback when the exporter tries
/// to export your component.
///
/// The callback should return true, and output the mesh you want.
///
/// Return false if you don't want to drive this game object.
///
/// Return true and output a null mesh if you don't want the
/// exporter to output anything.
/// </summary>
internal delegate bool GetMeshForComponent<T>(ModelExporter exporter, T component, FbxNode fbxNode) where T : MonoBehaviour;
internal delegate bool GetMeshForComponent(ModelExporter exporter, MonoBehaviour component, FbxNode fbxNode);
/// <summary>
/// Delegate used to convert a GameObject into a mesh.
///
/// This is useful if you want to have broader control over
/// the export process than the GetMeshForComponent callbacks
/// provide. But it's less efficient because you'll get a callback
/// on every single GameObject.
/// </summary>
internal delegate bool GetMeshForObject(ModelExporter exporter, GameObject gameObject, FbxNode fbxNode);
[System.Serializable]
internal class ModelExportException : System.Exception
{
public ModelExportException() {}
public ModelExportException(string message)
: base(message) {}
public ModelExportException(string message, System.Exception inner)
: base(message, inner) {}
protected ModelExportException(SerializationInfo info, StreamingContext context)
: base(info, context) {}
}
/// <summary>
/// Use the ModelExporter class to export Unity GameObjects to an FBX file.
/// <para>
/// Use the ExportObject and ExportObjects methods. The default export
/// options are used when exporting the objects to the FBX file.
/// </para>
/// <para>For information on using the ModelExporter class, see <a href="index.html">the Developer's Guide</a>.</para>
/// </summary>
public sealed class ModelExporter
{
const string Title =
"Created by FBX Exporter from Unity Technologies";
const string Subject =
"";
const string Keywords =
"Nodes Meshes Materials Textures Cameras Lights Skins Animation";
const string Comments =
@"";
/// <summary>
/// Path to the CHANGELOG file in Unity's virtual file system. Used to get the version number.
/// </summary>
const string ChangeLogPath = "Packages/com.unity.formats.fbx/CHANGELOG.md";
// NOTE: The ellipsis at the end of the Menu Item name prevents the context
// from being passed to command, thus resulting in OnContextItem()
// being called only once regardless of what is selected.
const string MenuItemName = "GameObject/Export To FBX...";
const string ProgressBarTitle = "FBX Export";
const char MayaNamespaceSeparator = ':';
// replace invalid chars with this one
const char InvalidCharReplacement = '_';
const string RegexCharStart = "[";
const string RegexCharEnd = "]";
internal const float UnitScaleFactor = 100f;
internal const string PACKAGE_UI_NAME = "FBX Exporter";
/// <summary>
/// name of the scene's default camera
/// </summary>
private static string DefaultCamera = "";
private const string SkeletonPrefix = "_Skel";
private const string SkinPrefix = "_Skin";
/// <summary>
/// name prefix for custom properties
/// </summary>
const string NamePrefix = "Unity_";
private static string MakeName(string basename)
{
return NamePrefix + basename;
}
/// <summary>
/// Create instance of exporter.
/// </summary>
static ModelExporter Create()
{
return new ModelExporter();
}
/// <summary>
/// Which components map from Unity Object to Fbx Object
/// </summary>
internal enum FbxNodeRelationType
{
NodeAttribute,
Property,
Material
}
internal static Dictionary<System.Type, KeyValuePair<System.Type, FbxNodeRelationType>> MapsToFbxObject = new Dictionary<System.Type, KeyValuePair<System.Type, FbxNodeRelationType>>()
{
{ typeof(Transform), new KeyValuePair<System.Type, FbxNodeRelationType>(typeof(FbxProperty), FbxNodeRelationType.Property) },
{ typeof(MeshFilter), new KeyValuePair<System.Type, FbxNodeRelationType>(typeof(FbxMesh), FbxNodeRelationType.NodeAttribute) },
{ typeof(SkinnedMeshRenderer), new KeyValuePair<System.Type, FbxNodeRelationType>(typeof(FbxMesh), FbxNodeRelationType.NodeAttribute) },
{ typeof(Light), new KeyValuePair<System.Type, FbxNodeRelationType>(typeof(FbxLight), FbxNodeRelationType.NodeAttribute) },
{ typeof(Camera), new KeyValuePair<System.Type, FbxNodeRelationType>(typeof(FbxCamera), FbxNodeRelationType.NodeAttribute) },
{ typeof(Material), new KeyValuePair<System.Type, FbxNodeRelationType>(typeof(FbxSurfaceMaterial), FbxNodeRelationType.Material) },
};
/// <summary>
/// keep a map between GameObject and FbxNode for quick lookup when we export
/// animation.
/// </summary>
Dictionary<GameObject, FbxNode> MapUnityObjectToFbxNode = new Dictionary<GameObject, FbxNode>();
/// <summary>
/// keep a map between the constrained FbxNode (in Unity this is the GameObject with constraint component)
/// and its FbxConstraints for quick lookup when exporting constraint animations.
/// </summary>
Dictionary<FbxNode, Dictionary<FbxConstraint, System.Type>> MapConstrainedObjectToConstraints = new Dictionary<FbxNode, Dictionary<FbxConstraint, System.Type>>();
/// <summary>
/// keep a map between the FbxNode and its blendshape channels for quick lookup when exporting blendshapes.
/// </summary>
Dictionary<FbxNode, List<FbxBlendShapeChannel>> MapUnityObjectToBlendShapes = new Dictionary<FbxNode, List<FbxBlendShapeChannel>>();
/// <summary>
/// Map Unity material ID to FBX material object
/// </summary>
Dictionary<int, FbxSurfaceMaterial> MaterialMap = new Dictionary<int, FbxSurfaceMaterial>();
/// <summary>
/// Map texture properties to FBX texture object
/// </summary>
Dictionary<(Texture unityTexture, Vector2 offset, Vector2 scale, TextureWrapMode wrapModeU, TextureWrapMode wrapModeV), FbxFileTexture> TextureMap =
new Dictionary<(Texture unityTexture, Vector2 offset, Vector2 scale, TextureWrapMode wrapModeU, TextureWrapMode wrapModeV), FbxFileTexture>();
/// <summary>
/// Map a Unity mesh to an fbx node (for preserving instances)
/// </summary>
Dictionary<Mesh, FbxNode> SharedMeshes = new Dictionary<Mesh, FbxNode>();
/// <summary>
/// Map for the Name of an Object to number of objects with this name.
/// Used for enforcing unique names on export.
/// </summary>
Dictionary<string, int> NameToIndexMap = new Dictionary<string, int>();
/// <summary>
/// Map for the Material Name to number of materials with this name.
/// Used for enforcing unique names on export.
/// </summary>
Dictionary<string, int> MaterialNameToIndexMap = new Dictionary<string, int>();
/// <summary>
/// Map for the Texture Name to number of textures with this name.
/// Used for enforcing unique names on export.
/// </summary>
Dictionary<string, int> TextureNameToIndexMap = new Dictionary<string, int>();
/// <summary>
/// Format for creating unique names
/// </summary>
const string UniqueNameFormat = "{0}_{1}";
/// <summary>
/// The animation fbx file format.
/// </summary>
const string AnimFbxFileFormat = "{0}/{1}@{2}.fbx";
/// <summary>
/// Gets the export settings.
/// </summary>
internal static ExportSettings ExportSettings
{
get { return ExportSettings.instance; }
}
internal static IExportOptions DefaultOptions
{
get { return new ExportModelSettingsSerialize(); }
}
private IExportOptions m_exportOptions;
private IExportOptions ExportOptions
{
get
{
if (m_exportOptions == null)
{
// get default settings;
m_exportOptions = DefaultOptions;
}
return m_exportOptions;
}
set { m_exportOptions = value; }
}
/// <summary>
/// Gets the Unity default material.
/// </summary>
internal static Material DefaultMaterial
{
get
{
if (!s_defaultMaterial)
{
var obj = GameObject.CreatePrimitive(PrimitiveType.Quad);
s_defaultMaterial = obj.GetComponent<Renderer>().sharedMaterial;
Object.DestroyImmediate(obj);
}
return s_defaultMaterial;
}
}
static Material s_defaultMaterial = null;
static Dictionary<UnityEngine.LightType, FbxLight.EType> MapLightType = new Dictionary<UnityEngine.LightType, FbxLight.EType>()
{
{ UnityEngine.LightType.Directional, FbxLight.EType.eDirectional },
{ UnityEngine.LightType.Spot, FbxLight.EType.eSpot },
{ UnityEngine.LightType.Point, FbxLight.EType.ePoint },
{ UnityEngine.LightType.Rectangle, FbxLight.EType.eArea },
};
/// <summary>
/// Gets the version number of the FbxExporters plugin from the readme.
/// </summary>
internal static string GetVersionFromReadme()
{
if (!File.Exists(ChangeLogPath))
{
Debug.LogWarning(string.Format("Could not find version number, the ChangeLog file is missing from: {0}", ChangeLogPath));
return null;
}
try
{
// The standard format is:
// ## [a.b.c-whatever] - yyyy-mm-dd
// Another format is:
// **Version**: a.b.c-whatever
// we handle either one and read out the version
var lines = File.ReadAllLines(ChangeLogPath);
var regexes = new string[]
{
@"^\s*##\s*\[(.*)\]",
@"^\s*\*\*Version\*\*:\s*(.*)\s*"
};
foreach (var line in lines)
{
foreach (var regex in regexes)
{
var match = System.Text.RegularExpressions.Regex.Match(line, regex);
if (match.Success)
{
var version = match.Groups[1].Value;
return version.Trim();
}
}
}
// If we're here, we didn't find any match.
Debug.LogWarning(string.Format("Could not find most recent version number in {0}", ChangeLogPath));
return null;
}
catch (IOException e)
{
Debug.LogException(e);
Debug.LogWarning(string.Format("Error reading file {0} ({1})", ChangeLogPath, e));
return null;
}
}
/// <summary>
/// Get a layer (to store UVs, normals, etc) on the mesh.
/// If it doesn't exist yet, create it.
/// </summary>
internal static FbxLayer GetOrCreateLayer(FbxMesh fbxMesh, int layer = 0 /* default layer */)
{
int maxLayerIndex = fbxMesh.GetLayerCount() - 1;
while (layer > maxLayerIndex)
{
// We'll have to create the layer (potentially several).
// Make sure to avoid infinite loops even if there's an
// FbxSdk bug.
int newLayerIndex = fbxMesh.CreateLayer();
if (newLayerIndex <= maxLayerIndex)
{
// Error!
throw new ModelExportException(
"Internal error: Unable to create mesh layer "
+ (maxLayerIndex + 1)
+ " on mesh " + fbxMesh.GetName());
}
maxLayerIndex = newLayerIndex;
}
return fbxMesh.GetLayer(layer);
}
/// <summary>
/// Export the mesh's attributes using layer 0.
/// </summary>
private bool ExportComponentAttributes(MeshInfo mesh, FbxMesh fbxMesh, int[] unmergedTriangles)
{
// return true if any attribute was exported
bool exportedAttribute = false;
// Set the normals on Layer 0.
FbxLayer fbxLayer = GetOrCreateLayer(fbxMesh);
if (mesh.HasValidNormals())
{
using (var fbxLayerElement = FbxLayerElementNormal.Create(fbxMesh, "Normals"))
{
fbxLayerElement.SetMappingMode(FbxLayerElement.EMappingMode.eByPolygonVertex);
fbxLayerElement.SetReferenceMode(FbxLayerElement.EReferenceMode.eDirect);
// Add one normal per each vertex face index (3 per triangle)
FbxLayerElementArray fbxElementArray = fbxLayerElement.GetDirectArray();
for (int n = 0; n < unmergedTriangles.Length; n++)
{
int unityTriangle = unmergedTriangles[n];
fbxElementArray.Add(ConvertToFbxVector4(mesh.Normals[unityTriangle]));
}
fbxLayer.SetNormals(fbxLayerElement);
}
exportedAttribute = true;
}
/// Set the binormals on Layer 0.
if (mesh.HasValidBinormals())
{
using (var fbxLayerElement = FbxLayerElementBinormal.Create(fbxMesh, "Binormals"))
{
fbxLayerElement.SetMappingMode(FbxLayerElement.EMappingMode.eByPolygonVertex);
fbxLayerElement.SetReferenceMode(FbxLayerElement.EReferenceMode.eDirect);
// Add one normal per each vertex face index (3 per triangle)
FbxLayerElementArray fbxElementArray = fbxLayerElement.GetDirectArray();
for (int n = 0; n < unmergedTriangles.Length; n++)
{
int unityTriangle = unmergedTriangles[n];
fbxElementArray.Add(ConvertToFbxVector4(mesh.Binormals[unityTriangle]));
}
fbxLayer.SetBinormals(fbxLayerElement);
}
exportedAttribute = true;
}
/// Set the tangents on Layer 0.
if (mesh.HasValidTangents())
{
using (var fbxLayerElement = FbxLayerElementTangent.Create(fbxMesh, "Tangents"))
{
fbxLayerElement.SetMappingMode(FbxLayerElement.EMappingMode.eByPolygonVertex);
fbxLayerElement.SetReferenceMode(FbxLayerElement.EReferenceMode.eDirect);
// Add one normal per each vertex face index (3 per triangle)
FbxLayerElementArray fbxElementArray = fbxLayerElement.GetDirectArray();
for (int n = 0; n < unmergedTriangles.Length; n++)
{
int unityTriangle = unmergedTriangles[n];
fbxElementArray.Add(ConvertToFbxVector4(
new Vector3(
mesh.Tangents[unityTriangle][0],
mesh.Tangents[unityTriangle][1],
mesh.Tangents[unityTriangle][2]
)
));
}
fbxLayer.SetTangents(fbxLayerElement);
}
exportedAttribute = true;
}
exportedAttribute |= ExportUVs(fbxMesh, mesh, unmergedTriangles);
if (mesh.HasValidVertexColors())
{
using (var fbxLayerElement = FbxLayerElementVertexColor.Create(fbxMesh, "VertexColors"))
{
fbxLayerElement.SetMappingMode(FbxLayerElement.EMappingMode.eByPolygonVertex);
fbxLayerElement.SetReferenceMode(FbxLayerElement.EReferenceMode.eIndexToDirect);
// set texture coordinates per vertex
FbxLayerElementArray fbxElementArray = fbxLayerElement.GetDirectArray();
// (Uni-31596) only copy unique UVs into this array, and index appropriately
for (int n = 0; n < mesh.VertexColors.Length; n++)
{
// Converting to Color from Color32, as Color32 stores the colors
// as ints between 0-255, while FbxColor and Color
// use doubles between 0-1
Color color = mesh.VertexColors[n];
fbxElementArray.Add(new FbxColor(color.r,
color.g,
color.b,
color.a));
}
// For each face index, point to a texture uv
FbxLayerElementArray fbxIndexArray = fbxLayerElement.GetIndexArray();
fbxIndexArray.SetCount(unmergedTriangles.Length);
for (int i = 0; i < unmergedTriangles.Length; i++)
{
fbxIndexArray.SetAt(i, unmergedTriangles[i]);
}
fbxLayer.SetVertexColors(fbxLayerElement);
}
exportedAttribute = true;
}
return exportedAttribute;
}
/// <summary>
/// Unity has up to 4 uv sets per mesh. Export all the ones that exist.
/// </summary>
/// <param name="fbxMesh">Fbx mesh.</param>
/// <param name="mesh">Mesh.</param>
/// <param name="unmergedTriangles">Unmerged triangles.</param>
private static bool ExportUVs(FbxMesh fbxMesh, MeshInfo meshInfo, int[] unmergedTriangles)
{
var mesh = meshInfo.mesh;
List<Vector2> uvs = new List<Vector2>();
int k = 0;
for (int i = 0; i < 8; i++)
{
mesh.GetUVs(i, uvs);
if (uvs == null || uvs.Count == 0)
{
continue; // don't have these UV's, so skip
}
FbxLayer fbxLayer = GetOrCreateLayer(fbxMesh, k);
using (var fbxLayerElement = FbxLayerElementUV.Create(fbxMesh, "UVSet" + i))
{
fbxLayerElement.SetMappingMode(FbxLayerElement.EMappingMode.eByPolygonVertex);
fbxLayerElement.SetReferenceMode(FbxLayerElement.EReferenceMode.eIndexToDirect);
// set texture coordinates per vertex
FbxLayerElementArray fbxElementArray = fbxLayerElement.GetDirectArray();
// (Uni-31596) only copy unique UVs into this array, and index appropriately
for (int n = 0; n < uvs.Count; n++)
{
fbxElementArray.Add(new FbxVector2(uvs[n][0],
uvs[n][1]));
}
// For each face index, point to a texture uv
FbxLayerElementArray fbxIndexArray = fbxLayerElement.GetIndexArray();
fbxIndexArray.SetCount(unmergedTriangles.Length);
for (int j = 0; j < unmergedTriangles.Length; j++)
{
fbxIndexArray.SetAt(j, unmergedTriangles[j]);
}
fbxLayer.SetUVs(fbxLayerElement, FbxLayerElement.EType.eTextureDiffuse);
}
k++;
uvs.Clear();
}
// if we incremented k, then at least on set of UV's were exported
return k > 0;
}
/// <summary>
/// Export the mesh's blend shapes.
/// </summary>
private FbxBlendShape ExportBlendShapes(MeshInfo mesh, FbxMesh fbxMesh, FbxScene fbxScene, int[] unmergedTriangles)
{
var umesh = mesh.mesh;
if (umesh.blendShapeCount == 0)
return null;
var fbxBlendShape = FbxBlendShape.Create(fbxScene, umesh.name + "_BlendShape");
fbxMesh.AddDeformer(fbxBlendShape);
var numVertices = umesh.vertexCount;
var basePoints = umesh.vertices;
var baseNormals = umesh.normals;
var baseTangents = umesh.tangents;
var deltaPoints = new Vector3[numVertices];
var deltaNormals = new Vector3[numVertices];
var deltaTangents = new Vector3[numVertices];
for (int bi = 0; bi < umesh.blendShapeCount; ++bi)
{
var bsName = umesh.GetBlendShapeName(bi);
var numFrames = umesh.GetBlendShapeFrameCount(bi);
var fbxChannel = FbxBlendShapeChannel.Create(fbxScene, bsName);
fbxBlendShape.AddBlendShapeChannel(fbxChannel);
for (int fi = 0; fi < numFrames; ++fi)
{
var weight = umesh.GetBlendShapeFrameWeight(bi, fi);
umesh.GetBlendShapeFrameVertices(bi, fi, deltaPoints, deltaNormals, deltaTangents);
var fbxShapeName = bsName;
if (numFrames > 1)
{
fbxShapeName += "_" + fi;
}
var fbxShape = FbxShape.Create(fbxScene, fbxShapeName);
fbxChannel.AddTargetShape(fbxShape, weight);
// control points
fbxShape.InitControlPoints(ControlPointToIndex.Count);
for (int vi = 0; vi < numVertices; ++vi)
{
int ni = ControlPointToIndex[basePoints[vi]];
var v = basePoints[vi] + deltaPoints[vi];
fbxShape.SetControlPointAt(ConvertToFbxVector4(v, UnitScaleFactor), ni);
}
// normals
if (mesh.HasValidNormals())
{
var elemNormals = fbxShape.CreateElementNormal();
elemNormals.SetMappingMode(FbxLayerElement.EMappingMode.eByPolygonVertex);
elemNormals.SetReferenceMode(FbxLayerElement.EReferenceMode.eDirect);
var dstNormals = elemNormals.GetDirectArray();
dstNormals.SetCount(unmergedTriangles.Length);
for (int ii = 0; ii < unmergedTriangles.Length; ++ii)
{
int vi = unmergedTriangles[ii];
var n = baseNormals[vi] + deltaNormals[vi];
dstNormals.SetAt(ii, ConvertToFbxVector4(n));
}
}
// tangents
if (mesh.HasValidTangents())
{
var elemTangents = fbxShape.CreateElementTangent();
elemTangents.SetMappingMode(FbxLayerElement.EMappingMode.eByPolygonVertex);
elemTangents.SetReferenceMode(FbxLayerElement.EReferenceMode.eDirect);
var dstTangents = elemTangents.GetDirectArray();
dstTangents.SetCount(unmergedTriangles.Length);
for (int ii = 0; ii < unmergedTriangles.Length; ++ii)
{
int vi = unmergedTriangles[ii];
var t = (Vector3)baseTangents[vi] + deltaTangents[vi];
dstTangents.SetAt(ii, ConvertToFbxVector4(t));
}
}
}
}
return fbxBlendShape;
}
/// <summary>
/// Takes in a left-handed UnityEngine.Vector3 denoting a normal,
/// returns a right-handed FbxVector4.
///
/// Unity is left-handed, Maya and Max are right-handed.
/// The FbxSdk conversion routines can't handle changing handedness.
///
/// Remember you also need to flip the winding order on your polygons.
/// </summary>
internal static FbxVector4 ConvertToFbxVector4(Vector3 leftHandedVector, float unitScale = 1f)
{
// negating the x component of the vector converts it from left to right handed coordinates
return unitScale * new FbxVector4(
leftHandedVector[0],
leftHandedVector[1],
leftHandedVector[2]);
}
/// <summary>
/// Exports a texture from Unity to FBX.
/// The texture must be a property on the unityMaterial; it gets
/// linked to the FBX via a property on the fbxMaterial.
///
/// The texture file must be a file on disk; it is not embedded within the FBX.
/// </summary>
/// <param name="unityMaterial">Unity material.</param>
/// <param name="unityPropName">Unity property name, e.g. "_MainTex".</param>
/// <param name="fbxMaterial">Fbx material.</param>
/// <param name="fbxPropName">Fbx property name, e.g. <c>FbxSurfaceMaterial.sDiffuse</c>.</param>
internal bool ExportTexture(Material unityMaterial, string unityPropName,
FbxSurfaceMaterial fbxMaterial, string fbxPropName)
{
if (!unityMaterial)
{
return false;
}
// Get the texture on this property, if any.
if (!unityMaterial.HasProperty(unityPropName))
{
return false;
}
var unityTexture = unityMaterial.GetTexture(unityPropName);
if (!unityTexture)
{
return false;
}
// Find its filename
var textureSourceFullPath = AssetDatabase.GetAssetPath(unityTexture);
if (string.IsNullOrEmpty(textureSourceFullPath))
{
return false;
}
// get absolute filepath to texture
textureSourceFullPath = Path.GetFullPath(textureSourceFullPath);
if (Verbose)
{
Debug.Log(string.Format("{2}.{1} setting texture path {0}", textureSourceFullPath, fbxPropName, fbxMaterial.GetName()));
}
// Find the corresponding property on the fbx material.
var fbxMaterialProperty = fbxMaterial.FindProperty(fbxPropName);
if (fbxMaterialProperty == null || !fbxMaterialProperty.IsValid())
{
Debug.Log("property not found");
return false;
}
var offset = unityMaterial.GetTextureOffset(unityPropName);
var scale = unityMaterial.GetTextureScale(unityPropName);
var wrapModeU = unityTexture.wrapModeU;
var wrapModeV = unityTexture.wrapModeV;
var tuple = (unityTexture, offset, scale, wrapModeU, wrapModeV);
FbxFileTexture fbxTexture;
// Find or create an fbx texture and link it up to the fbx material.
if (!TextureMap.TryGetValue(tuple, out fbxTexture))
{
var textureName = GetUniqueTextureName(fbxPropName + "_Texture");
fbxTexture = FbxFileTexture.Create(fbxMaterial, textureName);
fbxTexture.SetFileName(textureSourceFullPath);
fbxTexture.SetTextureUse(FbxTexture.ETextureUse.eStandard);
fbxTexture.SetMappingType(FbxTexture.EMappingType.eUV);
fbxTexture.SetScale(scale.x, scale.y);
fbxTexture.SetTranslation(offset.x, offset.y);
fbxTexture.SetWrapMode(GetWrapModeFromUnityWrapMode(wrapModeU, unityMaterial.name, unityPropName),
GetWrapModeFromUnityWrapMode(wrapModeV, unityMaterial.name, unityPropName));
TextureMap.Add(tuple, fbxTexture);
}
fbxTexture.ConnectDstProperty(fbxMaterialProperty);
return true;
}
private FbxTexture.EWrapMode GetWrapModeFromUnityWrapMode(TextureWrapMode wrapMode, string materialName, string textureName)
{
switch (wrapMode)
{
case TextureWrapMode.Clamp: return FbxTexture.EWrapMode.eClamp;
case TextureWrapMode.Repeat: return FbxTexture.EWrapMode.eRepeat;
default:
Debug.LogWarning($"Texture {textureName} on material {materialName} uses wrap mode {wrapMode} which is not supported by FBX. Will be exported as \"Repeat\".");
return FbxTexture.EWrapMode.eRepeat;
}
}
/// <summary>
/// Get the color of a material, or grey if we can't find it.
/// </summary>
internal FbxDouble3 GetMaterialColor(Material unityMaterial, string unityPropName, float defaultValue = 1)
{
if (!unityMaterial)
{
return new FbxDouble3(defaultValue);
}
if (!unityMaterial.HasProperty(unityPropName))
{
return new FbxDouble3(defaultValue);
}
var unityColor = unityMaterial.GetColor(unityPropName);
return new FbxDouble3(unityColor.r, unityColor.g, unityColor.b);
}
/// <summary>
/// Export (and map) a Unity PBS material to FBX classic material
/// </summary>
internal bool ExportMaterial(Material unityMaterial, FbxScene fbxScene, FbxNode fbxNode)
{
if (!unityMaterial)
{
unityMaterial = DefaultMaterial;
}
var unityID = unityMaterial.GetInstanceID();
FbxSurfaceMaterial mappedMaterial;
if (MaterialMap.TryGetValue(unityID, out mappedMaterial))
{
fbxNode.AddMaterial(mappedMaterial);
return true;
}
var unityName = unityMaterial.name;
var fbxName = ExportOptions.UseMayaCompatibleNames
? ConvertToMayaCompatibleName(unityName) : unityName;
fbxName = GetUniqueMaterialName(fbxName);
if (Verbose)
{
if (unityName != fbxName)
{
Debug.Log(string.Format("exporting material {0} as {1}", unityName, fbxName));
}
else
{
Debug.Log(string.Format("exporting material {0}", unityName));
}
}
// We'll export either Phong or Lambert. Phong if it calls
// itself specular, Lambert otherwise.
System.StringComparison stringComparison = System.StringComparison.OrdinalIgnoreCase;
var shader = unityMaterial.shader;
bool specular = shader.name.IndexOf("specular", stringComparison) >= 0;
bool hdrp = shader.name.IndexOf("hdrp", stringComparison) >= 0;
var fbxMaterial = specular
? FbxSurfacePhong.Create(fbxScene, fbxName)
: FbxSurfaceLambert.Create(fbxScene, fbxName);
// Copy the flat colours over from Unity standard materials to FBX.
fbxMaterial.Diffuse.Set(GetMaterialColor(unityMaterial, "_Color"));
fbxMaterial.Emissive.Set(GetMaterialColor(unityMaterial, "_EmissionColor", 0));
// hdrp materials dont export emission properly, so default to 0
if (hdrp)
{
fbxMaterial.Emissive.Set(new FbxDouble3(0, 0, 0));
}
fbxMaterial.Ambient.Set(new FbxDouble3());
fbxMaterial.BumpFactor.Set(unityMaterial.HasProperty("_BumpScale") ? unityMaterial.GetFloat("_BumpScale") : 0);
if (specular)
{
(fbxMaterial as FbxSurfacePhong).Specular.Set(GetMaterialColor(unityMaterial, "_SpecColor"));
}
// Export the textures from Unity standard materials to FBX.
ExportTexture(unityMaterial, "_MainTex", fbxMaterial, FbxSurfaceMaterial.sDiffuse);
ExportTexture(unityMaterial, "_EmissionMap", fbxMaterial, FbxSurfaceMaterial.sEmissive);
ExportTexture(unityMaterial, "_BumpMap", fbxMaterial, FbxSurfaceMaterial.sNormalMap);
if (specular)
{
ExportTexture(unityMaterial, "_SpecGlossMap", fbxMaterial, FbxSurfaceMaterial.sSpecular);
}
MaterialMap.Add(unityID, fbxMaterial);
fbxNode.AddMaterial(fbxMaterial);
return true;
}
/// <summary>
/// Sets up the material to polygon mapping for fbxMesh.
/// To determine which part of the mesh uses which material, look at the submeshes
/// and which polygons they represent.
/// Assuming equal number of materials as submeshes, and that they are in the same order.
/// (i.e. submesh 1 uses material 1)
/// </summary>
/// <param name="fbxMesh">Fbx mesh.</param>
/// <param name="mesh">Mesh.</param>
/// <param name="materials">Materials.</param>
private void AssignLayerElementMaterial(FbxMesh fbxMesh, Mesh mesh, int materialCount)
{
// Add FbxLayerElementMaterial to layer 0 of the node
FbxLayer fbxLayer = fbxMesh.GetLayer(0 /* default layer */);
if (fbxLayer == null)
{
fbxMesh.CreateLayer();
fbxLayer = fbxMesh.GetLayer(0 /* default layer */);
}
using (var fbxLayerElement = FbxLayerElementMaterial.Create(fbxMesh, "Material"))
{
// if there is only one material then set everything to that material
if (materialCount == 1)
{
fbxLayerElement.SetMappingMode(FbxLayerElement.EMappingMode.eAllSame);
fbxLayerElement.SetReferenceMode(FbxLayerElement.EReferenceMode.eIndexToDirect);
FbxLayerElementArray fbxElementArray = fbxLayerElement.GetIndexArray();
fbxElementArray.Add(0);
}
else
{
fbxLayerElement.SetMappingMode(FbxLayerElement.EMappingMode.eByPolygon);
fbxLayerElement.SetReferenceMode(FbxLayerElement.EReferenceMode.eIndexToDirect);
FbxLayerElementArray fbxElementArray = fbxLayerElement.GetIndexArray();
for (int subMeshIndex = 0; subMeshIndex < mesh.subMeshCount; subMeshIndex++)
{
var topology = mesh.GetTopology(subMeshIndex);
int polySize;
switch (topology)
{
case MeshTopology.Triangles:
polySize = 3;
break;
case MeshTopology.Quads:
polySize = 4;
break;
case MeshTopology.Lines:
throw new System.NotImplementedException();
case MeshTopology.Points:
throw new System.NotImplementedException();
case MeshTopology.LineStrip:
throw new System.NotImplementedException();
default:
throw new System.NotImplementedException();
}
// Specify the material index for each polygon.
// Material index should match subMeshIndex.
var indices = mesh.GetIndices(subMeshIndex);
for (int j = 0, n = indices.Length / polySize; j < n; j++)
{
fbxElementArray.Add(subMeshIndex);
}
}
}
fbxLayer.SetMaterials(fbxLayerElement);
}
}
/// <summary>
/// Exports a unity mesh and attaches it to the node as an FbxMesh.
///
/// Able to export materials per sub-mesh as well (by default, exports with the default material).
///
/// Use fbxNode.GetMesh() to access the exported mesh.
/// </summary>
internal bool ExportMesh(Mesh mesh, FbxNode fbxNode, Material[] materials = null)
{
var meshInfo = new MeshInfo(mesh, materials);
return ExportMesh(meshInfo, fbxNode);
}
/// <summary>
/// Keeps track of the index of each point in the exported vertex array.
/// </summary>
private Dictionary<Vector3, int> ControlPointToIndex = new Dictionary<Vector3, int>();
/// <summary>
/// Exports a unity mesh and attaches it to the node as an FbxMesh.
/// </summary>
bool ExportMesh(MeshInfo meshInfo, FbxNode fbxNode)
{
if (!meshInfo.IsValid)
{
return false;
}
NumMeshes++;
NumTriangles += meshInfo.Triangles.Length / 3;
// create the mesh structure.
var fbxScene = fbxNode.GetScene();
FbxMesh fbxMesh = FbxMesh.Create(fbxScene, "Scene");
// Create control points.
ControlPointToIndex.Clear();
{
var vertices = meshInfo.Vertices;
for (int v = 0, n = meshInfo.VertexCount; v < n; v++)
{
if (ControlPointToIndex.ContainsKey(vertices[v]))
{
continue;
}
ControlPointToIndex[vertices[v]] = ControlPointToIndex.Count;
}
fbxMesh.InitControlPoints(ControlPointToIndex.Count);
foreach (var kvp in ControlPointToIndex)
{
var controlPoint = kvp.Key;
var index = kvp.Value;
fbxMesh.SetControlPointAt(ConvertToFbxVector4(controlPoint, UnitScaleFactor), index);
}
}
var unmergedPolygons = new List<int>();
var mesh = meshInfo.mesh;
for (int s = 0; s < mesh.subMeshCount; s++)
{
var topology = mesh.GetTopology(s);
var indices = mesh.GetIndices(s);
int polySize;
int[] vertOrder;
switch (topology)
{
case MeshTopology.Triangles:
polySize = 3;
vertOrder = new int[] { 0, 1, 2 };
break;
case MeshTopology.Quads:
polySize = 4;
vertOrder = new int[] { 0, 1, 2, 3 };
break;
case MeshTopology.Lines:
throw new System.NotImplementedException();
case MeshTopology.Points:
throw new System.NotImplementedException();
case MeshTopology.LineStrip:
throw new System.NotImplementedException();
default:
throw new System.NotImplementedException();
}
for (int f = 0; f < indices.Length / polySize; f++)
{
fbxMesh.BeginPolygon();
foreach (int val in vertOrder)
{
int polyVert = indices[polySize * f + val];
// Save the polygon order (without merging vertices) so we
// properly export UVs, normals, binormals, etc.
unmergedPolygons.Add(polyVert);
polyVert = ControlPointToIndex[meshInfo.Vertices[polyVert]];
fbxMesh.AddPolygon(polyVert);
}
fbxMesh.EndPolygon();
}
}
// Set up materials per submesh.
foreach (var mat in meshInfo.Materials)
{
ExportMaterial(mat, fbxScene, fbxNode);
}
AssignLayerElementMaterial(fbxMesh, meshInfo.mesh, meshInfo.Materials.Length);
// Set up normals, etc.
ExportComponentAttributes(meshInfo, fbxMesh, unmergedPolygons.ToArray());