forked from assimp/assimp
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathColladaLoader.cpp
1483 lines (1266 loc) · 57.8 KB
/
ColladaLoader.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-2010, ASSIMP Development 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 Development 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 Implementation of the Collada loader */
#include "AssimpPCH.h"
#ifndef ASSIMP_BUILD_NO_DAE_IMPORTER
#include "../include/aiAnim.h"
#include "ColladaLoader.h"
#include "ColladaParser.h"
#include "fast_atof.h"
#include "ParsingUtils.h"
#include "SkeletonMeshBuilder.h"
#include "time.h"
using namespace Assimp;
// ------------------------------------------------------------------------------------------------
// Constructor to be privately used by Importer
ColladaLoader::ColladaLoader()
{}
// ------------------------------------------------------------------------------------------------
// Destructor, private as well
ColladaLoader::~ColladaLoader()
{}
// ------------------------------------------------------------------------------------------------
// Returns whether the class can handle the format of the given file.
bool ColladaLoader::CanRead( const std::string& pFile, IOSystem* pIOHandler, bool checkSig) const
{
// check file extension
std::string extension = GetExtension(pFile);
if( extension == "dae")
return true;
// XML - too generic, we need to open the file and search for typical keywords
if( extension == "xml" || !extension.length() || checkSig) {
/* If CanRead() is called in order to check whether we
* support a specific file extension in general pIOHandler
* might be NULL and it's our duty to return true here.
*/
if (!pIOHandler)return true;
const char* tokens[] = {"collada"};
return SearchFileHeaderForToken(pIOHandler,pFile,tokens,1);
}
return false;
}
// ------------------------------------------------------------------------------------------------
// Get file extension list
void ColladaLoader::GetExtensionList( std::set<std::string>& extensions )
{
extensions.insert("dae");
}
// ------------------------------------------------------------------------------------------------
// Imports the given file into the given scene structure.
void ColladaLoader::InternReadFile( const std::string& pFile, aiScene* pScene, IOSystem* pIOHandler)
{
mFileName = pFile;
// clean all member arrays - just for safety, it should work even if we did not
mMeshIndexByID.clear();
mMaterialIndexByName.clear();
mMeshes.clear();
newMats.clear();
mLights.clear();
mCameras.clear();
mTextures.clear();
// parse the input file
ColladaParser parser( pIOHandler, pFile);
if( !parser.mRootNode)
throw DeadlyImportError( "Collada: File came out empty. Something is wrong here.");
// reserve some storage to avoid unnecessary reallocs
newMats.reserve(parser.mMaterialLibrary.size()*2);
mMeshes.reserve(parser.mMeshLibrary.size()*2);
mCameras.reserve(parser.mCameraLibrary.size());
mLights.reserve(parser.mLightLibrary.size());
// create the materials first, for the meshes to find
BuildMaterials( parser, pScene);
// build the node hierarchy from it
pScene->mRootNode = BuildHierarchy( parser, parser.mRootNode);
// ... then fill the materials with the now adjusted settings
FillMaterials(parser, pScene);
// Convert to Y_UP, if different orientation
if( parser.mUpDirection == ColladaParser::UP_X)
pScene->mRootNode->mTransformation *= aiMatrix4x4(
0, -1, 0, 0,
1, 0, 0, 0,
0, 0, 1, 0,
0, 0, 0, 1);
else if( parser.mUpDirection == ColladaParser::UP_Z)
pScene->mRootNode->mTransformation *= aiMatrix4x4(
1, 0, 0, 0,
0, 0, 1, 0,
0, -1, 0, 0,
0, 0, 0, 1);
// store all meshes
StoreSceneMeshes( pScene);
// store all materials
StoreSceneMaterials( pScene);
// store all lights
StoreSceneLights( pScene);
// store all cameras
StoreSceneCameras( pScene);
// store all animations
StoreAnimations( pScene, parser);
// If no meshes have been loaded, it's probably just an animated skeleton.
if (!pScene->mNumMeshes) {
SkeletonMeshBuilder hero(pScene);
pScene->mFlags |= AI_SCENE_FLAGS_INCOMPLETE;
}
}
// ------------------------------------------------------------------------------------------------
// Recursively constructs a scene node for the given parser node and returns it.
aiNode* ColladaLoader::BuildHierarchy( const ColladaParser& pParser, const Collada::Node* pNode)
{
// create a node for it
aiNode* node = new aiNode();
// find a name for the new node. It's more complicated than you might think
node->mName.Set( FindNameForNode( pNode));
// calculate the transformation matrix for it
node->mTransformation = pParser.CalculateResultTransform( pNode->mTransforms);
// now resolve node instances
std::vector<const Collada::Node*> instances;
ResolveNodeInstances(pParser,pNode,instances);
// add children. first the *real* ones
node->mNumChildren = pNode->mChildren.size()+instances.size();
node->mChildren = new aiNode*[node->mNumChildren];
for( size_t a = 0; a < pNode->mChildren.size(); a++)
{
node->mChildren[a] = BuildHierarchy( pParser, pNode->mChildren[a]);
node->mChildren[a]->mParent = node;
}
// ... and finally the resolved node instances
for( size_t a = 0; a < instances.size(); a++)
{
node->mChildren[pNode->mChildren.size() + a] = BuildHierarchy( pParser, instances[a]);
node->mChildren[pNode->mChildren.size() + a]->mParent = node;
}
// construct meshes
BuildMeshesForNode( pParser, pNode, node);
// construct cameras
BuildCamerasForNode(pParser, pNode, node);
// construct lights
BuildLightsForNode(pParser, pNode, node);
return node;
}
// ------------------------------------------------------------------------------------------------
// Resolve node instances
void ColladaLoader::ResolveNodeInstances( const ColladaParser& pParser, const Collada::Node* pNode,
std::vector<const Collada::Node*>& resolved)
{
// reserve enough storage
resolved.reserve(pNode->mNodeInstances.size());
// ... and iterate through all nodes to be instanced as children of pNode
for (std::vector<Collada::NodeInstance>::const_iterator it = pNode->mNodeInstances.begin(),
end = pNode->mNodeInstances.end(); it != end; ++it)
{
// find the corresponding node in the library
const ColladaParser::NodeLibrary::const_iterator itt = pParser.mNodeLibrary.find((*it).mNode);
Collada::Node* nd = itt == pParser.mNodeLibrary.end() ? NULL : (*itt).second;
// FIX for http://sourceforge.net/tracker/?func=detail&aid=3054873&group_id=226462&atid=1067632
// need to check for both name and ID to catch all. To avoid breaking valid files,
// the workaround is only enabled when the first attempt to resolve the node has failed.
if (!nd) {
nd = const_cast<Collada::Node*>(FindNode(pParser.mRootNode,(*it).mNode));
}
if (!nd)
DefaultLogger::get()->error("Collada: Unable to resolve reference to instanced node " + (*it).mNode);
else {
// attach this node to the list of children
resolved.push_back(nd);
}
}
}
// ------------------------------------------------------------------------------------------------
// Resolve UV channels
void ColladaLoader::ApplyVertexToEffectSemanticMapping(Collada::Sampler& sampler,
const Collada::SemanticMappingTable& table)
{
std::map<std::string, Collada::InputSemanticMapEntry>::const_iterator it = table.mMap.find(sampler.mUVChannel);
if (it != table.mMap.end()) {
if (it->second.mType != Collada::IT_Texcoord)
DefaultLogger::get()->error("Collada: Unexpected effect input mapping");
sampler.mUVId = it->second.mSet;
}
}
// ------------------------------------------------------------------------------------------------
// Builds lights for the given node and references them
void ColladaLoader::BuildLightsForNode( const ColladaParser& pParser, const Collada::Node* pNode, aiNode* pTarget)
{
BOOST_FOREACH( const Collada::LightInstance& lid, pNode->mLights)
{
// find the referred light
ColladaParser::LightLibrary::const_iterator srcLightIt = pParser.mLightLibrary.find( lid.mLight);
if( srcLightIt == pParser.mLightLibrary.end())
{
DefaultLogger::get()->warn("Collada: Unable to find light for ID \"" + lid.mLight + "\". Skipping.");
continue;
}
const Collada::Light* srcLight = &srcLightIt->second;
if (srcLight->mType == aiLightSource_AMBIENT) {
DefaultLogger::get()->error("Collada: Skipping ambient light for the moment");
continue;
}
// now fill our ai data structure
aiLight* out = new aiLight();
out->mName = pTarget->mName;
out->mType = (aiLightSourceType)srcLight->mType;
// collada lights point in -Z by default, rest is specified in node transform
out->mDirection = aiVector3D(0.f,0.f,-1.f);
out->mAttenuationConstant = srcLight->mAttConstant;
out->mAttenuationLinear = srcLight->mAttLinear;
out->mAttenuationQuadratic = srcLight->mAttQuadratic;
// collada doesn't differenciate between these color types
out->mColorDiffuse = out->mColorSpecular = out->mColorAmbient = srcLight->mColor*srcLight->mIntensity;
// convert falloff angle and falloff exponent in our representation, if given
if (out->mType == aiLightSource_SPOT) {
out->mAngleInnerCone = AI_DEG_TO_RAD( srcLight->mFalloffAngle );
// ... some extension magic. FUCKING COLLADA.
if (srcLight->mOuterAngle == 10e10f)
{
// ... some deprecation magic. FUCKING FCOLLADA.
if (srcLight->mPenumbraAngle == 10e10f)
{
// Need to rely on falloff_exponent. I don't know how to interpret it, so I need to guess ....
// epsilon chosen to be 0.1
out->mAngleOuterCone = AI_DEG_TO_RAD (acos(pow(0.1f,1.f/srcLight->mFalloffExponent))+
srcLight->mFalloffAngle);
}
else {
out->mAngleOuterCone = out->mAngleInnerCone + AI_DEG_TO_RAD( srcLight->mPenumbraAngle );
if (out->mAngleOuterCone < out->mAngleInnerCone)
std::swap(out->mAngleInnerCone,out->mAngleOuterCone);
}
}
else out->mAngleOuterCone = AI_DEG_TO_RAD( srcLight->mOuterAngle );
}
// add to light list
mLights.push_back(out);
}
}
// ------------------------------------------------------------------------------------------------
// Builds cameras for the given node and references them
void ColladaLoader::BuildCamerasForNode( const ColladaParser& pParser, const Collada::Node* pNode, aiNode* pTarget)
{
BOOST_FOREACH( const Collada::CameraInstance& cid, pNode->mCameras)
{
// find the referred light
ColladaParser::CameraLibrary::const_iterator srcCameraIt = pParser.mCameraLibrary.find( cid.mCamera);
if( srcCameraIt == pParser.mCameraLibrary.end())
{
DefaultLogger::get()->warn("Collada: Unable to find camera for ID \"" + cid.mCamera + "\". Skipping.");
continue;
}
const Collada::Camera* srcCamera = &srcCameraIt->second;
// orthographic cameras not yet supported in Assimp
if (srcCamera->mOrtho) {
DefaultLogger::get()->warn("Collada: Orthographic cameras are not supported.");
}
// now fill our ai data structure
aiCamera* out = new aiCamera();
out->mName = pTarget->mName;
// collada cameras point in -Z by default, rest is specified in node transform
out->mLookAt = aiVector3D(0.f,0.f,-1.f);
// near/far z is already ok
out->mClipPlaneFar = srcCamera->mZFar;
out->mClipPlaneNear = srcCamera->mZNear;
// ... but for the rest some values are optional
// and we need to compute the others in any combination. FUCKING COLLADA.
if (srcCamera->mAspect != 10e10f)
out->mAspect = srcCamera->mAspect;
if (srcCamera->mHorFov != 10e10f) {
out->mHorizontalFOV = srcCamera->mHorFov;
if (srcCamera->mVerFov != 10e10f && srcCamera->mAspect == 10e10f) {
out->mAspect = tan(AI_DEG_TO_RAD(srcCamera->mHorFov)) /
tan(AI_DEG_TO_RAD(srcCamera->mVerFov));
}
}
else if (srcCamera->mAspect != 10e10f && srcCamera->mVerFov != 10e10f) {
out->mHorizontalFOV = 2.0f * AI_RAD_TO_DEG(atan(srcCamera->mAspect *
tan(AI_DEG_TO_RAD(srcCamera->mVerFov) * 0.5f)));
}
// Collada uses degrees, we use radians
out->mHorizontalFOV = AI_DEG_TO_RAD(out->mHorizontalFOV);
// add to camera list
mCameras.push_back(out);
}
}
// ------------------------------------------------------------------------------------------------
// Builds meshes for the given node and references them
void ColladaLoader::BuildMeshesForNode( const ColladaParser& pParser, const Collada::Node* pNode, aiNode* pTarget)
{
// accumulated mesh references by this node
std::vector<size_t> newMeshRefs;
newMeshRefs.reserve(pNode->mMeshes.size());
// add a mesh for each subgroup in each collada mesh
BOOST_FOREACH( const Collada::MeshInstance& mid, pNode->mMeshes)
{
const Collada::Mesh* srcMesh = NULL;
const Collada::Controller* srcController = NULL;
// find the referred mesh
ColladaParser::MeshLibrary::const_iterator srcMeshIt = pParser.mMeshLibrary.find( mid.mMeshOrController);
if( srcMeshIt == pParser.mMeshLibrary.end())
{
// if not found in the mesh-library, it might also be a controller referring to a mesh
ColladaParser::ControllerLibrary::const_iterator srcContrIt = pParser.mControllerLibrary.find( mid.mMeshOrController);
if( srcContrIt != pParser.mControllerLibrary.end())
{
srcController = &srcContrIt->second;
srcMeshIt = pParser.mMeshLibrary.find( srcController->mMeshId);
if( srcMeshIt != pParser.mMeshLibrary.end())
srcMesh = srcMeshIt->second;
}
if( !srcMesh)
{
DefaultLogger::get()->warn( boost::str( boost::format( "Collada: Unable to find geometry for ID \"%s\". Skipping.") % mid.mMeshOrController));
continue;
}
} else
{
// ID found in the mesh library -> direct reference to an unskinned mesh
srcMesh = srcMeshIt->second;
}
// build a mesh for each of its subgroups
size_t vertexStart = 0, faceStart = 0;
for( size_t sm = 0; sm < srcMesh->mSubMeshes.size(); ++sm)
{
const Collada::SubMesh& submesh = srcMesh->mSubMeshes[sm];
if( submesh.mNumFaces == 0)
continue;
// find material assigned to this submesh
std::string meshMaterial;
std::map<std::string, Collada::SemanticMappingTable >::const_iterator meshMatIt = mid.mMaterials.find( submesh.mMaterial);
const Collada::SemanticMappingTable* table = NULL;
if( meshMatIt != mid.mMaterials.end())
{
table = &meshMatIt->second;
meshMaterial = table->mMatName;
}
else
{
DefaultLogger::get()->warn( boost::str( boost::format( "Collada: No material specified for subgroup \"%s\" in geometry \"%s\".") % submesh.mMaterial % mid.mMeshOrController));
if( !mid.mMaterials.empty() )
meshMaterial = mid.mMaterials.begin()->second.mMatName;
}
// OK ... here the *real* fun starts ... we have the vertex-input-to-effect-semantic-table
// given. The only mapping stuff which we do actually support is the UV channel.
std::map<std::string, size_t>::const_iterator matIt = mMaterialIndexByName.find( meshMaterial);
unsigned int matIdx;
if( matIt != mMaterialIndexByName.end())
matIdx = matIt->second;
else
matIdx = 0;
if (table && !table->mMap.empty() ) {
std::pair<Collada::Effect*, aiMaterial*>& mat = newMats[matIdx];
// Iterate through all texture channels assigned to the effect and
// check whether we have mapping information for it.
ApplyVertexToEffectSemanticMapping(mat.first->mTexDiffuse, *table);
ApplyVertexToEffectSemanticMapping(mat.first->mTexAmbient, *table);
ApplyVertexToEffectSemanticMapping(mat.first->mTexSpecular, *table);
ApplyVertexToEffectSemanticMapping(mat.first->mTexEmissive, *table);
ApplyVertexToEffectSemanticMapping(mat.first->mTexTransparent,*table);
ApplyVertexToEffectSemanticMapping(mat.first->mTexBump, *table);
}
// built lookup index of the Mesh-Submesh-Material combination
ColladaMeshIndex index( mid.mMeshOrController, sm, meshMaterial);
// if we already have the mesh at the library, just add its index to the node's array
std::map<ColladaMeshIndex, size_t>::const_iterator dstMeshIt = mMeshIndexByID.find( index);
if( dstMeshIt != mMeshIndexByID.end()) {
newMeshRefs.push_back( dstMeshIt->second);
}
else
{
// else we have to add the mesh to the collection and store its newly assigned index at the node
aiMesh* dstMesh = CreateMesh( pParser, srcMesh, submesh, srcController, vertexStart, faceStart);
// store the mesh, and store its new index in the node
newMeshRefs.push_back( mMeshes.size());
mMeshIndexByID[index] = mMeshes.size();
mMeshes.push_back( dstMesh);
vertexStart += dstMesh->mNumVertices; faceStart += submesh.mNumFaces;
// assign the material index
dstMesh->mMaterialIndex = matIdx;
}
}
}
// now place all mesh references we gathered in the target node
pTarget->mNumMeshes = newMeshRefs.size();
if( newMeshRefs.size())
{
pTarget->mMeshes = new unsigned int[pTarget->mNumMeshes];
std::copy( newMeshRefs.begin(), newMeshRefs.end(), pTarget->mMeshes);
}
}
// ------------------------------------------------------------------------------------------------
// Creates a mesh for the given ColladaMesh face subset and returns the newly created mesh
aiMesh* ColladaLoader::CreateMesh( const ColladaParser& pParser, const Collada::Mesh* pSrcMesh, const Collada::SubMesh& pSubMesh,
const Collada::Controller* pSrcController, size_t pStartVertex, size_t pStartFace)
{
aiMesh* dstMesh = new aiMesh;
// count the vertices addressed by its faces
const size_t numVertices = std::accumulate( pSrcMesh->mFaceSize.begin() + pStartFace,
pSrcMesh->mFaceSize.begin() + pStartFace + pSubMesh.mNumFaces, 0);
// copy positions
dstMesh->mNumVertices = numVertices;
dstMesh->mVertices = new aiVector3D[numVertices];
std::copy( pSrcMesh->mPositions.begin() + pStartVertex, pSrcMesh->mPositions.begin() +
pStartVertex + numVertices, dstMesh->mVertices);
// normals, if given. HACK: (thom) Due to the fucking Collada spec we never
// know if we have the same number of normals as there are positions. So we
// also ignore any vertex attribute if it has a different count
if( pSrcMesh->mNormals.size() >= pStartVertex + numVertices)
{
dstMesh->mNormals = new aiVector3D[numVertices];
std::copy( pSrcMesh->mNormals.begin() + pStartVertex, pSrcMesh->mNormals.begin() +
pStartVertex + numVertices, dstMesh->mNormals);
}
// tangents, if given.
if( pSrcMesh->mTangents.size() >= pStartVertex + numVertices)
{
dstMesh->mTangents = new aiVector3D[numVertices];
std::copy( pSrcMesh->mTangents.begin() + pStartVertex, pSrcMesh->mTangents.begin() +
pStartVertex + numVertices, dstMesh->mTangents);
}
// bitangents, if given.
if( pSrcMesh->mBitangents.size() >= pStartVertex + numVertices)
{
dstMesh->mBitangents = new aiVector3D[numVertices];
std::copy( pSrcMesh->mBitangents.begin() + pStartVertex, pSrcMesh->mBitangents.begin() +
pStartVertex + numVertices, dstMesh->mBitangents);
}
// same for texturecoords, as many as we have
// empty slots are not allowed, need to pack and adjust UV indexes accordingly
for( size_t a = 0, real = 0; a < AI_MAX_NUMBER_OF_TEXTURECOORDS; a++)
{
if( pSrcMesh->mTexCoords[a].size() >= pStartVertex + numVertices)
{
dstMesh->mTextureCoords[real] = new aiVector3D[numVertices];
for( size_t b = 0; b < numVertices; ++b)
dstMesh->mTextureCoords[real][b] = pSrcMesh->mTexCoords[a][pStartVertex+b];
dstMesh->mNumUVComponents[real] = pSrcMesh->mNumUVComponents[a];
++real;
}
}
// same for vertex colors, as many as we have. again the same packing to avoid empty slots
for( size_t a = 0, real = 0; a < AI_MAX_NUMBER_OF_COLOR_SETS; a++)
{
if( pSrcMesh->mColors[a].size() >= pStartVertex + numVertices)
{
dstMesh->mColors[real] = new aiColor4D[numVertices];
std::copy( pSrcMesh->mColors[a].begin() + pStartVertex, pSrcMesh->mColors[a].begin() + pStartVertex + numVertices,dstMesh->mColors[real]);
++real;
}
}
// create faces. Due to the fact that each face uses unique vertices, we can simply count up on each vertex
size_t vertex = 0;
dstMesh->mNumFaces = pSubMesh.mNumFaces;
dstMesh->mFaces = new aiFace[dstMesh->mNumFaces];
for( size_t a = 0; a < dstMesh->mNumFaces; ++a)
{
size_t s = pSrcMesh->mFaceSize[ pStartFace + a];
aiFace& face = dstMesh->mFaces[a];
face.mNumIndices = s;
face.mIndices = new unsigned int[s];
for( size_t b = 0; b < s; ++b)
face.mIndices[b] = vertex++;
}
// create bones if given
if( pSrcController)
{
// refuse if the vertex count does not match
// if( pSrcController->mWeightCounts.size() != dstMesh->mNumVertices)
// throw DeadlyImportError( "Joint Controller vertex count does not match mesh vertex count");
// resolve references - joint names
const Collada::Accessor& jointNamesAcc = pParser.ResolveLibraryReference( pParser.mAccessorLibrary, pSrcController->mJointNameSource);
const Collada::Data& jointNames = pParser.ResolveLibraryReference( pParser.mDataLibrary, jointNamesAcc.mSource);
// joint offset matrices
const Collada::Accessor& jointMatrixAcc = pParser.ResolveLibraryReference( pParser.mAccessorLibrary, pSrcController->mJointOffsetMatrixSource);
const Collada::Data& jointMatrices = pParser.ResolveLibraryReference( pParser.mDataLibrary, jointMatrixAcc.mSource);
// joint vertex_weight name list - should refer to the same list as the joint names above. If not, report and reconsider
const Collada::Accessor& weightNamesAcc = pParser.ResolveLibraryReference( pParser.mAccessorLibrary, pSrcController->mWeightInputJoints.mAccessor);
if( &weightNamesAcc != &jointNamesAcc)
throw DeadlyImportError( "Temporary implementational lazyness. If you read this, please report to the author.");
// vertex weights
const Collada::Accessor& weightsAcc = pParser.ResolveLibraryReference( pParser.mAccessorLibrary, pSrcController->mWeightInputWeights.mAccessor);
const Collada::Data& weights = pParser.ResolveLibraryReference( pParser.mDataLibrary, weightsAcc.mSource);
if( !jointNames.mIsStringArray || jointMatrices.mIsStringArray || weights.mIsStringArray)
throw DeadlyImportError( "Data type mismatch while resolving mesh joints");
// sanity check: we rely on the vertex weights always coming as pairs of BoneIndex-WeightIndex
if( pSrcController->mWeightInputJoints.mOffset != 0 || pSrcController->mWeightInputWeights.mOffset != 1)
throw DeadlyImportError( "Unsupported vertex_weight adresssing scheme. Fucking collada spec.");
// create containers to collect the weights for each bone
size_t numBones = jointNames.mStrings.size();
std::vector<std::vector<aiVertexWeight> > dstBones( numBones);
// build a temporary array of pointers to the start of each vertex's weights
typedef std::vector< std::pair<size_t, size_t> > IndexPairVector;
std::vector<IndexPairVector::const_iterator> weightStartPerVertex( pSrcController->mWeightCounts.size());
IndexPairVector::const_iterator pit = pSrcController->mWeights.begin();
for( size_t a = 0; a < pSrcController->mWeightCounts.size(); ++a)
{
weightStartPerVertex[a] = pit;
pit += pSrcController->mWeightCounts[a];
}
// now for each vertex put the corresponding vertex weights into each bone's weight collection
for( size_t a = pStartVertex; a < pStartVertex + numVertices; ++a)
{
// which position index was responsible for this vertex? that's also the index by which
// the controller assigns the vertex weights
size_t orgIndex = pSrcMesh->mFacePosIndices[a];
// find the vertex weights for this vertex
IndexPairVector::const_iterator iit = weightStartPerVertex[orgIndex];
size_t pairCount = pSrcController->mWeightCounts[orgIndex];
for( size_t b = 0; b < pairCount; ++b, ++iit)
{
size_t jointIndex = iit->first;
size_t vertexIndex = iit->second;
float weight = ReadFloat( weightsAcc, weights, vertexIndex, 0);
// one day I gonna kill that XSI Collada exporter
if( weight > 0.0f)
{
aiVertexWeight w;
w.mVertexId = a - pStartVertex;
w.mWeight = weight;
dstBones[jointIndex].push_back( w);
}
}
}
// count the number of bones which influence vertices of the current submesh
size_t numRemainingBones = 0;
for( std::vector<std::vector<aiVertexWeight> >::const_iterator it = dstBones.begin(); it != dstBones.end(); ++it)
if( it->size() > 0)
numRemainingBones++;
// create bone array and copy bone weights one by one
dstMesh->mNumBones = numRemainingBones;
dstMesh->mBones = new aiBone*[numRemainingBones];
size_t boneCount = 0;
for( size_t a = 0; a < numBones; ++a)
{
// omit bones without weights
if( dstBones[a].size() == 0)
continue;
// create bone with its weights
aiBone* bone = new aiBone;
bone->mName = ReadString( jointNamesAcc, jointNames, a);
bone->mOffsetMatrix.a1 = ReadFloat( jointMatrixAcc, jointMatrices, a, 0);
bone->mOffsetMatrix.a2 = ReadFloat( jointMatrixAcc, jointMatrices, a, 1);
bone->mOffsetMatrix.a3 = ReadFloat( jointMatrixAcc, jointMatrices, a, 2);
bone->mOffsetMatrix.a4 = ReadFloat( jointMatrixAcc, jointMatrices, a, 3);
bone->mOffsetMatrix.b1 = ReadFloat( jointMatrixAcc, jointMatrices, a, 4);
bone->mOffsetMatrix.b2 = ReadFloat( jointMatrixAcc, jointMatrices, a, 5);
bone->mOffsetMatrix.b3 = ReadFloat( jointMatrixAcc, jointMatrices, a, 6);
bone->mOffsetMatrix.b4 = ReadFloat( jointMatrixAcc, jointMatrices, a, 7);
bone->mOffsetMatrix.c1 = ReadFloat( jointMatrixAcc, jointMatrices, a, 8);
bone->mOffsetMatrix.c2 = ReadFloat( jointMatrixAcc, jointMatrices, a, 9);
bone->mOffsetMatrix.c3 = ReadFloat( jointMatrixAcc, jointMatrices, a, 10);
bone->mOffsetMatrix.c4 = ReadFloat( jointMatrixAcc, jointMatrices, a, 11);
bone->mNumWeights = dstBones[a].size();
bone->mWeights = new aiVertexWeight[bone->mNumWeights];
std::copy( dstBones[a].begin(), dstBones[a].end(), bone->mWeights);
// apply bind shape matrix to offset matrix
aiMatrix4x4 bindShapeMatrix;
bindShapeMatrix.a1 = pSrcController->mBindShapeMatrix[0];
bindShapeMatrix.a2 = pSrcController->mBindShapeMatrix[1];
bindShapeMatrix.a3 = pSrcController->mBindShapeMatrix[2];
bindShapeMatrix.a4 = pSrcController->mBindShapeMatrix[3];
bindShapeMatrix.b1 = pSrcController->mBindShapeMatrix[4];
bindShapeMatrix.b2 = pSrcController->mBindShapeMatrix[5];
bindShapeMatrix.b3 = pSrcController->mBindShapeMatrix[6];
bindShapeMatrix.b4 = pSrcController->mBindShapeMatrix[7];
bindShapeMatrix.c1 = pSrcController->mBindShapeMatrix[8];
bindShapeMatrix.c2 = pSrcController->mBindShapeMatrix[9];
bindShapeMatrix.c3 = pSrcController->mBindShapeMatrix[10];
bindShapeMatrix.c4 = pSrcController->mBindShapeMatrix[11];
bindShapeMatrix.d1 = pSrcController->mBindShapeMatrix[12];
bindShapeMatrix.d2 = pSrcController->mBindShapeMatrix[13];
bindShapeMatrix.d3 = pSrcController->mBindShapeMatrix[14];
bindShapeMatrix.d4 = pSrcController->mBindShapeMatrix[15];
bone->mOffsetMatrix *= bindShapeMatrix;
// HACK: (thom) Some exporters address the bone nodes by SID, others address them by ID or even name.
// Therefore I added a little name replacement here: I search for the bone's node by either name, ID or SID,
// and replace the bone's name by the node's name so that the user can use the standard
// find-by-name method to associate nodes with bones.
const Collada::Node* bnode = FindNode( pParser.mRootNode, bone->mName.data);
if( !bnode)
bnode = FindNodeBySID( pParser.mRootNode, bone->mName.data);
// assign the name that we would have assigned for the source node
if( bnode)
bone->mName.Set( FindNameForNode( bnode));
else
DefaultLogger::get()->warn( boost::str( boost::format( "ColladaLoader::CreateMesh(): could not find corresponding node for joint \"%s\".") % bone->mName.data));
// and insert bone
dstMesh->mBones[boneCount++] = bone;
}
}
return dstMesh;
}
// ------------------------------------------------------------------------------------------------
// Stores all meshes in the given scene
void ColladaLoader::StoreSceneMeshes( aiScene* pScene)
{
pScene->mNumMeshes = mMeshes.size();
if( mMeshes.size() > 0)
{
pScene->mMeshes = new aiMesh*[mMeshes.size()];
std::copy( mMeshes.begin(), mMeshes.end(), pScene->mMeshes);
mMeshes.clear();
}
}
// ------------------------------------------------------------------------------------------------
// Stores all cameras in the given scene
void ColladaLoader::StoreSceneCameras( aiScene* pScene)
{
pScene->mNumCameras = mCameras.size();
if( mCameras.size() > 0)
{
pScene->mCameras = new aiCamera*[mCameras.size()];
std::copy( mCameras.begin(), mCameras.end(), pScene->mCameras);
mCameras.clear();
}
}
// ------------------------------------------------------------------------------------------------
// Stores all lights in the given scene
void ColladaLoader::StoreSceneLights( aiScene* pScene)
{
pScene->mNumLights = mLights.size();
if( mLights.size() > 0)
{
pScene->mLights = new aiLight*[mLights.size()];
std::copy( mLights.begin(), mLights.end(), pScene->mLights);
mLights.clear();
}
}
// ------------------------------------------------------------------------------------------------
// Stores all textures in the given scene
void ColladaLoader::StoreSceneTextures( aiScene* pScene)
{
pScene->mNumTextures = mTextures.size();
if( mTextures.size() > 0)
{
pScene->mTextures = new aiTexture*[mTextures.size()];
std::copy( mTextures.begin(), mTextures.end(), pScene->mTextures);
mTextures.clear();
}
}
// ------------------------------------------------------------------------------------------------
// Stores all materials in the given scene
void ColladaLoader::StoreSceneMaterials( aiScene* pScene)
{
pScene->mNumMaterials = newMats.size();
if (newMats.size() > 0) {
pScene->mMaterials = new aiMaterial*[newMats.size()];
for (unsigned int i = 0; i < newMats.size();++i)
pScene->mMaterials[i] = newMats[i].second;
newMats.clear();
}
}
// ------------------------------------------------------------------------------------------------
// Stores all animations
void ColladaLoader::StoreAnimations( aiScene* pScene, const ColladaParser& pParser)
{
// recursivly collect all animations from the collada scene
StoreAnimations( pScene, pParser, &pParser.mAnims, "");
// catch special case: many animations with the same length, each affecting only a single node.
// we need to unite all those single-node-anims to a proper combined animation
for( size_t a = 0; a < mAnims.size(); ++a)
{
aiAnimation* templateAnim = mAnims[a];
if( templateAnim->mNumChannels == 1)
{
// search for other single-channel-anims with the same duration
std::vector<size_t> collectedAnimIndices;
for( size_t b = a+1; b < mAnims.size(); ++b)
{
aiAnimation* other = mAnims[b];
if( other->mNumChannels == 1 && other->mDuration == templateAnim->mDuration && other->mTicksPerSecond == templateAnim->mTicksPerSecond )
collectedAnimIndices.push_back( b);
}
// if there are other animations which fit the template anim, combine all channels into a single anim
if( !collectedAnimIndices.empty() )
{
aiAnimation* combinedAnim = new aiAnimation();
combinedAnim->mName = aiString( std::string( "combinedAnim_") + char( '0' + a));
combinedAnim->mDuration = templateAnim->mDuration;
combinedAnim->mTicksPerSecond = templateAnim->mTicksPerSecond;
combinedAnim->mNumChannels = collectedAnimIndices.size() + 1;
combinedAnim->mChannels = new aiNodeAnim*[combinedAnim->mNumChannels];
// add the template anim as first channel by moving its aiNodeAnim to the combined animation
combinedAnim->mChannels[0] = templateAnim->mChannels[0];
templateAnim->mChannels[0] = NULL;
delete templateAnim;
// combined animation replaces template animation in the anim array
mAnims[a] = combinedAnim;
// move the memory of all other anims to the combined anim and erase them from the source anims
for( size_t b = 0; b < collectedAnimIndices.size(); ++b)
{
aiAnimation* srcAnimation = mAnims[collectedAnimIndices[b]];
combinedAnim->mChannels[1 + b] = srcAnimation->mChannels[0];
srcAnimation->mChannels[0] = NULL;
delete srcAnimation;
}
// in a second go, delete all the single-channel-anims that we've stripped from their channels
// back to front to preserve indices - you know, removing an element from a vector moves all elements behind the removed one
while( !collectedAnimIndices.empty() )
{
mAnims.erase( mAnims.begin() + collectedAnimIndices.back());
collectedAnimIndices.pop_back();
}
}
}
}
// now store all anims in the scene
if( !mAnims.empty())
{
pScene->mNumAnimations = mAnims.size();
pScene->mAnimations = new aiAnimation*[mAnims.size()];
std::copy( mAnims.begin(), mAnims.end(), pScene->mAnimations);
}
}
// ------------------------------------------------------------------------------------------------
// Constructs the animations for the given source anim
void ColladaLoader::StoreAnimations( aiScene* pScene, const ColladaParser& pParser, const Collada::Animation* pSrcAnim, const std::string pPrefix)
{
std::string animName = pPrefix.empty() ? pSrcAnim->mName : pPrefix + "_" + pSrcAnim->mName;
// create nested animations, if given
for( std::vector<Collada::Animation*>::const_iterator it = pSrcAnim->mSubAnims.begin(); it != pSrcAnim->mSubAnims.end(); ++it)
StoreAnimations( pScene, pParser, *it, animName);
// create animation channels, if any
if( !pSrcAnim->mChannels.empty())
CreateAnimation( pScene, pParser, pSrcAnim, animName);
}
// ------------------------------------------------------------------------------------------------
// Constructs the animation for the given source anim
void ColladaLoader::CreateAnimation( aiScene* pScene, const ColladaParser& pParser, const Collada::Animation* pSrcAnim, const std::string& pName)
{
// collect a list of animatable nodes
std::vector<const aiNode*> nodes;
CollectNodes( pScene->mRootNode, nodes);
std::vector<aiNodeAnim*> anims;
for( std::vector<const aiNode*>::const_iterator nit = nodes.begin(); nit != nodes.end(); ++nit)
{
// find all the collada anim channels which refer to the current node
std::vector<Collada::ChannelEntry> entries;
std::string nodeName = (*nit)->mName.data;
// find the collada node corresponding to the aiNode
const Collada::Node* srcNode = FindNode( pParser.mRootNode, nodeName);
// ai_assert( srcNode != NULL);
if( !srcNode)
continue;
// now check all channels if they affect the current node
for( std::vector<Collada::AnimationChannel>::const_iterator cit = pSrcAnim->mChannels.begin();
cit != pSrcAnim->mChannels.end(); ++cit)
{
const Collada::AnimationChannel& srcChannel = *cit;
Collada::ChannelEntry entry;
// we except the animation target to be of type "nodeName/transformID.subElement". Ignore all others
// find the slash that separates the node name - there should be only one
std::string::size_type slashPos = srcChannel.mTarget.find( '/');
if( slashPos == std::string::npos)
continue;
if( srcChannel.mTarget.find( '/', slashPos+1) != std::string::npos)
continue;
std::string targetID = srcChannel.mTarget.substr( 0, slashPos);
if( targetID != srcNode->mID)
continue;
// find the dot that separates the transformID - there should be only one or zero
std::string::size_type dotPos = srcChannel.mTarget.find( '.');
if( dotPos != std::string::npos)
{
if( srcChannel.mTarget.find( '.', dotPos+1) != std::string::npos)
continue;
entry.mTransformId = srcChannel.mTarget.substr( slashPos+1, dotPos - slashPos - 1);
std::string subElement = srcChannel.mTarget.substr( dotPos+1);
if( subElement == "ANGLE")
entry.mSubElement = 3; // last number in an Axis-Angle-Transform is the angle
else if( subElement == "X")
entry.mSubElement = 0;
else if( subElement == "Y")
entry.mSubElement = 1;
else if( subElement == "Z")
entry.mSubElement = 2;
else
DefaultLogger::get()->warn( boost::str( boost::format( "Unknown anim subelement \"%s\". Ignoring") % subElement));
} else
{
// no subelement following, transformId is remaining string
entry.mTransformId = srcChannel.mTarget.substr( slashPos+1);
}
// determine which transform step is affected by this channel
entry.mTransformIndex = SIZE_MAX;
for( size_t a = 0; a < srcNode->mTransforms.size(); ++a)
if( srcNode->mTransforms[a].mID == entry.mTransformId)
entry.mTransformIndex = a;
if( entry.mTransformIndex == SIZE_MAX) {
continue;
}
entry.mChannel = &(*cit);
entries.push_back( entry);
}
// if there's no channel affecting the current node, we skip it
if( entries.empty())
continue;
// resolve the data pointers for all anim channels. Find the minimum time while we're at it
float startTime = 1e20f, endTime = -1e20f;
for( std::vector<Collada::ChannelEntry>::iterator it = entries.begin(); it != entries.end(); ++it)
{
Collada::ChannelEntry& e = *it;
e.mTimeAccessor = &pParser.ResolveLibraryReference( pParser.mAccessorLibrary, e.mChannel->mSourceTimes);
e.mTimeData = &pParser.ResolveLibraryReference( pParser.mDataLibrary, e.mTimeAccessor->mSource);
e.mValueAccessor = &pParser.ResolveLibraryReference( pParser.mAccessorLibrary, e.mChannel->mSourceValues);
e.mValueData = &pParser.ResolveLibraryReference( pParser.mDataLibrary, e.mValueAccessor->mSource);
// time count and value count must match
if( e.mTimeAccessor->mCount != e.mValueAccessor->mCount)
throw DeadlyImportError( boost::str( boost::format( "Time count / value count mismatch in animation channel \"%s\".") % e.mChannel->mTarget));
// find bounding times
startTime = std::min( startTime, ReadFloat( *e.mTimeAccessor, *e.mTimeData, 0, 0));
endTime = std::max( endTime, ReadFloat( *e.mTimeAccessor, *e.mTimeData, e.mTimeAccessor->mCount-1, 0));
}
// create a local transformation chain of the node's transforms
std::vector<Collada::Transform> transforms = srcNode->mTransforms;
// now for every unique point in time, find or interpolate the key values for that time
// and apply them to the transform chain. Then the node's present transformation can be calculated.
float time = startTime;
std::vector<aiMatrix4x4> resultTrafos;
while( 1)
{
for( std::vector<Collada::ChannelEntry>::iterator it = entries.begin(); it != entries.end(); ++it)
{
Collada::ChannelEntry& e = *it;
// find the keyframe behind the current point in time