/
FBXConverter.cpp
3357 lines (2711 loc) · 122 KB
/
FBXConverter.cpp
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
/*
Open Asset Import Library (assimp)
----------------------------------------------------------------------
Copyright (c) 2006-2017, assimp team
All rights reserved.
Redistribution and use of this software in source and binary forms,
with or without modification, are permitted provided that the
following conditions are met:
* Redistributions of source code must retain the above
copyright notice, this list of conditions and the
following disclaimer.
* Redistributions in binary form must reproduce the above
copyright notice, this list of conditions and the
following disclaimer in the documentation and/or other
materials provided with the distribution.
* Neither the name of the assimp team, nor the names of its
contributors may be used to endorse or promote products
derived from this software without specific prior
written permission of the assimp team.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
"AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
----------------------------------------------------------------------
*/
/** @file FBXConverter.cpp
* @brief Implementation of the FBX DOM -> aiScene converter
*/
#ifndef ASSIMP_BUILD_NO_FBX_IMPORTER
#include "FBXConverter.h"
#include "FBXParser.h"
#include "FBXMeshGeometry.h"
#include "FBXDocument.h"
#include "FBXUtil.h"
#include "FBXProperties.h"
#include "FBXImporter.h"
#include "StringComparison.h"
#include <assimp/scene.h>
#include <tuple>
#include <memory>
#include <iterator>
#include <vector>
namespace Assimp {
namespace FBX {
using namespace Util;
#define MAGIC_NODE_TAG "_$AssimpFbx$"
#define CONVERT_FBX_TIME(time) static_cast<double>(time) / 46186158000L
// XXX vc9's debugger won't step into anonymous namespaces
//namespace {
/** Dummy class to encapsulate the conversion process */
class Converter
{
public:
/**
* The different parts that make up the final local transformation of a fbx-node
*/
enum TransformationComp
{
TransformationComp_Translation = 0,
TransformationComp_RotationOffset,
TransformationComp_RotationPivot,
TransformationComp_PreRotation,
TransformationComp_Rotation,
TransformationComp_PostRotation,
TransformationComp_RotationPivotInverse,
TransformationComp_ScalingOffset,
TransformationComp_ScalingPivot,
TransformationComp_Scaling,
TransformationComp_ScalingPivotInverse,
TransformationComp_GeometricTranslation,
TransformationComp_GeometricRotation,
TransformationComp_GeometricScaling,
TransformationComp_MAXIMUM
};
public:
Converter( aiScene* out, const Document& doc );
~Converter();
private:
// ------------------------------------------------------------------------------------------------
// find scene root and trigger recursive scene conversion
void ConvertRootNode();
// ------------------------------------------------------------------------------------------------
// collect and assign child nodes
void ConvertNodes( uint64_t id, aiNode& parent, const aiMatrix4x4& parent_transform = aiMatrix4x4() );
// ------------------------------------------------------------------------------------------------
void ConvertLights( const Model& model );
// ------------------------------------------------------------------------------------------------
void ConvertCameras( const Model& model );
// ------------------------------------------------------------------------------------------------
void ConvertLight( const Model& model, const Light& light );
// ------------------------------------------------------------------------------------------------
void ConvertCamera( const Model& model, const Camera& cam );
// ------------------------------------------------------------------------------------------------
// this returns unified names usable within assimp identifiers (i.e. no space characters -
// while these would be allowed, they are a potential trouble spot so better not use them).
const char* NameTransformationComp( TransformationComp comp );
// ------------------------------------------------------------------------------------------------
// note: this returns the REAL fbx property names
const char* NameTransformationCompProperty( TransformationComp comp );
// ------------------------------------------------------------------------------------------------
aiVector3D TransformationCompDefaultValue( TransformationComp comp );
// ------------------------------------------------------------------------------------------------
void GetRotationMatrix( Model::RotOrder mode, const aiVector3D& rotation, aiMatrix4x4& out );
// ------------------------------------------------------------------------------------------------
/**
* checks if a node has more than just scaling, rotation and translation components
*/
bool NeedsComplexTransformationChain( const Model& model );
// ------------------------------------------------------------------------------------------------
// note: name must be a FixNodeName() result
std::string NameTransformationChainNode( const std::string& name, TransformationComp comp );
// ------------------------------------------------------------------------------------------------
/**
* note: memory for output_nodes will be managed by the caller
*/
void GenerateTransformationNodeChain( const Model& model, std::vector<aiNode*>& output_nodes );
// ------------------------------------------------------------------------------------------------
void SetupNodeMetadata( const Model& model, aiNode& nd );
// ------------------------------------------------------------------------------------------------
void ConvertModel( const Model& model, aiNode& nd, const aiMatrix4x4& node_global_transform );
// ------------------------------------------------------------------------------------------------
// MeshGeometry -> aiMesh, return mesh index + 1 or 0 if the conversion failed
std::vector<unsigned int> ConvertMesh( const MeshGeometry& mesh, const Model& model,
const aiMatrix4x4& node_global_transform );
// ------------------------------------------------------------------------------------------------
aiMesh* SetupEmptyMesh( const MeshGeometry& mesh );
// ------------------------------------------------------------------------------------------------
unsigned int ConvertMeshSingleMaterial( const MeshGeometry& mesh, const Model& model,
const aiMatrix4x4& node_global_transform );
// ------------------------------------------------------------------------------------------------
std::vector<unsigned int> ConvertMeshMultiMaterial( const MeshGeometry& mesh, const Model& model,
const aiMatrix4x4& node_global_transform );
// ------------------------------------------------------------------------------------------------
unsigned int ConvertMeshMultiMaterial( const MeshGeometry& mesh, const Model& model,
MatIndexArray::value_type index,
const aiMatrix4x4& node_global_transform );
// ------------------------------------------------------------------------------------------------
static const unsigned int NO_MATERIAL_SEPARATION = /* std::numeric_limits<unsigned int>::max() */
static_cast<unsigned int>(-1);
// ------------------------------------------------------------------------------------------------
/**
* - if materialIndex == NO_MATERIAL_SEPARATION, materials are not taken into
* account when determining which weights to include.
* - outputVertStartIndices is only used when a material index is specified, it gives for
* each output vertex the DOM index it maps to.
*/
void ConvertWeights( aiMesh* out, const Model& model, const MeshGeometry& geo,
const aiMatrix4x4& node_global_transform = aiMatrix4x4(),
unsigned int materialIndex = NO_MATERIAL_SEPARATION,
std::vector<unsigned int>* outputVertStartIndices = NULL );
// ------------------------------------------------------------------------------------------------
void ConvertCluster( std::vector<aiBone*>& bones, const Model& /*model*/, const Cluster& cl,
std::vector<size_t>& out_indices,
std::vector<size_t>& index_out_indices,
std::vector<size_t>& count_out_indices,
const aiMatrix4x4& node_global_transform );
// ------------------------------------------------------------------------------------------------
void ConvertMaterialForMesh( aiMesh* out, const Model& model, const MeshGeometry& geo,
MatIndexArray::value_type materialIndex );
// ------------------------------------------------------------------------------------------------
unsigned int GetDefaultMaterial();
// ------------------------------------------------------------------------------------------------
// Material -> aiMaterial
unsigned int ConvertMaterial( const Material& material, const MeshGeometry* const mesh );
// ------------------------------------------------------------------------------------------------
// Video -> aiTexture
unsigned int ConvertVideo( const Video& video );
// ------------------------------------------------------------------------------------------------
void TrySetTextureProperties( aiMaterial* out_mat, const TextureMap& textures,
const std::string& propName,
aiTextureType target, const MeshGeometry* const mesh );
// ------------------------------------------------------------------------------------------------
void TrySetTextureProperties( aiMaterial* out_mat, const LayeredTextureMap& layeredTextures,
const std::string& propName,
aiTextureType target, const MeshGeometry* const mesh );
// ------------------------------------------------------------------------------------------------
void SetTextureProperties( aiMaterial* out_mat, const TextureMap& textures, const MeshGeometry* const mesh );
// ------------------------------------------------------------------------------------------------
void SetTextureProperties( aiMaterial* out_mat, const LayeredTextureMap& layeredTextures, const MeshGeometry* const mesh );
// ------------------------------------------------------------------------------------------------
aiColor3D GetColorPropertyFromMaterial( const PropertyTable& props, const std::string& baseName,
bool& result );
// ------------------------------------------------------------------------------------------------
void SetShadingPropertiesCommon( aiMaterial* out_mat, const PropertyTable& props );
// ------------------------------------------------------------------------------------------------
// get the number of fps for a FrameRate enumerated value
static double FrameRateToDouble( FileGlobalSettings::FrameRate fp, double customFPSVal = -1.0 );
// ------------------------------------------------------------------------------------------------
// convert animation data to aiAnimation et al
void ConvertAnimations();
// ------------------------------------------------------------------------------------------------
// rename a node already partially converted. fixed_name is a string previously returned by
// FixNodeName, new_name specifies the string FixNodeName should return on all further invocations
// which would previously have returned the old value.
//
// this also updates names in node animations, cameras and light sources and is thus slow.
//
// NOTE: the caller is responsible for ensuring that the new name is unique and does
// not collide with any other identifiers. The best way to ensure this is to only
// append to the old name, which is guaranteed to match these requirements.
void RenameNode( const std::string& fixed_name, const std::string& new_name );
// ------------------------------------------------------------------------------------------------
// takes a fbx node name and returns the identifier to be used in the assimp output scene.
// the function is guaranteed to provide consistent results over multiple invocations
// UNLESS RenameNode() is called for a particular node name.
std::string FixNodeName( const std::string& name );
typedef std::map<const AnimationCurveNode*, const AnimationLayer*> LayerMap;
// XXX: better use multi_map ..
typedef std::map<std::string, std::vector<const AnimationCurveNode*> > NodeMap;
// ------------------------------------------------------------------------------------------------
void ConvertAnimationStack( const AnimationStack& st );
// ------------------------------------------------------------------------------------------------
void GenerateNodeAnimations( std::vector<aiNodeAnim*>& node_anims,
const std::string& fixed_name,
const std::vector<const AnimationCurveNode*>& curves,
const LayerMap& layer_map,
int64_t start, int64_t stop,
double& max_time,
double& min_time );
// ------------------------------------------------------------------------------------------------
bool IsRedundantAnimationData( const Model& target,
TransformationComp comp,
const std::vector<const AnimationCurveNode*>& curves );
// ------------------------------------------------------------------------------------------------
aiNodeAnim* GenerateRotationNodeAnim( const std::string& name,
const Model& target,
const std::vector<const AnimationCurveNode*>& curves,
const LayerMap& layer_map,
int64_t start, int64_t stop,
double& max_time,
double& min_time );
// ------------------------------------------------------------------------------------------------
aiNodeAnim* GenerateScalingNodeAnim( const std::string& name,
const Model& /*target*/,
const std::vector<const AnimationCurveNode*>& curves,
const LayerMap& layer_map,
int64_t start, int64_t stop,
double& max_time,
double& min_time );
// ------------------------------------------------------------------------------------------------
aiNodeAnim* GenerateTranslationNodeAnim( const std::string& name,
const Model& /*target*/,
const std::vector<const AnimationCurveNode*>& curves,
const LayerMap& layer_map,
int64_t start, int64_t stop,
double& max_time,
double& min_time,
bool inverse = false );
// ------------------------------------------------------------------------------------------------
// generate node anim, extracting only Rotation, Scaling and Translation from the given chain
aiNodeAnim* GenerateSimpleNodeAnim( const std::string& name,
const Model& target,
NodeMap::const_iterator chain[ TransformationComp_MAXIMUM ],
NodeMap::const_iterator iter_end,
const LayerMap& layer_map,
int64_t start, int64_t stop,
double& max_time,
double& min_time,
bool reverse_order = false );
// key (time), value, mapto (component index)
typedef std::tuple<std::shared_ptr<KeyTimeList>, std::shared_ptr<KeyValueList>, unsigned int > KeyFrameList;
typedef std::vector<KeyFrameList> KeyFrameListList;
// ------------------------------------------------------------------------------------------------
KeyFrameListList GetKeyframeList( const std::vector<const AnimationCurveNode*>& nodes, int64_t start, int64_t stop );
// ------------------------------------------------------------------------------------------------
KeyTimeList GetKeyTimeList( const KeyFrameListList& inputs );
// ------------------------------------------------------------------------------------------------
void InterpolateKeys( aiVectorKey* valOut, const KeyTimeList& keys, const KeyFrameListList& inputs,
const aiVector3D& def_value,
double& max_time,
double& min_time );
// ------------------------------------------------------------------------------------------------
void InterpolateKeys( aiQuatKey* valOut, const KeyTimeList& keys, const KeyFrameListList& inputs,
const aiVector3D& def_value,
double& maxTime,
double& minTime,
Model::RotOrder order );
// ------------------------------------------------------------------------------------------------
void ConvertTransformOrder_TRStoSRT( aiQuatKey* out_quat, aiVectorKey* out_scale,
aiVectorKey* out_translation,
const KeyFrameListList& scaling,
const KeyFrameListList& translation,
const KeyFrameListList& rotation,
const KeyTimeList& times,
double& maxTime,
double& minTime,
Model::RotOrder order,
const aiVector3D& def_scale,
const aiVector3D& def_translate,
const aiVector3D& def_rotation );
// ------------------------------------------------------------------------------------------------
// euler xyz -> quat
aiQuaternion EulerToQuaternion( const aiVector3D& rot, Model::RotOrder order );
// ------------------------------------------------------------------------------------------------
void ConvertScaleKeys( aiNodeAnim* na, const std::vector<const AnimationCurveNode*>& nodes, const LayerMap& /*layers*/,
int64_t start, int64_t stop,
double& maxTime,
double& minTime );
// ------------------------------------------------------------------------------------------------
void ConvertTranslationKeys( aiNodeAnim* na, const std::vector<const AnimationCurveNode*>& nodes,
const LayerMap& /*layers*/,
int64_t start, int64_t stop,
double& maxTime,
double& minTime );
// ------------------------------------------------------------------------------------------------
void ConvertRotationKeys( aiNodeAnim* na, const std::vector<const AnimationCurveNode*>& nodes,
const LayerMap& /*layers*/,
int64_t start, int64_t stop,
double& maxTime,
double& minTime,
Model::RotOrder order );
// ------------------------------------------------------------------------------------------------
// copy generated meshes, animations, lights, cameras and textures to the output scene
void TransferDataToScene();
private:
// 0: not assigned yet, others: index is value - 1
unsigned int defaultMaterialIndex;
std::vector<aiMesh*> meshes;
std::vector<aiMaterial*> materials;
std::vector<aiAnimation*> animations;
std::vector<aiLight*> lights;
std::vector<aiCamera*> cameras;
std::vector<aiTexture*> textures;
typedef std::map<const Material*, unsigned int> MaterialMap;
MaterialMap materials_converted;
typedef std::map<const Video*, unsigned int> VideoMap;
VideoMap textures_converted;
typedef std::map<const Geometry*, std::vector<unsigned int> > MeshMap;
MeshMap meshes_converted;
// fixed node name -> which trafo chain components have animations?
typedef std::map<std::string, unsigned int> NodeAnimBitMap;
NodeAnimBitMap node_anim_chain_bits;
// name -> has had its prefix_stripped?
typedef std::map<std::string, bool> NodeNameMap;
NodeNameMap node_names;
typedef std::map<std::string, std::string> NameNameMap;
NameNameMap renamed_nodes;
double anim_fps;
aiScene* const out;
const FBX::Document& doc;
bool FindTextureIndexByFilename(const Video& video, unsigned int& index) {
index = 0;
const char* videoFileName = video.FileName().c_str();
for (auto texture = textures_converted.begin(); texture != textures_converted.end(); ++texture)
{
if (!strcmp(texture->first->FileName().c_str(), videoFileName)) {
return true;
}
index++;
}
return false;
}
};
Converter::Converter( aiScene* out, const Document& doc )
: defaultMaterialIndex()
, out( out )
, doc( doc )
{
// animations need to be converted first since this will
// populate the node_anim_chain_bits map, which is needed
// to determine which nodes need to be generated.
ConvertAnimations();
ConvertRootNode();
if ( doc.Settings().readAllMaterials ) {
// unfortunately this means we have to evaluate all objects
for( const ObjectMap::value_type& v : doc.Objects() ) {
const Object* ob = v.second->Get();
if ( !ob ) {
continue;
}
const Material* mat = dynamic_cast<const Material*>( ob );
if ( mat ) {
if ( materials_converted.find( mat ) == materials_converted.end() ) {
ConvertMaterial( *mat, 0 );
}
}
}
}
TransferDataToScene();
// if we didn't read any meshes set the AI_SCENE_FLAGS_INCOMPLETE
// to make sure the scene passes assimp's validation. FBX files
// need not contain geometry (i.e. camera animations, raw armatures).
if ( out->mNumMeshes == 0 ) {
out->mFlags |= AI_SCENE_FLAGS_INCOMPLETE;
}
}
Converter::~Converter()
{
std::for_each( meshes.begin(), meshes.end(), Util::delete_fun<aiMesh>() );
std::for_each( materials.begin(), materials.end(), Util::delete_fun<aiMaterial>() );
std::for_each( animations.begin(), animations.end(), Util::delete_fun<aiAnimation>() );
std::for_each( lights.begin(), lights.end(), Util::delete_fun<aiLight>() );
std::for_each( cameras.begin(), cameras.end(), Util::delete_fun<aiCamera>() );
std::for_each( textures.begin(), textures.end(), Util::delete_fun<aiTexture>() );
}
void Converter::ConvertRootNode()
{
out->mRootNode = new aiNode();
out->mRootNode->mName.Set( "RootNode" );
// root has ID 0
ConvertNodes( 0L, *out->mRootNode );
}
void Converter::ConvertNodes( uint64_t id, aiNode& parent, const aiMatrix4x4& parent_transform )
{
const std::vector<const Connection*>& conns = doc.GetConnectionsByDestinationSequenced( id, "Model" );
std::vector<aiNode*> nodes;
nodes.reserve( conns.size() );
std::vector<aiNode*> nodes_chain;
try {
for( const Connection* con : conns ) {
// ignore object-property links
if ( con->PropertyName().length() ) {
continue;
}
const Object* const object = con->SourceObject();
if ( !object ) {
FBXImporter::LogWarn( "failed to convert source object for Model link" );
continue;
}
const Model* const model = dynamic_cast<const Model*>( object );
if ( model ) {
nodes_chain.clear();
aiMatrix4x4 new_abs_transform = parent_transform;
// even though there is only a single input node, the design of
// assimp (or rather: the complicated transformation chain that
// is employed by fbx) means that we may need multiple aiNode's
// to represent a fbx node's transformation.
GenerateTransformationNodeChain( *model, nodes_chain );
ai_assert( nodes_chain.size() );
const std::string& original_name = FixNodeName( model->Name() );
// check if any of the nodes in the chain has the name the fbx node
// is supposed to have. If there is none, add another node to
// preserve the name - people might have scripts etc. that rely
// on specific node names.
aiNode* name_carrier = NULL;
for( aiNode* prenode : nodes_chain ) {
if ( !strcmp( prenode->mName.C_Str(), original_name.c_str() ) ) {
name_carrier = prenode;
break;
}
}
if ( !name_carrier ) {
nodes_chain.push_back( new aiNode( original_name ) );
}
//setup metadata on newest node
SetupNodeMetadata( *model, *nodes_chain.back() );
// link all nodes in a row
aiNode* last_parent = &parent;
for( aiNode* prenode : nodes_chain ) {
ai_assert( prenode );
if ( last_parent != &parent ) {
last_parent->mNumChildren = 1;
last_parent->mChildren = new aiNode*[ 1 ];
last_parent->mChildren[ 0 ] = prenode;
}
prenode->mParent = last_parent;
last_parent = prenode;
new_abs_transform *= prenode->mTransformation;
}
// attach geometry
ConvertModel( *model, *nodes_chain.back(), new_abs_transform );
// attach sub-nodes
ConvertNodes( model->ID(), *nodes_chain.back(), new_abs_transform );
if ( doc.Settings().readLights ) {
ConvertLights( *model );
}
if ( doc.Settings().readCameras ) {
ConvertCameras( *model );
}
nodes.push_back( nodes_chain.front() );
nodes_chain.clear();
}
}
if ( nodes.size() ) {
parent.mChildren = new aiNode*[ nodes.size() ]();
parent.mNumChildren = static_cast<unsigned int>( nodes.size() );
std::swap_ranges( nodes.begin(), nodes.end(), parent.mChildren );
}
}
catch ( std::exception& ) {
Util::delete_fun<aiNode> deleter;
std::for_each( nodes.begin(), nodes.end(), deleter );
std::for_each( nodes_chain.begin(), nodes_chain.end(), deleter );
}
}
void Converter::ConvertLights( const Model& model )
{
const std::vector<const NodeAttribute*>& node_attrs = model.GetAttributes();
for( const NodeAttribute* attr : node_attrs ) {
const Light* const light = dynamic_cast<const Light*>( attr );
if ( light ) {
ConvertLight( model, *light );
}
}
}
void Converter::ConvertCameras( const Model& model )
{
const std::vector<const NodeAttribute*>& node_attrs = model.GetAttributes();
for( const NodeAttribute* attr : node_attrs ) {
const Camera* const cam = dynamic_cast<const Camera*>( attr );
if ( cam ) {
ConvertCamera( model, *cam );
}
}
}
void Converter::ConvertLight( const Model& model, const Light& light )
{
lights.push_back( new aiLight() );
aiLight* const out_light = lights.back();
out_light->mName.Set( FixNodeName( model.Name() ) );
const float intensity = light.Intensity() / 100.0f;
const aiVector3D& col = light.Color();
out_light->mColorDiffuse = aiColor3D( col.x, col.y, col.z );
out_light->mColorDiffuse.r *= intensity;
out_light->mColorDiffuse.g *= intensity;
out_light->mColorDiffuse.b *= intensity;
out_light->mColorSpecular = out_light->mColorDiffuse;
//lights are defined along negative y direction
out_light->mPosition = aiVector3D(0.0f);
out_light->mDirection = aiVector3D(0.0f, -1.0f, 0.0f);
out_light->mUp = aiVector3D(0.0f, 0.0f, -1.0f);
switch ( light.LightType() )
{
case Light::Type_Point:
out_light->mType = aiLightSource_POINT;
break;
case Light::Type_Directional:
out_light->mType = aiLightSource_DIRECTIONAL;
break;
case Light::Type_Spot:
out_light->mType = aiLightSource_SPOT;
out_light->mAngleOuterCone = AI_DEG_TO_RAD( light.OuterAngle() );
out_light->mAngleInnerCone = AI_DEG_TO_RAD( light.InnerAngle() );
break;
case Light::Type_Area:
FBXImporter::LogWarn( "cannot represent area light, set to UNDEFINED" );
out_light->mType = aiLightSource_UNDEFINED;
break;
case Light::Type_Volume:
FBXImporter::LogWarn( "cannot represent volume light, set to UNDEFINED" );
out_light->mType = aiLightSource_UNDEFINED;
break;
default:
ai_assert( false );
}
float decay = light.DecayStart();
switch ( light.DecayType() )
{
case Light::Decay_None:
out_light->mAttenuationConstant = decay;
out_light->mAttenuationLinear = 0.0f;
out_light->mAttenuationQuadratic = 0.0f;
break;
case Light::Decay_Linear:
out_light->mAttenuationConstant = 0.0f;
out_light->mAttenuationLinear = 2.0f / decay;
out_light->mAttenuationQuadratic = 0.0f;
break;
case Light::Decay_Quadratic:
out_light->mAttenuationConstant = 0.0f;
out_light->mAttenuationLinear = 0.0f;
out_light->mAttenuationQuadratic = 2.0f / (decay * decay);
break;
case Light::Decay_Cubic:
FBXImporter::LogWarn( "cannot represent cubic attenuation, set to Quadratic" );
out_light->mAttenuationQuadratic = 1.0f;
break;
default:
ai_assert( false );
}
}
void Converter::ConvertCamera( const Model& model, const Camera& cam )
{
cameras.push_back( new aiCamera() );
aiCamera* const out_camera = cameras.back();
out_camera->mName.Set( FixNodeName( model.Name() ) );
out_camera->mAspect = cam.AspectWidth() / cam.AspectHeight();
//cameras are defined along positive x direction
out_camera->mPosition = aiVector3D(0.0f);
out_camera->mLookAt = aiVector3D(1.0f, 0.0f, 0.0f);
out_camera->mUp = aiVector3D(0.0f, 1.0f, 0.0f);
out_camera->mHorizontalFOV = AI_DEG_TO_RAD( cam.FieldOfView() );
out_camera->mClipPlaneNear = cam.NearPlane();
out_camera->mClipPlaneFar = cam.FarPlane();
}
const char* Converter::NameTransformationComp( TransformationComp comp )
{
switch ( comp )
{
case TransformationComp_Translation:
return "Translation";
case TransformationComp_RotationOffset:
return "RotationOffset";
case TransformationComp_RotationPivot:
return "RotationPivot";
case TransformationComp_PreRotation:
return "PreRotation";
case TransformationComp_Rotation:
return "Rotation";
case TransformationComp_PostRotation:
return "PostRotation";
case TransformationComp_RotationPivotInverse:
return "RotationPivotInverse";
case TransformationComp_ScalingOffset:
return "ScalingOffset";
case TransformationComp_ScalingPivot:
return "ScalingPivot";
case TransformationComp_Scaling:
return "Scaling";
case TransformationComp_ScalingPivotInverse:
return "ScalingPivotInverse";
case TransformationComp_GeometricScaling:
return "GeometricScaling";
case TransformationComp_GeometricRotation:
return "GeometricRotation";
case TransformationComp_GeometricTranslation:
return "GeometricTranslation";
case TransformationComp_MAXIMUM: // this is to silence compiler warnings
default:
break;
}
ai_assert( false );
return NULL;
}
const char* Converter::NameTransformationCompProperty( TransformationComp comp )
{
switch ( comp )
{
case TransformationComp_Translation:
return "Lcl Translation";
case TransformationComp_RotationOffset:
return "RotationOffset";
case TransformationComp_RotationPivot:
return "RotationPivot";
case TransformationComp_PreRotation:
return "PreRotation";
case TransformationComp_Rotation:
return "Lcl Rotation";
case TransformationComp_PostRotation:
return "PostRotation";
case TransformationComp_RotationPivotInverse:
return "RotationPivotInverse";
case TransformationComp_ScalingOffset:
return "ScalingOffset";
case TransformationComp_ScalingPivot:
return "ScalingPivot";
case TransformationComp_Scaling:
return "Lcl Scaling";
case TransformationComp_ScalingPivotInverse:
return "ScalingPivotInverse";
case TransformationComp_GeometricScaling:
return "GeometricScaling";
case TransformationComp_GeometricRotation:
return "GeometricRotation";
case TransformationComp_GeometricTranslation:
return "GeometricTranslation";
case TransformationComp_MAXIMUM: // this is to silence compiler warnings
break;
}
ai_assert( false );
return NULL;
}
aiVector3D Converter::TransformationCompDefaultValue( TransformationComp comp )
{
// XXX a neat way to solve the never-ending special cases for scaling
// would be to do everything in log space!
return comp == TransformationComp_Scaling ? aiVector3D( 1.f, 1.f, 1.f ) : aiVector3D();
}
void Converter::GetRotationMatrix( Model::RotOrder mode, const aiVector3D& rotation, aiMatrix4x4& out )
{
if ( mode == Model::RotOrder_SphericXYZ ) {
FBXImporter::LogError( "Unsupported RotationMode: SphericXYZ" );
out = aiMatrix4x4();
return;
}
const float angle_epsilon = 1e-6f;
out = aiMatrix4x4();
bool is_id[ 3 ] = { true, true, true };
aiMatrix4x4 temp[ 3 ];
if ( std::fabs( rotation.z ) > angle_epsilon ) {
aiMatrix4x4::RotationZ( AI_DEG_TO_RAD( rotation.z ), temp[ 2 ] );
is_id[ 2 ] = false;
}
if ( std::fabs( rotation.y ) > angle_epsilon ) {
aiMatrix4x4::RotationY( AI_DEG_TO_RAD( rotation.y ), temp[ 1 ] );
is_id[ 1 ] = false;
}
if ( std::fabs( rotation.x ) > angle_epsilon ) {
aiMatrix4x4::RotationX( AI_DEG_TO_RAD( rotation.x ), temp[ 0 ] );
is_id[ 0 ] = false;
}
int order[ 3 ] = { -1, -1, -1 };
// note: rotation order is inverted since we're left multiplying as is usual in assimp
switch ( mode )
{
case Model::RotOrder_EulerXYZ:
order[ 0 ] = 2;
order[ 1 ] = 1;
order[ 2 ] = 0;
break;
case Model::RotOrder_EulerXZY:
order[ 0 ] = 1;
order[ 1 ] = 2;
order[ 2 ] = 0;
break;
case Model::RotOrder_EulerYZX:
order[ 0 ] = 0;
order[ 1 ] = 2;
order[ 2 ] = 1;
break;
case Model::RotOrder_EulerYXZ:
order[ 0 ] = 2;
order[ 1 ] = 0;
order[ 2 ] = 1;
break;
case Model::RotOrder_EulerZXY:
order[ 0 ] = 1;
order[ 1 ] = 0;
order[ 2 ] = 2;
break;
case Model::RotOrder_EulerZYX:
order[ 0 ] = 0;
order[ 1 ] = 1;
order[ 2 ] = 2;
break;
default:
ai_assert( false );
}
ai_assert( ( order[ 0 ] >= 0 ) && ( order[ 0 ] <= 2 ) );
ai_assert( ( order[ 1 ] >= 0 ) && ( order[ 1 ] <= 2 ) );
ai_assert( ( order[ 2 ] >= 0 ) && ( order[ 2 ] <= 2 ) );
if ( !is_id[ order[ 0 ] ] ) {
out = temp[ order[ 0 ] ];
}
if ( !is_id[ order[ 1 ] ] ) {
out = out * temp[ order[ 1 ] ];
}
if ( !is_id[ order[ 2 ] ] ) {
out = out * temp[ order[ 2 ] ];
}
}
bool Converter::NeedsComplexTransformationChain( const Model& model )
{
const PropertyTable& props = model.Props();
bool ok;
const float zero_epsilon = 1e-6f;
for ( size_t i = 0; i < TransformationComp_MAXIMUM; ++i ) {
const TransformationComp comp = static_cast< TransformationComp >( i );
if ( comp == TransformationComp_Rotation || comp == TransformationComp_Scaling || comp == TransformationComp_Translation ||
comp == TransformationComp_GeometricScaling || comp == TransformationComp_GeometricRotation || comp == TransformationComp_GeometricTranslation ) {
continue;
}
const aiVector3D& v = PropertyGet<aiVector3D>( props, NameTransformationCompProperty( comp ), ok );
if ( ok && v.SquareLength() > zero_epsilon ) {
return true;
}
}
return false;
}
std::string Converter::NameTransformationChainNode( const std::string& name, TransformationComp comp )
{
return name + std::string( MAGIC_NODE_TAG ) + "_" + NameTransformationComp( comp );
}
void Converter::GenerateTransformationNodeChain( const Model& model, std::vector<aiNode*>& output_nodes )
{
const PropertyTable& props = model.Props();
const Model::RotOrder rot = model.RotationOrder();
bool ok;
aiMatrix4x4 chain[ TransformationComp_MAXIMUM ];
std::fill_n( chain, static_cast<unsigned int>( TransformationComp_MAXIMUM ), aiMatrix4x4() );
// generate transformation matrices for all the different transformation components
const float zero_epsilon = 1e-6f;
bool is_complex = false;
const aiVector3D& PreRotation = PropertyGet<aiVector3D>( props, "PreRotation", ok );
if ( ok && PreRotation.SquareLength() > zero_epsilon ) {
is_complex = true;
GetRotationMatrix( rot, PreRotation, chain[ TransformationComp_PreRotation ] );
}
const aiVector3D& PostRotation = PropertyGet<aiVector3D>( props, "PostRotation", ok );
if ( ok && PostRotation.SquareLength() > zero_epsilon ) {
is_complex = true;
GetRotationMatrix( rot, PostRotation, chain[ TransformationComp_PostRotation ] );
}
const aiVector3D& RotationPivot = PropertyGet<aiVector3D>( props, "RotationPivot", ok );
if ( ok && RotationPivot.SquareLength() > zero_epsilon ) {
is_complex = true;
aiMatrix4x4::Translation( RotationPivot, chain[ TransformationComp_RotationPivot ] );
aiMatrix4x4::Translation( -RotationPivot, chain[ TransformationComp_RotationPivotInverse ] );
}
const aiVector3D& RotationOffset = PropertyGet<aiVector3D>( props, "RotationOffset", ok );
if ( ok && RotationOffset.SquareLength() > zero_epsilon ) {
is_complex = true;
aiMatrix4x4::Translation( RotationOffset, chain[ TransformationComp_RotationOffset ] );
}
const aiVector3D& ScalingOffset = PropertyGet<aiVector3D>( props, "ScalingOffset", ok );
if ( ok && ScalingOffset.SquareLength() > zero_epsilon ) {
is_complex = true;
aiMatrix4x4::Translation( ScalingOffset, chain[ TransformationComp_ScalingOffset ] );
}
const aiVector3D& ScalingPivot = PropertyGet<aiVector3D>( props, "ScalingPivot", ok );
if ( ok && ScalingPivot.SquareLength() > zero_epsilon ) {