-
Notifications
You must be signed in to change notification settings - Fork 335
/
BaseLibrary.hx
1525 lines (1389 loc) · 43.1 KB
/
BaseLibrary.hx
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
package hxd.fmt.fbx;
import haxe.io.Bytes;
using hxd.fmt.fbx.Data;
import h3d.col.Point;
import haxe.xml.Access;
class TmpObject {
public var index : Int;
public var model : FbxNode;
public var parent : TmpObject;
public var isJoint : Bool;
public var isMesh : Bool;
public var childs : Array<TmpObject>;
#if !(dataOnly || macro)
public var obj : h3d.scene.Object;
#end
public var joint : h3d.anim.Skin.Joint;
public var skin : TmpObject;
public function new() {
childs = [];
}
}
private class AnimCurve {
public var def : DefaultMatrixes;
public var object : String;
public var t : { t : Array<Float>, x : Array<Float>, y : Array<Float>, z : Array<Float> };
public var r : { t : Array<Float>, x : Array<Float>, y : Array<Float>, z : Array<Float> };
public var s : { t : Array<Float>, x : Array<Float>, y : Array<Float>, z : Array<Float> };
public var a : { t : Array<Float>, v : Array<Float> };
public var fov : { t : Array<Float>, v : Array<Float> };
public var roll : { t : Array<Float>, v : Array<Float> };
public var uv : Array<{ t : Float, u : Float, v : Float }>;
public function new(def, object) {
this.def = def;
this.object = object;
}
}
class DefaultMatrixes {
public var trans : Null<Point>;
public var scale : Null<Point>;
public var rotate : Null<Point>;
public var preRot : Null<Point>;
public var wasRemoved : Null<Int>;
public var transPos : h3d.Matrix;
public function new() {
}
public static inline function rightHandToLeft( m : h3d.Matrix ) {
// if [x,y,z] is our original point and M the matrix
// in right hand we have [x,y,z] * M = [x',y',z']
// we need to ensure that left hand matrix convey the x axis flip,
// in order to have [-x,y,z] * M = [-x',y',z']
m._12 = -m._12;
m._13 = -m._13;
m._21 = -m._21;
m._31 = -m._31;
m._41 = -m._41;
}
public function toMatrix(leftHand) {
var m = new h3d.Matrix();
m.identity();
if( scale != null ) m.scale(scale.x, scale.y, scale.z);
if( rotate != null ) m.rotate(rotate.x, rotate.y, rotate.z);
if( preRot != null ) m.rotate(preRot.x, preRot.y, preRot.z);
if( trans != null ) m.translate(trans.x, trans.y, trans.z);
if( leftHand ) rightHandToLeft(m);
return m;
}
public function toQuaternion(leftHand) {
var m = new h3d.Matrix();
m.identity();
if( rotate != null ) m.rotate(rotate.x, rotate.y, rotate.z);
if( preRot != null ) m.rotate(preRot.x, preRot.y, preRot.z);
if( leftHand ) rightHandToLeft(m);
var q = new h3d.Quat();
q.initRotateMatrix(m);
return q;
}
}
class BaseLibrary {
var root : FbxNode;
var ids : Map<Int,FbxNode>;
var connect : Map<Int,Array<Int>>;
var namedConnect : Map<Int,Map<String,Int>>;
var invConnect : Map<Int,Array<Int>>;
var leftHand : Bool;
var defaultModelMatrixes : Map<Int,DefaultMatrixes>;
var uvAnims : Map<String, Array<{ t : Float, u : Float, v : Float }>>;
var animationEvents : Array<{ frame : Int, data : String }>;
var isMaya : Bool;
public var fileName : String;
/**
The FBX version that was decoded
**/
public var version : Float = 0.;
/**
Allows to prevent some terminal unskinned joints to be removed, for instance if we want to track their position
**/
public var keepJoints : Map<String,Bool>;
/**
Allows to skip some objects from being processed as if they were not part of the FBX
**/
public var skipObjects : Map<String,Bool>;
/**
Use 4 bones of influence per vertex instead of 3
**/
public var fourBonesByVertex = false;
/**
If there are too many bones, the model will be split in separate render passes.
**/
public var maxBonesPerSkin = 34;
/**
Consider unskinned joints to be simple objects
**/
public var unskinnedJointsAsObjects : Bool;
public var allowVertexColor : Bool = true;
/**
Convert centimeters to meters and axis to Z-up (Maya FBX export)
**/
public var normalizeScaleOrient : Bool = true;
/**
Keep high precision values. Might increase animation data size and compressed size.
**/
public var highPrecision : Bool = false;
public function new( fileName ) {
this.fileName = fileName;
root = { name : "Root", props : [], childs : [] };
keepJoints = new Map();
skipObjects = new Map();
reset();
}
function reset() {
ids = new Map();
connect = new Map();
namedConnect = new Map();
invConnect = new Map();
defaultModelMatrixes = new Map();
}
public function loadFile( data : Bytes ) {
load(Parser.parse(data));
}
public function load( root : FbxNode ) {
reset();
this.root = root;
version = root.get("FBXHeaderExtension.FBXVersion").props[0].toInt() / 1000;
if( Std.int(version) != 7 )
throw "FBX Version 7.x required : use FBX 2010 export";
for( p in root.getAll("FBXHeaderExtension.SceneInfo.Properties70.P") )
if( p.props[0].toString() == "Original|ApplicationName" ) {
isMaya = p.props[4].toString().toLowerCase().indexOf("maya") >= 0;
break;
}
for( c in root.childs )
init(c);
if( normalizeScaleOrient )
updateModelScale();
// init properties
for( m in getAllModels() ) {
for( p in m.getAll("Properties70.P") )
switch( p.props[0].toString() ) {
case "UDP3DSMAX" | "Events":
var userProps = p.props[4].toString().split("&cr;&lf;");
for( p in userProps ) {
var pl = p.split("=");
var pname = StringTools.trim(pl.shift());
var pval = StringTools.trim(pl.join("="));
switch( pname ) {
case "UV" if( pval != "" ):
var xml = try Xml.parse(pval) catch( e : Dynamic ) throw "Invalid UV data in " + m.getName();
var frames = [for( f in new Access(xml.firstElement()).elements ) { var f = f.innerData.split(" "); { t : Std.parseFloat(f[0]) * 9622116.25, u : Std.parseFloat(f[1]), v : Std.parseFloat(f[2]) }} ];
if( uvAnims == null ) uvAnims = new Map();
uvAnims.set(m.getName(), frames);
case "Events":
var xml = try Xml.parse(pval) catch( e : Dynamic ) throw "Invalid Events data in " + m.getName();
animationEvents = [for( f in new Access(xml.firstElement()).elements ) { var f = f.innerData.split(" "); { frame : Std.parseInt(f.shift()), data : StringTools.trim(f.join(" ")) }} ];
default:
}
}
default:
}
}
}
function toFloats( n : FbxNode ) {
return switch( n.props[0] ) {
case PInts(vl):
var vl = [for( v in vl ) (v:Float)];
n.props[0] = PFloats(vl);
vl;
case PFloats(vl):
vl;
default:
throw n.props[0]+" should be floats ";
}
}
function getAllModels() {
return this.root.getAll("Objects.Model");
}
function getRootModels() {
return [for( m in getAllModels() ) if( isRootModel(m) ) m];
}
function isRootModel( m ) {
return getParent(m,"Model",true) == null;
}
function updateModelScale() {
var unitScale = 1;
var originScale = 1;
var upAxis = 1;
var originalUpAxis = 2;
for( p in root.getAll("GlobalSettings.Properties70.P") ) {
switch( p.props[0].toString() ) {
case "UnitScaleFactor": unitScale = p.props[4].toInt();
case "OriginalUnitScaleFactor": originScale = p.props[4].toInt();
case "UpAxis": upAxis = p.props[4].toInt();
case "OriginalUpAxis": originalUpAxis = p.props[4].toInt();
default:
}
}
var scaleFactor : Float = unitScale == 100 && originScale == 1 ? 100 : 1;
var geometryScaleFactor = scaleFactor;
if( upAxis == 1 ) // Y-up
convertYupToZup(originalUpAxis);
var app = "";
for( p in root.getAll("FBXHeaderExtension.SceneInfo.Properties70.P") )
switch( p.props[0].toString() ) {
case "LastSaved|ApplicationName": app = p.props[4].toString();
default:
}
if( app.indexOf("Blender") >= 0 && unitScale == originScale ) {
if ( unitScale == 0 ) scaleFactor = 1; // 0.9999999776482582 scale turning into 0
else scaleFactor = unitScale / 100; // Adjust blender output scaling
}
if( scaleFactor == 1 && geometryScaleFactor == 1 )
return;
// scale on geometry
if( geometryScaleFactor != 1 ) {
for( g in this.root.getAll("Objects.Geometry.Vertices").concat(this.root.getAll("Objects.Geometry.Shape.Vertices")) ) {
var v = toFloats(g);
for( i in 0...v.length )
v[i] = v[i] / geometryScaleFactor;
}
}
if( scaleFactor == 1 )
return;
// scale on root models
for( m in getAllModels() ) {
var isRoot = isRootModel(m);
for( p in m.getAll("Properties70.P") )
switch( p.props[0].toString() ) {
case "Lcl Scaling" if( isRoot ):
for( idx in [4,5,6] ) {
var v = p.props[idx].toFloat();
p.props[idx] = PFloat(v * scaleFactor);
}
case "Lcl Translation", "GeometricTranslation" if( !isRoot ):
for( idx in [4,5,6] ) {
var v = p.props[idx].toFloat();
p.props[idx] = PFloat(v / scaleFactor);
}
case "GeometricTranslation":
for( idx in [4,5,6] ) {
var v = p.props[idx].toFloat();
p.props[idx] = PFloat(v / scaleFactor);
}
default:
}
}
// scale blender's geometry transform
if (app.indexOf("Blender") >= 0) {
for( m in getAllModels() ) {
for( p in m.getAll("Properties70.P") ) {
if (p.props[0].toString() == "Lcl Translation" || p.props[0].toString() == "GeometricTranslation") {
for( idx in [4,5,6] ) {
var v = p.props[idx].toFloat();
p.props[idx] = PFloat(v * scaleFactor);
}
}
}
}
}
// scale on skin
for( t in this.root.getAll("Objects.Deformer.Transform") ) {
var m = toFloats(t);
m[12] /= scaleFactor;
m[13] /= scaleFactor;
m[14] /= scaleFactor;
}
// scale on animation
for( n in this.root.getAll("Objects.AnimationCurveNode") ) {
var name = n.getName();
var model = getParent(n,"Model",true);
var isRoot = model != null && getParent(model,"Model",true) == null;
for( p in n.getAll("Properties70.P") )
switch( p.props[0].toString() ) {
case "d|X", "d|Y", "d|Z" if( name == "T" && !isRoot ): p.props[4] = PFloat(p.props[4].toFloat() / scaleFactor);
case "d|X", "d|Y", "d|Z" if( name == "S" && isRoot ): p.props[4] = PFloat(p.props[4].toFloat() * scaleFactor);
default:
}
for( c in getChilds(n,"AnimationCurve") ) {
var vl = toFloats(c.get("KeyValueFloat"));
switch( name ) {
case "T" if( !isRoot ):
for( i in 0...vl.length )
vl[i] = vl[i] / scaleFactor;
case "S" if( isRoot ):
for( i in 0...vl.length )
vl[i] = vl[i] * scaleFactor;
default:
}
}
}
}
function convertYupToZup( originalUpAxis : Int ) {
switch( originalUpAxis ) {
case 2: // Original Axis Z - Maya & 3DS Max
for( rootObject in getRootModels() ) {
var props = rootObject.get("Properties70");
for( c in props.childs ) {
if( c.props[0].toString() == "PreRotation" && c.props[4].toFloat() == -90 && c.props[5].toFloat()== 0 && c.props[6].toFloat() == 0 ) {
for( c2 in props.childs ) {
if( c2.props[0].toString() == "Lcl Translation") {
var temp = c2.props[5].toFloat();
c2.props[5] = PFloat(-c2.props[6].toFloat());
c2.props[6] = PFloat(temp);
}
}
props.childs.remove(c);
break;
}
}
}
case -1, 1: // Original Axis -Y or Y - Blender & Maya
for( m in getRootModels() ) {
var needPreRot = true;
for( c in root.getAll("GlobalSettings.Properties70.P") ) {
if( c.props[0].toString() == "PreRotation" && c.props[4].toFloat() == 90 && c.props[5].toFloat()== 0 && c.props[6].toFloat() == 0 ) {
needPreRot = false;
break;
}
}
if( needPreRot ) {
var preRotProp : FbxNode = {name : "P", props : [PString("PreRotation"), PString("Vector3D"), PString("Vector"), PString(""), PFloat(90),PFloat(0),PFloat(0)], childs : []};
m.get("Properties70").childs.insert(0, preRotProp);
}
}
default:
throw "From Y-up to Z-up with orginalUpAxis = " + originalUpAxis + " not implemented.";
}
}
function convertPoints( a : Array<Float> ) {
var p = 0;
for( i in 0...Std.int(a.length / 3) ) {
a[p] = -a[p]; // inverse X axis
p += 3;
}
}
public function leftHandConvert() {
if( leftHand ) return;
leftHand = true;
for( g in root.getAll("Objects.Geometry") ) {
for( v in g.getAll("Vertices") )
convertPoints(v.getFloats());
for( v in g.getAll("LayerElementNormal.Normals") )
convertPoints(v.getFloats());
for( v in g.getAll("LayerElementTangent.Tangents") )
convertPoints(v.getFloats());
for( v in g.getAll("LayerElementBinormal.Binormals") )
convertPoints(v.getFloats());
}
for ( s in root.getAll("Objects.Geometry.Shape") ) {
for ( v in s.getAll("Vertices") )
convertPoints(v.getFloats());
for ( v in s.getAll("Normals") )
convertPoints(v.getFloats());
for ( v in s.getAll("Tangents") )
convertPoints(v.getFloats());
for ( v in s.getAll("Binormals") )
convertPoints(v.getFloats());
}
}
function init( n : FbxNode ) {
switch( n.name ) {
case "Connections":
for( c in n.childs ) {
if( c.name != "C" )
continue;
var child = c.props[1].toInt();
var parent = c.props[2].toInt();
// Maya exports invalid references
if( ids.get(child) == null || ids.get(parent) == null ) continue;
var name = c.props[3];
if( name != null ) {
var name = name.toString();
var nc = namedConnect.get(parent);
if( nc == null ) {
nc = new Map();
namedConnect.set(parent, nc);
}
nc.set(name, child);
// don't register as a parent, since the target can also be the child of something else
if( name == "LookAtProperty" ) continue;
}
var c = connect.get(parent);
if( c == null ) {
c = [];
connect.set(parent, c);
}
c.push(child);
if( parent == 0 )
continue;
var c = invConnect.get(child);
if( c == null ) {
c = [];
invConnect.set(child, c);
}
c.push(parent);
}
case "Objects":
for( c in n.childs )
ids.set(c.getId(), c);
default:
}
}
public function getGeometry( name : String = "" ) {
var geom = null;
for( g in root.getAll("Objects.Geometry") )
if( g.hasProp(PString("Geometry::" + name)) ) {
geom = g;
break;
}
if( geom == null )
throw "Geometry " + name + " not found";
return new Geometry(this, geom);
}
public function getParent( node : FbxNode, nodeName : String, ?opt : Bool ) {
var p = getParents(node, nodeName);
if( p.length > 1 )
throw node.getName() + " has " + p.length + " " + nodeName + " parents "+[for( o in p ) o.getName()].join(",");
if( p.length == 0 && !opt )
throw "Missing " + node.getName() + " " + nodeName + " parent";
return p[0];
}
public function getChild( node : FbxNode, nodeName : String, ?opt : Bool ) {
var c = getChilds(node, nodeName);
if( c.length > 1 )
throw node.getName() + " has " + c.length + " " + nodeName + " childs "+[for( o in c ) o.getName()].join(",");
if( c.length == 0 && !opt )
throw "Missing " + node.getName() + " " + nodeName + " child";
return c[0];
}
public function getSpecChild( node : FbxNode, name : String ) {
var nc = namedConnect.get(node.getId());
if( nc == null )
return null;
var id = nc.get(name);
if( id == null )
return null;
return ids.get(id);
}
public function getChilds( node : FbxNode, ?nodeName : String ) {
var c = connect.get(node.getId());
var subs = [];
if( c != null )
for( id in c ) {
var n = ids.get(id);
if( n == null ) throw id + " not found";
if( nodeName != null && n.name != nodeName ) continue;
subs.push(n);
}
return subs;
}
public function getParents( node : FbxNode, ?nodeName : String ) {
var c = invConnect.get(node.getId());
var pl = [];
if( c != null )
for( id in c ) {
var n = ids.get(id);
if( n == null ) throw id + " not found";
if( nodeName != null && n.name != nodeName ) continue;
pl.push(n);
}
return pl;
}
public function getRoot() {
return root;
}
function ignoreMissingObject( id : Int ) {
var def = defaultModelMatrixes.get(id);
if( def == null ) {
def = new DefaultMatrixes();
def.wasRemoved = -2;
defaultModelMatrixes.set(id, def);
}
}
function buildHierarchy() {
// init objects
var oroot = new TmpObject();
var objects = new Array<TmpObject>();
var hobjects = new Map<Int, TmpObject>();
hobjects.set(0, oroot);
for( model in getAllModels() ) {
if( skipObjects.get(model.getName()) )
continue;
var mtype = model.getType();
var isJoint = mtype == "LimbNode" && (!unskinnedJointsAsObjects || !isNullJoint(model));
var o = new TmpObject();
o.model = model;
o.isJoint = isJoint;
o.isMesh = mtype == "Mesh";
hobjects.set(model.getId(), o);
objects.push(o);
}
// build hierarchy
for( o in objects ) {
var p = getParent(o.model, "Model", true);
var pid = if( p == null ) 0 else p.getId();
var op = hobjects.get(pid);
if( op == null ) op = oroot; // if parent has been removed
op.childs.push(o);
o.parent = op;
}
inline function getDepth( o : TmpObject ) {
var k = 0;
while( o != oroot ) {
o = o.parent;
k++;
}
return k;
}
// look for common skin ancestor
for( o in objects ) {
if( !o.isMesh ) continue;
var g = getChild(o.model, "Geometry");
var def = getChild(g, "Deformer", true);
if( def == null ) continue;
var bones = [for( d in getChilds(def, "Deformer") ) hobjects.get(getChild(d, "Model").getId())];
if( bones.length == 0 ) continue;
// first let's go the minimal depth for all bones
var minDepth = getDepth(bones[0]);
for( i in 1...bones.length ) {
var d = getDepth(bones[i]);
if( d < minDepth ) minDepth = d;
}
var out = [];
for( i in 0...bones.length ) {
var b = bones[i];
var n = getDepth(b) - minDepth;
for( i in 0...n ) {
b.isJoint = true;
b = b.parent;
}
out.remove(b);
out.push(b);
}
bones = out;
while( bones.length > 1 ) {
for( b in bones )
b.isJoint = true;
var parents = [];
for( b in bones ) {
if( b.parent == oroot || b.parent.isMesh ) continue;
parents.remove(b.parent);
parents.push(b.parent);
}
bones = parents;
}
}
// propagates joint flags
var changed = true;
while( changed ) {
changed = false;
for( o in objects ) {
if( o.isJoint || o.isMesh ) continue;
if( o.parent.isJoint ) {
o.isJoint = true;
changed = true;
continue;
}
var hasJoint = false;
for( c in o.childs )
if( c.isJoint ) {
hasJoint = true;
break;
}
if( hasJoint )
for( c in o.parent.childs )
if( c.isJoint ) {
o.isJoint = true;
changed = true;
break;
}
}
}
return { root : oroot, objects : objects };
}
function getObjectCurve( curves : Map < Int, AnimCurve > , model : FbxNode, curveName : String, animName : String ) : AnimCurve {
var c = curves.get(model.getId());
if( c != null )
return c;
var name = model.getName();
if( skipObjects.get(name) )
return null;
var def = getDefaultMatrixes(model);
if( def == null )
return null;
// if it's a move animation on a terminal unskinned joint, let's skip it
var isMove = curveName != "Visibility" && curveName != "UV";
if( def.wasRemoved != null && (isMove || def.wasRemoved == -1) )
return null;
// allow not move animations on root model
if( def.wasRemoved != null && def.wasRemoved != -2 ) {
// apply it on the skin instead
model = ids.get(def.wasRemoved);
name = model.getName();
c = curves.get(def.wasRemoved);
def = getDefaultMatrixes(model);
// todo : change behavior not to remove the mesh but the skin instead!
if( def == null ) throw "assert";
}
if( c == null ) {
c = new AnimCurve(def, name);
curves.set(model.getId(), c);
}
return c;
}
public function mergeModels( modelNames : Array<String> ) {
if( modelNames.length <= 1 )
return;
var models = getAllModels();
function getModel(name) {
for( m in models )
if( m.getName() == name )
return m;
throw "Model not found " + name;
return null;
}
var m = getModel(modelNames[0]);
var geom = new Geometry(this, getChild(m, "Geometry"));
var def = getChild(geom.getRoot(), "Deformer", true);
var subDefs = getChilds(def, "Deformer");
for( i in 1...modelNames.length ) {
var name = modelNames[i];
var m2 = getModel(name);
var geom2 = new Geometry(this, getChild(m2, "Geometry"));
var vcount = Std.int(geom.getVertices().length / 3);
skipObjects.set(name, true);
// merge materials
var mindex = [];
var materials = getChilds(m, "Material");
for( mat in getChilds(m2, "Material") ) {
var idx = materials.indexOf(mat);
if( idx < 0 ) {
idx = materials.length;
materials.push(mat);
addLink(m, mat);
}
mindex.push(idx);
}
// merge geometry
geom.merge(geom2, mindex);
// merge skinning
var def2 = getChild(geom2.getRoot(), "Deformer", true);
if( def2 != null ) {
if( def == null ) throw m.getName() + " does not have a deformer but " + name + " has one";
for( subDef in getChilds(def2, "Deformer") ) {
var subModel = getChild(subDef, "Model");
var prevDef = null;
for( s in subDefs )
if( getChild(s, "Model") == subModel ) {
prevDef = s;
break;
}
if( prevDef != null )
removeLink(subDef, subModel);
var idx = subDef.get("Indexes", true);
if( idx == null ) continue;
if( prevDef == null ) {
addLink(def, subDef);
removeLink(def2, subDef);
subDefs.push(subDef);
var idx = idx.getInts();
for( i in 0...idx.length )
idx[i] += vcount;
} else {
var pidx = prevDef.get("Indexes").getInts();
for( i in idx.getInts() )
pidx.push(i + vcount);
var weights = prevDef.get("Weights").getFloats();
for( w in subDef.get("Weights").getFloats() )
weights.push(w);
}
}
}
}
}
function addLink( parent : FbxNode, child : FbxNode ) {
var pid = parent.getId();
var nid = child.getId();
connect.get(pid).push(nid);
invConnect.get(nid).push(pid);
}
function removeLink( parent : FbxNode, child : FbxNode ) {
var pid = parent.getId();
var nid = child.getId();
connect.get(pid).remove(nid);
invConnect.get(nid).remove(pid);
}
function checkData( t : { x : Array<Float>, y :Array<Float>, z:Array<Float> } ) {
if( t == null )
return true;
if( t.x != null ) {
var v = t.x[0];
for( v2 in t.x )
if( v != v2 )
return false;
}
if( t.y != null ) {
var v = t.y[0];
for( v2 in t.y )
if( v != v2 )
return false;
}
if( t.z != null ) {
var v = t.z[0];
for( v2 in t.z )
if( v != v2 )
return false;
}
return true;
}
function roundValues( data : Array<Float>, def : Float, mult : Float = 1. ) {
var hasValue = false;
var epsi = highPrecision ? 0 : 1e-3;
for( i in 0...data.length ) {
var v = data[i] * mult;
if( Math.abs(v - def) > epsi )
hasValue = true;
else
v = def;
data[i] = round(v);
}
return hasValue;
}
/**
Returns an array of names with all animations present in FBX file.
**/
public function getAnimationNames() : Array<String> {
var names = [];
for ( a in this.root.getAll("Objects.AnimationStack") ) {
if( getChilds(a, "AnimationLayer").length > 0 )
names.push(a.getName());
}
return names;
}
public function loadAnimation( ?animName : String, ?root : FbxNode, ?lib : BaseLibrary ) : h3d.anim.Animation {
if( lib != null ) {
lib.defaultModelMatrixes = defaultModelMatrixes;
return lib.loadAnimation(animName);
}
if( root != null ) {
var l = new BaseLibrary(fileName);
l.normalizeScaleOrient = normalizeScaleOrient;
l.load(root);
if( leftHand ) l.leftHandConvert();
l.defaultModelMatrixes = defaultModelMatrixes;
return l.loadAnimation(animName);
}
var defNode = null;
var animNodes = [];
for( a in this.root.getAll("Objects.AnimationStack") )
if( animName == null || a.getName() == animName ) {
for( n in getChilds(a, "AnimationLayer") ) {
defNode = n;
if( getChilds(n,"AnimationCurveNode").length > 0 )
animNodes.push(n);
}
}
var animNode = switch( animNodes.length ) {
case 0:
defNode;
case 1:
animNodes[0];
default:
trace("Multiple animation layers curves are currently not supported");
animNodes[0];
}
if( animNode == null ) {
if( animName != null )
throw "Animation not found " + animName;
if( uvAnims == null )
return null;
}
if( animName == null ) animName = getParent(animNode,"AnimationStack").getName();
var curves = new Map();
var P0 = new Point();
var P1 = new Point(1, 1, 1);
var F = Math.PI / 180;
var allTimes = new Map();
if( animNode != null ) for( cn in getChilds(animNode, "AnimationCurveNode") ) {
var model = getParent(cn, "Model", true);
if( model == null ) {
switch( cn.getName() ) {
case "Roll", "FieldOfView":
// the parent is not a Model but a NodeAttribute
var nattr = getParent(cn, "NodeAttribute", true);
model = nattr == null ? null : getParent(nattr, "Model", true);
if( model == null ) continue;
default:
continue; //morph support
}
}
var c = getObjectCurve(curves, model, cn.getName(), animName);
if( c == null )
continue;
var dataCurves = getChilds(cn, "AnimationCurve");
if( dataCurves.length == 0 ) continue;
var cname = cn.getName();
// collect all the timestamps
var times = dataCurves[0].get("KeyTime").getFloats();
for( i in 0...times.length ) {
var t = times[i];
// fix rounding error
if( t % 100 != 0 ) {
t += 100 - (t % 100);
times[i] = t;
}
// this should give significant-enough key
var it = Std.int(t / 200000);
allTimes.set(it, t);
}
// handle special curves
if( dataCurves.length != 3 ) {
var values = dataCurves[0].get("KeyValueFloat").getFloats();
switch( cname ) {
case "Visibility":
if( !roundValues(values, 1) )
continue;
c.a = {
v : values,
t : times,
};
continue;
case "Roll":
if( !roundValues(values, 0) )
continue;
c.roll = {
v : values,
t : times,
};
continue;
case "FieldOfView":
var ratio = 16/9, fov = 45.;
for( p in getChild(model, "NodeAttribute").getAll("Properties70.P") ) {
switch( p.props[0].toString() ) {
case "FilmAspectRatio": ratio = p.props[4].toFloat();
case "FieldOfView": fov = p.props[4].toFloat();
default:
}
}
inline function fovXtoY(v:Float) {
return 2 * Math.atan( Math.tan(v * 0.5 * Math.PI / 180) / ratio ) * 180 / Math.PI;
}
for( i in 0...values.length )
values[i] = fovXtoY(values[i]);
if( !roundValues(values, fovXtoY(fov)) )
continue;
c.fov = {
v : values,
t : times,
};
continue;
default:
}
}
// handle TRS curves
var data = {
x : null,
y : null,
z : null,
t : times,
};
var curves = namedConnect.get(cn.getId());
for( cname in curves.keys() ) {
var values = ids.get(curves.get(cname)).get("KeyValueFloat").getFloats();
switch( cname ) {
case "d|X": data.x = values;
case "d|Y": data.y = values;
case "d|Z": data.z = values;
default:
trace("Unsupported key name "+cname);
}
}
// this can happen when resampling anims due to rounding errors, let's ignore it for now
//if( data.y.length != times.length || data.z.length != times.length )
// throw "Unsynchronized curve components on " + model.getName()+"."+cname+" (" + data.x.length + "/" + data.y.length + "/" + data.z.length + ")";
// optimize empty animations out
var M = 1.0;
var def = switch( cname ) {
case "T":
if( c.def.trans == null ) P0 else c.def.trans;
case "R":
M = F;
if( c.def.rotate == null && c.def.preRot == null ) P0 else
if( c.def.rotate == null ) c.def.preRot else
if( c.def.preRot == null ) c.def.rotate else