-
Notifications
You must be signed in to change notification settings - Fork 308
/
BabylonExporter.Mesh.cs
1401 lines (1206 loc) · 64.5 KB
/
BabylonExporter.Mesh.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 Autodesk.Max;
using BabylonExport.Entities;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using Newtonsoft.Json.Linq;
using System.Globalization;
using Utilities;
namespace Max2Babylon
{
partial class BabylonExporter
{
private bool isMaterialDoubleSided;
private bool IsMeshExportable(IIGameNode meshNode)
{
if (!IsNodeExportable(meshNode))
{
return false;
}
if (exportParameters.exportAnimationsOnly)
{
var gameMesh = meshNode.IGameObject.AsGameMesh();
try
{
bool initialized = gameMesh.InitializeData; // needed, the property is in fact a method initializing the exporter that has wrongly been auto
// translated into a property because it has no parameters
}
catch (Exception e)
{
RaiseWarning($"Mesh {meshNode.Name} failed to initialize.", 2);
}
if (!isAnimated(meshNode))
{
return false;
}
}
return true;
}
private BabylonNode ExportDummy(IIGameScene scene, IIGameNode meshNode, BabylonScene babylonScene)
{
RaiseMessage(meshNode.Name, 1);
var babylonMesh = new BabylonMesh { name = meshNode.Name, id = meshNode.MaxNode.GetGuid().ToString() };
babylonMesh.isDummy = true;
// Position / rotation / scaling / hierarchy
exportNode(babylonMesh, meshNode, scene, babylonScene);
// Animations
exportAnimation(babylonMesh, meshNode);
babylonScene.MeshesList.Add(babylonMesh);
return babylonMesh;
}
private BabylonNode ExportDummy(BabylonNode babylonNode, BabylonScene babylonScene)
{
var babylonMesh = new BabylonMesh { name = babylonNode.name, id = babylonNode.id };
babylonMesh.isDummy = true;
// Position / rotation / scaling / hierarchy
babylonMesh.parentId = babylonNode.parentId;
babylonMesh.position = babylonNode.position;
babylonMesh.rotation = babylonNode.rotation;
babylonMesh.rotationQuaternion = babylonNode.rotationQuaternion;
babylonMesh.scaling = babylonNode.scaling;
// Animations
babylonMesh.animations = babylonNode.animations;
babylonMesh.extraAnimations = babylonNode.extraAnimations;
babylonMesh.autoAnimate = babylonNode.autoAnimate;
babylonMesh.autoAnimateFrom = babylonNode.autoAnimateFrom;
babylonMesh.autoAnimateTo = babylonNode.autoAnimateTo;
babylonMesh.autoAnimateLoop = babylonNode.autoAnimateLoop;
babylonScene.MeshesList.Add(babylonMesh);
return babylonMesh;
}
Dictionary<BabylonMesh, IIGameNode> masterMeshMap = new Dictionary<BabylonMesh, IIGameNode>();
private BabylonNode ExportMesh(IIGameScene scene, IIGameNode meshNode, BabylonScene babylonScene)
{
if (IsMeshExportable(meshNode) == false)
{
return null;
}
RaiseMessage(meshNode.Name, 1);
// Instances
#if MAX2020 || MAX2021 || MAX2022 || MAX2023
var tabs = Loader.Global.INodeTab.Create();
#else
var tabs = Loader.Global.NodeTab.Create();
#endif
Loader.Global.IInstanceMgr.InstanceMgr.GetInstances(meshNode.MaxNode, tabs);
if (tabs.Count > 1)
{
// For a mesh with instances, we distinguish between master and instance meshes:
// - a master mesh stores all the info of the mesh (transform, hierarchy, animations + vertices, indices, materials, bones...)
// - an instance mesh only stores the info of the node (transform, hierarchy, animations)
// Check if this mesh has already been exported
for (int index = 0; index < tabs.Count; index++)
{
#if MAX2017 || MAX2018 || MAX2019 || MAX2020 || MAX2021 || MAX2022 || MAX2023
var tab = tabs[index];
#else
var tab = tabs[new IntPtr(index)];
#endif
var tabGuid = tab.GetGuid().ToString();
foreach (var masterMeshPair in masterMeshMap)
{
// Check if we need to export this instance as an instance mesh.
if (tabGuid == masterMeshPair.Key.id)
{
bool isShareMat = masterMeshPair.Key.materialId == null || (meshNode.NodeMaterial != null && meshNode.NodeMaterial.MaxMaterial.GetGuid().ToString().Equals(masterMeshPair.Value.NodeMaterial.MaxMaterial.GetGuid().ToString()));
BabylonNode n = isShareMat?
ExportInstanceMesh(scene, meshNode, babylonScene, masterMeshPair.Key, masterMeshPair.Value) :
exportParameters.useClone ? ExportCloneMesh(scene, meshNode, babylonScene, masterMeshPair.Key, masterMeshPair.Value) : null;
if( n != null)
{
return n;
}
}
}
}
}
return ExportMasterMesh(scene, meshNode, babylonScene);
}
private BabylonNode ExportMasterMesh(IIGameScene scene, IIGameNode meshNode, BabylonScene babylonScene)
{
var gameMesh = meshNode.IGameObject.AsGameMesh();
try
{
bool initialized = gameMesh.InitializeData; // needed, the property is in fact a method initializing the exporter that has wrongly been auto
// translated into a property because it has no parameters
}
catch (Exception e)
{
RaiseWarning($"Mesh {meshNode.Name} failed to initialize. Mesh is exported as dummy.", 2);
return ExportDummy(scene, meshNode, babylonScene);
}
var babylonMesh = new BabylonMesh { name = meshNode.Name, id = meshNode.MaxNode.GetGuid().ToString() };
// Position / rotation / scaling / hierarchy
exportNode(babylonMesh, meshNode, scene, babylonScene);
// Export the custom attributes of this mesh
babylonMesh.metadata = ExportExtraAttributes(meshNode, babylonScene);
// append userData to extras
ExportUserData(meshNode, babylonMesh);
// Sounds
var soundName = meshNode.MaxNode.GetStringProperty("babylonjs_sound_filename", "");
if (!string.IsNullOrEmpty(soundName))
{
var filename = Path.GetFileName(soundName);
var meshSound = new BabylonSound
{
name = filename,
autoplay = meshNode.MaxNode.GetBoolProperty("babylonjs_sound_autoplay", 1),
loop = meshNode.MaxNode.GetBoolProperty("babylonjs_sound_loop", 1),
volume = meshNode.MaxNode.GetFloatProperty("babylonjs_sound_volume", 1.0f),
playbackRate = meshNode.MaxNode.GetFloatProperty("babylonjs_sound_playbackrate", 1.0f),
connectedMeshId = babylonMesh.id,
isDirectional = false,
spatialSound = false,
distanceModel = meshNode.MaxNode.GetStringProperty("babylonjs_sound_distancemodel", "linear"),
maxDistance = meshNode.MaxNode.GetFloatProperty("babylonjs_sound_maxdistance", 100f),
rolloffFactor = meshNode.MaxNode.GetFloatProperty("babylonjs_sound_rolloff", 1.0f),
refDistance = meshNode.MaxNode.GetFloatProperty("babylonjs_sound_refdistance", 1.0f),
};
var isDirectional = meshNode.MaxNode.GetBoolProperty("babylonjs_sound_directional");
if (isDirectional)
{
meshSound.isDirectional = true;
meshSound.coneInnerAngle = meshNode.MaxNode.GetFloatProperty("babylonjs_sound_coneinnerangle", 360f);
meshSound.coneOuterAngle = meshNode.MaxNode.GetFloatProperty("babylonjs_sound_coneouterangle", 360f);
meshSound.coneOuterGain = meshNode.MaxNode.GetFloatProperty("babylonjs_sound_coneoutergain", 1.0f);
}
babylonScene.SoundsList.Add(meshSound);
if (isBabylonExported)
{
try
{
File.Copy(soundName, Path.Combine(babylonScene.OutputPath, filename), true);
}
catch
{
}
}
}
// Misc.
#if MAX2017 || MAX2018 || MAX2019 || MAX2020 || MAX2021 || MAX2022 || MAX2023
babylonMesh.isVisible = meshNode.MaxNode.Renderable;
babylonMesh.receiveShadows = meshNode.MaxNode.RcvShadows;
babylonMesh.applyFog = meshNode.MaxNode.ApplyAtmospherics;
#else
babylonMesh.isVisible = meshNode.MaxNode.Renderable == 1;
babylonMesh.receiveShadows = meshNode.MaxNode.RcvShadows == 1;
babylonMesh.applyFog = meshNode.MaxNode.ApplyAtmospherics == 1;
#endif
babylonMesh.pickable = meshNode.MaxNode.GetBoolProperty("babylonjs_checkpickable");
babylonMesh.showBoundingBox = meshNode.MaxNode.GetBoolProperty("babylonjs_showboundingbox");
babylonMesh.showSubMeshesBoundingBox = meshNode.MaxNode.GetBoolProperty("babylonjs_showsubmeshesboundingbox");
babylonMesh.alphaIndex = (int)meshNode.MaxNode.GetFloatProperty("babylonjs_alphaindex", 1000);
// Collisions
babylonMesh.checkCollisions = meshNode.MaxNode.GetBoolProperty("babylonjs_checkcollisions");
// Skin
var isSkinned = gameMesh.IsObjectSkinned;
var skin = gameMesh.IGameSkin;
var unskinnedMesh = gameMesh;
IGMatrix skinInitPoseMatrix = Loader.Global.GMatrix.Create(Loader.Global.Matrix3.Create(true));
List<int> boneIds = null;
int maxNbBones = 0;
List<IIGameNode> skinnedBones = GetSkinnedBones(skin).Item1;
if (isSkinned && skinnedBones.Count > 0) // if the mesh has a skin with at least one bone
{
var skinAlreadyStored = skins.Find(_skin => IsSkinEqualTo(_skin, skin));
if (skinAlreadyStored == null)
{
skins.Add(skin);
babylonMesh.skeletonId = skins.IndexOf(skin);
}
else
{
babylonMesh.skeletonId = skins.IndexOf(skinAlreadyStored);
}
skin.GetInitSkinTM(skinInitPoseMatrix);
boneIds = GetNodeIndices(skin);
}
else
{
skin = null;
}
// Mesh
if (unskinnedMesh.IGameType == Autodesk.Max.IGameObject.ObjectTypes.Mesh && unskinnedMesh.MaxMesh != null)
{
if (unskinnedMesh.NumberOfFaces < 1)
{
RaiseError($"Mesh {babylonMesh.name} has no face", 2);
}
if (unskinnedMesh.NumberOfVerts < 3)
{
RaiseError($"Mesh {babylonMesh.name} has not enough vertices", 2);
}
if (unskinnedMesh.NumberOfVerts >= 65536)
{
RaiseWarning($"Mesh {babylonMesh.name} has tmore than 65536 vertices which means that it will require specific WebGL extension to be rendered. This may impact portability of your scene on low end devices.", 2);
}
if (skin != null)
{
for (var vertexIndex = 0; vertexIndex < unskinnedMesh.NumberOfVerts; vertexIndex++)
{
maxNbBones = Math.Max(maxNbBones, skin.GetNumberOfBones(vertexIndex));
}
}
// Physics
var impostorText = meshNode.MaxNode.GetStringProperty("babylonjs_impostor", "None");
if (impostorText != "None")
{
switch (impostorText)
{
case "Sphere":
babylonMesh.physicsImpostor = 1;
break;
case "Box":
babylonMesh.physicsImpostor = 2;
break;
case "Plane":
babylonMesh.physicsImpostor = 3;
break;
default:
babylonMesh.physicsImpostor = 0;
break;
}
babylonMesh.physicsMass = meshNode.MaxNode.GetFloatProperty("babylonjs_mass");
babylonMesh.physicsFriction = meshNode.MaxNode.GetFloatProperty("babylonjs_friction", 0.2f);
babylonMesh.physicsRestitution = meshNode.MaxNode.GetFloatProperty("babylonjs_restitution", 0.2f);
}
// Material
var mtl = meshNode.NodeMaterial;
var multiMatsCount = 1;
// The DirectXShader material is a passthrough to its render material.
// The shell material is a passthrough to its baked material.
while (mtl != null && (isShellMaterial(mtl) || isDirectXShaderMaterial(mtl)))
{
if (isShellMaterial(mtl))
{
// Retrieve the baked material from the shell material.
mtl = GetBakedMaterialFromShellMaterial(mtl);
}
else // isDirectXShaderMaterial(mtl)
{
// Retrieve the render material from the directX shader
mtl = GetRenderMaterialFromDirectXShader(mtl);
}
}
isMaterialDoubleSided = false;
if (mtl != null)
{
IIGameMaterial unsupportedMaterial = isMaterialSupported(mtl);
if (unsupportedMaterial == null)
{
babylonMesh.materialId = mtl.MaxMaterial.GetGuid().ToString();
if (!referencedMaterials.Contains(mtl))
{
referencedMaterials.Add(mtl);
}
multiMatsCount = Math.Max(mtl.SubMaterialCount, 1);
if (isDoubleSidedMaterial(mtl))
{
isMaterialDoubleSided = true;
}
}
else
{
if (mtl.SubMaterialCount == 0 || mtl == unsupportedMaterial)
{
RaiseWarning("Unsupported material type '" + unsupportedMaterial.MaterialClass + "'. Material is ignored.", 2);
}
else
{
RaiseWarning("Unsupported sub-material type '" + unsupportedMaterial.MaterialClass + "'. Material is ignored.", 2);
}
}
}
babylonMesh.visibility = meshNode.MaxNode.GetVisibility(0, Tools.Forever);
var vertices = new List<GlobalVertex>();
var indices = new List<int>();
var mappingChannels = unskinnedMesh.ActiveMapChannelNum;
bool hasUV = false;
bool hasUV2 = false;
for (int i = 0; i < mappingChannels.Count; ++i)
{
#if MAX2017 || MAX2018 || MAX2019 || MAX2020 || MAX2021 || MAX2022 || MAX2023
var channelNum = mappingChannels[i];
#else
var channelNum = mappingChannels[new IntPtr(i)];
#endif
if (channelNum == 1)
{
hasUV = true;
}
else if (channelNum == 2)
{
hasUV2 = true;
}
}
var hasColor = unskinnedMesh.NumberOfColorVerts > 0;
var hasAlpha = unskinnedMesh.GetNumberOfMapVerts(-2) > 0;
bool quickExport = meshNode.MaxNode.GetBoolProperty("babylonjs_quickexport");
bool optimizeVertices = !quickExport;
var invertedWorldMatrix = GetInvertWorldTM(meshNode, 0);
var offsetTM = GetOffsetTM(meshNode, 0);
// Compute normals
var subMeshes = new List<BabylonSubMesh>();
List<int> faceIndexes = null;
ExtractGeometry(babylonMesh, vertices, indices, subMeshes, boneIds, skin, unskinnedMesh, invertedWorldMatrix, offsetTM, hasUV, hasUV2, hasColor, hasAlpha, optimizeVertices, multiMatsCount, meshNode, ref faceIndexes);
if (vertices.Count >= 65536)
{
RaiseWarning($"Mesh {babylonMesh.name} has {vertices.Count} vertices. This may prevent your scene to work on low end devices where 32 bits indice are not supported", 2);
if (!optimizeVertices)
{
RaiseError("You can try to optimize your object using [Try to optimize vertices] option", 2);
}
}
RaiseMessage($"{vertices.Count} vertices, {indices.Count / 3} faces", 2);
// Buffers
babylonMesh.positions = vertices.SelectMany(v => new[] { v.Position.X, v.Position.Y, v.Position.Z }).ToArray();
babylonMesh.normals = vertices.SelectMany(v => new[] { v.Normal.X, v.Normal.Y, v.Normal.Z }).ToArray();
// Export tangents if option is checked and mesh has tangents
if (exportParameters.exportTangents)
{
if (vertices.All(v => v.Tangent != null))
{
babylonMesh.tangents = vertices.SelectMany(v => v.Tangent).ToArray();
}
}
if (hasUV)
{
babylonMesh.uvs = vertices.SelectMany(v => new[] { v.UV.X, 1 - v.UV.Y }).ToArray();
}
if (hasUV2)
{
babylonMesh.uvs2 = vertices.SelectMany(v => new[] { v.UV2.X, 1 - v.UV2.Y }).ToArray();
}
if (skin != null)
{
babylonMesh.matricesWeights = vertices.SelectMany(v => v.Weights.ToArray()).ToArray();
babylonMesh.matricesIndices = vertices.Select(v => v.BonesIndices).ToArray();
babylonMesh.numBoneInfluencers = maxNbBones;
if (maxNbBones > 4)
{
babylonMesh.matricesWeightsExtra = vertices.SelectMany(v => v.WeightsExtra != null ? v.WeightsExtra.ToArray() : new[] { 0.0f, 0.0f, 0.0f, 0.0f }).ToArray();
babylonMesh.matricesIndicesExtra = vertices.Select(v => v.BonesIndicesExtra).ToArray();
}
}
if (hasColor)
{
var colors = vertices.SelectMany(v => v.Color.ToArray()).ToArray();
// There is an issue in 3dsMax where certain CSG operations assign a vertex color to the generated geometry.
// this workaround allows us to void our vertex colors if they have all been found to be [0,0,0,0]
bool useVertexColors = false;
for (int i = 0; i < colors.Length; ++i)
{
if (colors[i] != 0.0f)
{
useVertexColors = true;
break;
}
}
if (useVertexColors)
{
babylonMesh.colors = colors;
babylonMesh.hasVertexAlpha = hasAlpha;
}
}
babylonMesh.subMeshes = subMeshes.ToArray();
// Buffers - Indices
babylonMesh.indices = indices.ToArray();
// ------------------------
// ---- Morph targets -----
// ------------------------
// Retreive modifiers with morpher flag
List<IIGameModifier> modifiers = new List<IIGameModifier>();
for (int i = 0; i < meshNode.IGameObject.NumModifiers; i++)
{
var modifier = meshNode.IGameObject.GetIGameModifier(i);
if (modifier.ModifierType == Autodesk.Max.IGameModifier.ModType.Morpher)
{
modifiers.Add(modifier);
}
}
// Cast modifiers to morphers
List<IIGameMorpher> morphers = modifiers.ConvertAll(new Converter<IIGameModifier, IIGameMorpher>(modifier => modifier.AsGameMorpher()));
var hasMorphTarget = false;
morphers.ForEach(morpher =>
{
if (morpher.NumberOfMorphTargets > 0)
{
hasMorphTarget = true;
}
});
if (hasMorphTarget)
{
RaiseMessage("Export morph targets", 2);
// Morph Target Manager
var babylonMorphTargetManager = new BabylonMorphTargetManager(babylonMesh);
babylonScene.MorphTargetManagersList.Add(babylonMorphTargetManager);
babylonMesh.morphTargetManagerId = babylonMorphTargetManager.id;
// Morph Targets
var babylonMorphTargets = new List<BabylonMorphTarget>();
// All morphers are considered identical
// Their targets are concatenated
int m = 0;
morphers.ForEach(morpher =>
{
m++;
for (int i = 0; i < morpher.NumberOfMorphTargets; i++)
{
// Morph target
var maxMorphTarget = morpher.GetMorphTarget(i);
// here we avoid to extract vertices in an optimize way, du to the fact that the actual optimize process is NOT garanty to keep a one to one relationship
// with the source and target vertices.
bool mustRebuildMorphTarget = (maxMorphTarget == null || optimizeVertices );
if (mustRebuildMorphTarget)
{
string actionStr = exportParameters.rebuildMorphTarget ? $" trying to rebuild {i}." : string.Empty;
if (maxMorphTarget == null)
{
RaiseWarning($"Morph target [{i}] is not available anymore - ie: has been deleted in max and is baked into the scene.{actionStr}", 3);
}
else
{
RaiseWarning($"Morph target [{i}] MUST be rebuilt to avoid artifacts, using the vertices export process.{actionStr}", 3);
maxMorphTarget = null; // force target to be null anyway ie- when optimize on.
}
}
// Target geometry - this is where we rebuild the target if necessary
var targetVertices = ExtractMorphTargetVertices(babylonMesh, vertices, offsetTM, i, maxMorphTarget, optimizeVertices, faceIndexes);
if (targetVertices != null && targetVertices.Any())
{
var babylonMorphTarget = new BabylonMorphTarget
{
// the name is reconstructed if we have to rebuild the target
name = maxMorphTarget?.Name ?? $"{meshNode.Name}.morpher({m}).target({i})"
};
babylonMorphTargets.Add(babylonMorphTarget);
RaiseMessage($"Morph target {babylonMorphTarget.name} added.",3);
// TODO - Influence
babylonMorphTarget.influence = 0f;
// Target geometry
babylonMorphTarget.positions = targetVertices.SelectMany(v => new[] { v.Position.X, v.Position.Y, v.Position.Z }).ToArray();
if (exportParameters.exportMorphNormals)
{
if (mustRebuildMorphTarget)
{
// we do not recontruct the normals
RaiseWarning("we do not have morph normals when morph target has been rebuilded.",4);
babylonMorphTarget.normals = null;
}
else
{
babylonMorphTarget.normals = targetVertices.SelectMany(v => new[] { v.Normal.X, v.Normal.Y, v.Normal.Z }).ToArray();
}
}
// Tangent
if (exportParameters.exportTangents && exportParameters.exportMorphTangents)
{
if (mustRebuildMorphTarget)
{
// we do not recontruct the tangents
RaiseWarning("Rebuilt morph targets will not have tangent information.", 4);
babylonMorphTarget.tangents = null;
}
else
{
babylonMorphTarget.tangents = targetVertices.SelectMany(v => v.Tangent).ToArray();
}
}
// Animations
if (exportParameters.exportAnimations)
{
var animations = new List<BabylonAnimation>();
var morphWeight = morpher.GetMorphWeight(i);
ExportFloatGameController(morphWeight, "influence", animations);
if (animations.Count > 0)
{
babylonMorphTarget.animations = animations.ToArray();
babylonMorphTarget.autoAnimate = true;
babylonMorphTarget.autoAnimateLoop = true;
}
}
}
}
});
babylonMorphTargetManager.targets = babylonMorphTargets.ToArray();
}
}
// World Modifiers
ExportWorldModifiers(meshNode, babylonScene, babylonMesh);
// Animations
// Done last to avoid '0 vertex found' error (unkown cause)
exportAnimation(babylonMesh, meshNode);
babylonScene.MeshesList.Add(babylonMesh);
masterMeshMap[babylonMesh] = meshNode;
return babylonMesh;
}
private IEnumerable<GlobalVertex> ExtractMorphTargetVertices(BabylonAbstractMesh babylonAbstractMesh, List<GlobalVertex> vertices, IMatrix3 offsetTM, int morphIndex, IIGameNode maxMorphTarget, bool optimizeVertices, List<int> faceIndexes)
{
if (maxMorphTarget != null )
{
foreach(var v in ExtractVertices(babylonAbstractMesh, maxMorphTarget, optimizeVertices, faceIndexes))
{
yield return v;
}
yield break;
}
// rebuild Morph Target
if (exportParameters.rebuildMorphTarget)
{
var points = ExtractMorphTargetPoints(babylonAbstractMesh, morphIndex, offsetTM).ToList();
for (int i = 0; i != vertices.Count; i++)
{
int bi = vertices[i].BaseIndex;
yield return new GlobalVertex()
{
BaseIndex = bi,
Position = points[bi]
};
}
}
}
private IEnumerable<IPoint3> ExtractMorphTargetPoints(BabylonAbstractMesh babylonAbstractMesh, int morphIndex, IMatrix3 offsetTM)
{
// this is the place where we reconstruct the vertices.
// the needed function is not available on the .net SDK, then we have to use Max Script.
// TODO : use direct instance instead of manipulate string
var script = $"with printAllElements on (for k in 0 to (WM3_MC_NumMPts ${babylonAbstractMesh.name}.Morpher {morphIndex}) collect (WM3_MC_GetMorphPoint ${babylonAbstractMesh.name}.morpher {morphIndex} k)) as string";
#if MAX2022 || MAX2023
var str = ManagedServices.MaxscriptSDK.ExecuteStringMaxscriptQuery(script, ManagedServices.MaxscriptSDK.ScriptSource.NotSpecified);
#else
var str = ManagedServices.MaxscriptSDK.ExecuteStringMaxscriptQuery(script);
#endif
if (!String.IsNullOrEmpty(str))
{
// we obtain a list of Point3 as string in a format of #([5.69523,-58.2409,65.1479],...)
int i = str.IndexOf('[');
if (i != -1)
{
do
{
int j = str.IndexOf(']', i++);
var p3Str = str.Substring(i, j - i);
var xyz = p3Str.Split(',').Select(s => float.Parse(s, CultureInfo.InvariantCulture)).ToArray();
// conversion: Max to Directx(Babylon) (swap Y and Z).
var p = Loader.Global.Point3.Create(xyz[0] * scaleFactorToMeters, xyz[2] * scaleFactorToMeters, xyz[1] * scaleFactorToMeters);
yield return p;
i = str.IndexOf('[', j);
} while (i != -1);
}
}
yield break;
}
private void ExportUserData(IIGameNode meshNode, BabylonAbstractMesh babylonMesh)
{
string userProp = "";
// read "extras = ..." in user user defined object properties as a string
meshNode.MaxNode.GetUserPropString("extras", ref userProp);
if (userProp != "")
{
// setup metadata if needed
if (babylonMesh.metadata == null)
babylonMesh.metadata = new Dictionary<string, object>();
try
{
// JSON parse the string value
var o = JObject.Parse(userProp);
// convert Newtonsoft JSON to dictionary
Dictionary<string, object> d = o.ToObject<Dictionary<string, object>>();
// insert root elements to metadata
foreach (var e in d)
{
babylonMesh.metadata[e.Key] = e.Value;
}
RaiseMessage(d.Count + " User defined properties", 2);
}
catch (Exception e)
{
RaiseWarning("Failed to parse user defined properties: " + userProp, 2);
}
}
}
private BabylonNode ExportCloneMesh(IIGameScene maxScene, IIGameNode maxNode, BabylonScene babylonScene, BabylonMesh babylonMasterMesh, IIGameNode maxMasterNode)
{
// idea here is to create a mesh with a geometryId similar to the babylonMasterMesh
// for the purpose we wrote a specific extension
var babylonMesh = babylonMasterMesh.Clone(babylonScene);
if (babylonMesh != null)
{
babylonMesh.id = maxNode.MaxNode.GetGuid().ToString();
babylonMesh.name = maxNode.Name;
babylonMesh.pickable = maxNode.MaxNode.GetBoolProperty("babylonjs_checkpickable");
babylonMesh.checkCollisions = maxNode.MaxNode.GetBoolProperty("babylonjs_checkcollisions");
babylonMesh.showBoundingBox = maxNode.MaxNode.GetBoolProperty("babylonjs_showboundingbox");
babylonMesh.showSubMeshesBoundingBox = maxNode.MaxNode.GetBoolProperty("babylonjs_showsubmeshesboundingbox");
babylonMesh.alphaIndex = (int)maxNode.MaxNode.GetFloatProperty("babylonjs_alphaindex", 1000);
babylonMesh.visibility = maxNode.MaxNode.GetVisibility(0, Tools.Forever);
// Material
var mtl = maxNode.NodeMaterial;
var multiMatsCount = 1;
// The DirectXShader material is a passthrough to its render material.
// The shell material is a passthrough to its baked material.
while (mtl != null && (isShellMaterial(mtl) || isDirectXShaderMaterial(mtl)))
{
if (isShellMaterial(mtl))
{
// Retrieve the baked material from the shell material.
mtl = GetBakedMaterialFromShellMaterial(mtl);
}
else // isDirectXShaderMaterial(mtl)
{
// Retrieve the render material from the directX shader
mtl = GetRenderMaterialFromDirectXShader(mtl);
}
}
isMaterialDoubleSided = false;
if (mtl != null)
{
IIGameMaterial unsupportedMaterial = isMaterialSupported(mtl);
if (unsupportedMaterial == null)
{
babylonMesh.materialId = mtl.MaxMaterial.GetGuid().ToString();
if (!referencedMaterials.Contains(mtl))
{
referencedMaterials.Add(mtl);
}
multiMatsCount = Math.Max(mtl.SubMaterialCount, 1);
if (isDoubleSidedMaterial(mtl))
{
isMaterialDoubleSided = true;
}
}
else
{
if (mtl.SubMaterialCount == 0 || mtl == unsupportedMaterial)
{
RaiseWarning("Unsupported material type '" + unsupportedMaterial.MaterialClass + "'. Material is ignored.", 2);
}
else
{
RaiseWarning("Unsupported sub-material type '" + unsupportedMaterial.MaterialClass + "'. Material is ignored.", 2);
}
}
}
else
{
// ensure to clean the material because Clone() did not define any behavior about
// cloning the material id.
babylonMesh.materialId = null;
}
// Export the custom attributes of this mesh
babylonMesh.metadata = ExportExtraAttributes(maxNode, babylonScene);
// Append userData to extras
ExportUserData(maxNode, babylonMesh);
// Export transform / hierarchy / animations
exportNode(babylonMesh, maxNode, maxScene, babylonScene);
// Animations
exportAnimation(babylonMesh, maxNode);
// in order to keep the optimisation, a clone could be considered as Master
masterMeshMap[babylonMesh] = maxNode;
babylonScene.MeshesList.Add(babylonMesh);
}
return babylonMesh;
}
private BabylonNode ExportInstanceMesh(IIGameScene maxScene, IIGameNode maxNode, BabylonScene babylonScene, BabylonMesh babylonMasterMesh, IIGameNode maxMasterNode)
{
maxNode.MaxNode.MarkAsInstance();
var babylonInstanceMesh = new BabylonAbstractMesh
{
id = maxNode.MaxNode.GetGuid().ToString(),
name = maxNode.Name,
pickable = maxNode.MaxNode.GetBoolProperty("babylonjs_checkpickable"),
checkCollisions = maxNode.MaxNode.GetBoolProperty("babylonjs_checkcollisions"),
showBoundingBox = maxNode.MaxNode.GetBoolProperty("babylonjs_showboundingbox"),
showSubMeshesBoundingBox = maxNode.MaxNode.GetBoolProperty("babylonjs_showsubmeshesboundingbox"),
alphaIndex = (int)maxNode.MaxNode.GetFloatProperty("babylonjs_alphaindex", 1000)
};
// Export the custom attributes of this mesh
babylonInstanceMesh.metadata = ExportExtraAttributes(maxNode, babylonScene);
// Append userData to extras
ExportUserData(maxNode, babylonInstanceMesh);
// Physics
var impostorText = maxNode.MaxNode.GetStringProperty("babylonjs_impostor", "None");
if (impostorText != "None")
{
switch (impostorText)
{
case "Sphere":
babylonInstanceMesh.physicsImpostor = 1;
break;
case "Box":
babylonInstanceMesh.physicsImpostor = 2;
break;
case "Plane":
babylonInstanceMesh.physicsImpostor = 3;
break;
default:
babylonInstanceMesh.physicsImpostor = 0;
break;
}
babylonInstanceMesh.physicsMass = maxNode.MaxNode.GetFloatProperty("babylonjs_mass");
babylonInstanceMesh.physicsFriction = maxNode.MaxNode.GetFloatProperty("babylonjs_friction", 0.2f);
babylonInstanceMesh.physicsRestitution = maxNode.MaxNode.GetFloatProperty("babylonjs_restitution", 0.2f);
}
// Add instance to master mesh
List<BabylonAbstractMesh> list = babylonMasterMesh.instances != null ? babylonMasterMesh.instances.ToList() : new List<BabylonAbstractMesh>();
list.Add(babylonInstanceMesh);
babylonMasterMesh.instances = list.ToArray();
// Export transform / hierarchy / animations
exportNode(babylonInstanceMesh, maxNode, maxScene, babylonScene);
// Animations
exportAnimation(babylonInstanceMesh, maxNode);
return babylonInstanceMesh;
}
private List<GlobalVertex> ExtractVertices(BabylonAbstractMesh babylonAbstractMesh, IIGameNode maxMorphTarget, bool optimizeVertices, List<int> faceIndexes)
{
var gameMesh = maxMorphTarget.IGameObject.AsGameMesh();
bool initialized = gameMesh.InitializeData; // needed, the property is in fact a method initializing the exporter that has wrongly been auto
// translated into a property because it has no parameters
var mtl = maxMorphTarget.NodeMaterial;
var multiMatsCount = 1;
if (mtl != null)
{
multiMatsCount = Math.Max(mtl.SubMaterialCount, 1);
}
var invertedWorldMatrix = GetInvertWorldTM(maxMorphTarget, 0);
var offsetTM = GetOffsetTM(maxMorphTarget, 0);
var vertices = new List<GlobalVertex>();
ExtractGeometry(babylonAbstractMesh, vertices, new List<int>(), new List<BabylonSubMesh>(), null, null, gameMesh, invertedWorldMatrix, offsetTM, false, false, false, false, optimizeVertices, multiMatsCount, maxMorphTarget, ref faceIndexes);
return vertices;
}
private void ExtractGeometry(BabylonAbstractMesh babylonAbstractMesh, List<GlobalVertex> vertices, List<int> indices, List<BabylonSubMesh> subMeshes, List<int> boneIds, IIGameSkin skin, IIGameMesh unskinnedMesh, IMatrix3 invertedWorldMatrix, IMatrix3 offsetTM, bool hasUV, bool hasUV2, bool hasColor, bool hasAlpha, bool optimizeVertices, int multiMatsCount, IIGameNode meshNode, ref List<int> faceIndexes)
{
Dictionary<GlobalVertex, List<GlobalVertex>> verticesAlreadyExported = null;
if (optimizeVertices)
{
verticesAlreadyExported = new Dictionary<GlobalVertex, List<GlobalVertex>>();
}
var indexStart = 0;
// Whether or not to store order in which faces are exported
// Storage is used when exporting Morph Targets geometry
// To ensure face order is identical, especially with multimaterials involved
bool storeFaceIndexes = faceIndexes == null;
if (storeFaceIndexes)
{
faceIndexes = new List<int>();
}
int indexInFaceIndexesArray = 0;
for (int i = 0; i < multiMatsCount; ++i)
{
var indexCount = 0;
var minVertexIndex = int.MaxValue;
var maxVertexIndex = int.MinValue;
// Material Id is 0 if normal material, and GetMaterialID if multi-material
// default is [1,n] increment by 1 but user can decide to change the id (still an int) and set for example [4,3,9,1]
// note that GetMaterialID return the user id minus 1
int materialId = multiMatsCount == 1? i : meshNode.NodeMaterial.GetMaterialID(i);
var subMesh = new BabylonSubMesh { indexStart = indexStart, materialIndex = i };
if (multiMatsCount == 1)
{
for (int j = 0; j < unskinnedMesh.NumberOfFaces; ++j)
{
IFaceEx face = null;
if (storeFaceIndexes)
{
face = unskinnedMesh.GetFace(j);
// Store face index (j = face.MeshFaceIndex)
faceIndexes.Add(j);
}
else
{
face = unskinnedMesh.GetFace(faceIndexes[indexInFaceIndexesArray++]);
}
ExtractFace(skin, unskinnedMesh, babylonAbstractMesh, invertedWorldMatrix, offsetTM, vertices, indices, hasUV, hasUV2, hasColor, hasAlpha, verticesAlreadyExported, ref indexCount, ref minVertexIndex, ref maxVertexIndex, face, boneIds);
}
}
else
{
if (i == 0 || isMaterialDoubleSided == false)
{
ITab<IFaceEx> materialFaces = unskinnedMesh.GetFacesFromMatID(materialId);
for (int j = 0; j < materialFaces.Count; ++j)
{
IFaceEx face = null;
if (storeFaceIndexes)
{
// Retreive face
#if MAX2017 || MAX2018 || MAX2019 || MAX2020 || MAX2021 || MAX2022 || MAX2023
face = materialFaces[j];
#else
face = materialFaces[new IntPtr(j)];
#endif
// Store face index
faceIndexes.Add(face.MeshFaceIndex);
}
else
{
face = unskinnedMesh.GetFace(faceIndexes[indexInFaceIndexesArray++]);
}
ExtractFace(skin, unskinnedMesh, babylonAbstractMesh, invertedWorldMatrix, offsetTM, vertices, indices, hasUV, hasUV2, hasColor, hasAlpha, verticesAlreadyExported, ref indexCount, ref minVertexIndex, ref maxVertexIndex, face, boneIds);
}
}
else
{
// It's a double sided material
// The back faces are created at runtime
// WARNING - Nested multimaterial and double sided material are not supported
minVertexIndex = vertices.Count;
maxVertexIndex = vertices.Count * 2 - 1;
// Vertices
int nbVertices = vertices.Count;
for (int index = 0; index < nbVertices; index++)
{
GlobalVertex vertexOrg = vertices[index];
// Duplicate vertex
GlobalVertex vertexNew = new GlobalVertex(vertexOrg);
// Inverse back vertices normal
vertexNew.Normal = vertexNew.Normal.MultiplyBy(-1);
vertexNew.Tangent = vertexNew.Tangent.MultiplyBy(-1);
vertices.Add(vertexNew);
}
// Faces
int nbIndices = indices.Count;
for (int index = 0; index < nbIndices; index += 3)
{
// Duplicate and flip faces
indices.Add(indices[index + 2] + nbIndices);
indices.Add(indices[index + 1] + nbIndices);