You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
 
 
 
 
 
 

1204 lines
37 KiB

  1. /*
  2. Open Asset Import Library (assimp)
  3. ----------------------------------------------------------------------
  4. Copyright (c) 2006-2012, assimp team
  5. All rights reserved.
  6. Redistribution and use of this software in source and binary forms,
  7. with or without modification, are permitted provided that the
  8. following conditions are met:
  9. * Redistributions of source code must retain the above
  10. copyright notice, this list of conditions and the
  11. following disclaimer.
  12. * Redistributions in binary form must reproduce the above
  13. copyright notice, this list of conditions and the
  14. following disclaimer in the documentation and/or other
  15. materials provided with the distribution.
  16. * Neither the name of the assimp team, nor the names of its
  17. contributors may be used to endorse or promote products
  18. derived from this software without specific prior
  19. written permission of the assimp team.
  20. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
  21. "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
  22. LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
  23. A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
  24. OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
  25. SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
  26. LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
  27. DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
  28. THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
  29. (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
  30. OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
  31. ----------------------------------------------------------------------
  32. */
  33. // ----------------------------------------------------------------------------
  34. /** @file Implements Assimp::SceneCombiner. This is a smart utility
  35. * class that combines multiple scenes, meshes, ... into one. Currently
  36. * these utilities are used by the IRR and LWS loaders and the
  37. * OptimizeGraph step.
  38. */
  39. // ----------------------------------------------------------------------------
  40. #include "AssimpPCH.h"
  41. #include "SceneCombiner.h"
  42. #include "fast_atof.h"
  43. #include "Hash.h"
  44. #include "time.h"
  45. namespace Assimp {
  46. // ------------------------------------------------------------------------------------------------
  47. // Add a prefix to a string
  48. inline void PrefixString(aiString& string,const char* prefix, unsigned int len)
  49. {
  50. // If the string is already prefixed, we won't prefix it a second time
  51. if (string.length >= 1 && string.data[0] == '$')
  52. return;
  53. if (len+string.length>=MAXLEN-1) {
  54. DefaultLogger::get()->debug("Can't add an unique prefix because the string is too long");
  55. ai_assert(false);
  56. return;
  57. }
  58. // Add the prefix
  59. ::memmove(string.data+len,string.data,string.length+1);
  60. ::memcpy (string.data, prefix, len);
  61. // And update the string's length
  62. string.length += len;
  63. }
  64. // ------------------------------------------------------------------------------------------------
  65. // Add node identifiers to a hashing set
  66. void SceneCombiner::AddNodeHashes(aiNode* node, std::set<unsigned int>& hashes)
  67. {
  68. // Add node name to hashing set if it is non-empty - empty nodes are allowed
  69. // and they can't have any anims assigned so its absolutely safe to duplicate them.
  70. if (node->mName.length) {
  71. hashes.insert( SuperFastHash(node->mName.data,node->mName.length) );
  72. }
  73. // Process all children recursively
  74. for (unsigned int i = 0; i < node->mNumChildren;++i)
  75. AddNodeHashes(node->mChildren[i],hashes);
  76. }
  77. // ------------------------------------------------------------------------------------------------
  78. // Add a name prefix to all nodes in a hierarchy
  79. void SceneCombiner::AddNodePrefixes(aiNode* node, const char* prefix, unsigned int len)
  80. {
  81. ai_assert(NULL != prefix);
  82. PrefixString(node->mName,prefix,len);
  83. // Process all children recursively
  84. for (unsigned int i = 0; i < node->mNumChildren;++i)
  85. AddNodePrefixes(node->mChildren[i],prefix,len);
  86. }
  87. // ------------------------------------------------------------------------------------------------
  88. // Search for matching names
  89. bool SceneCombiner::FindNameMatch(const aiString& name, std::vector<SceneHelper>& input, unsigned int cur)
  90. {
  91. const unsigned int hash = SuperFastHash(name.data, name.length);
  92. // Check whether we find a positive match in one of the given sets
  93. for (unsigned int i = 0; i < input.size(); ++i) {
  94. if (cur != i && input[i].hashes.find(hash) != input[i].hashes.end()) {
  95. return true;
  96. }
  97. }
  98. return false;
  99. }
  100. // ------------------------------------------------------------------------------------------------
  101. // Add a name prefix to all nodes in a hierarchy if a hash match is found
  102. void SceneCombiner::AddNodePrefixesChecked(aiNode* node, const char* prefix, unsigned int len,
  103. std::vector<SceneHelper>& input, unsigned int cur)
  104. {
  105. ai_assert(NULL != prefix);
  106. const unsigned int hash = SuperFastHash(node->mName.data,node->mName.length);
  107. // Check whether we find a positive match in one of the given sets
  108. for (unsigned int i = 0; i < input.size(); ++i) {
  109. if (cur != i && input[i].hashes.find(hash) != input[i].hashes.end()) {
  110. PrefixString(node->mName,prefix,len);
  111. break;
  112. }
  113. }
  114. // Process all children recursively
  115. for (unsigned int i = 0; i < node->mNumChildren;++i)
  116. AddNodePrefixesChecked(node->mChildren[i],prefix,len,input,cur);
  117. }
  118. // ------------------------------------------------------------------------------------------------
  119. // Add an offset to all mesh indices in a node graph
  120. void SceneCombiner::OffsetNodeMeshIndices (aiNode* node, unsigned int offset)
  121. {
  122. for (unsigned int i = 0; i < node->mNumMeshes;++i)
  123. node->mMeshes[i] += offset;
  124. for (unsigned int i = 0; i < node->mNumChildren;++i)
  125. OffsetNodeMeshIndices(node->mChildren[i],offset);
  126. }
  127. // ------------------------------------------------------------------------------------------------
  128. // Merges two scenes. Currently only used by the LWS loader.
  129. void SceneCombiner::MergeScenes(aiScene** _dest,std::vector<aiScene*>& src,
  130. unsigned int flags)
  131. {
  132. ai_assert(NULL != _dest);
  133. // if _dest points to NULL allocate a new scene. Otherwise clear the old and reuse it
  134. if (src.empty())
  135. {
  136. if (*_dest)
  137. {
  138. (*_dest)->~aiScene();
  139. SceneCombiner::CopySceneFlat(_dest,src[0]);
  140. }
  141. else *_dest = src[0];
  142. return;
  143. }
  144. if (*_dest)(*_dest)->~aiScene();
  145. else *_dest = new aiScene();
  146. // Create a dummy scene to serve as master for the others
  147. aiScene* master = new aiScene();
  148. master->mRootNode = new aiNode();
  149. master->mRootNode->mName.Set("<MergeRoot>");
  150. std::vector<AttachmentInfo> srcList (src.size());
  151. for (unsigned int i = 0; i < srcList.size();++i) {
  152. srcList[i] = AttachmentInfo(src[i],master->mRootNode);
  153. }
  154. // 'master' will be deleted afterwards
  155. MergeScenes (_dest, master, srcList, flags);
  156. }
  157. // ------------------------------------------------------------------------------------------------
  158. void SceneCombiner::AttachToGraph (aiNode* attach, std::vector<NodeAttachmentInfo>& srcList)
  159. {
  160. unsigned int cnt;
  161. for (cnt = 0; cnt < attach->mNumChildren;++cnt)
  162. AttachToGraph(attach->mChildren[cnt],srcList);
  163. cnt = 0;
  164. for (std::vector<NodeAttachmentInfo>::iterator it = srcList.begin();
  165. it != srcList.end(); ++it)
  166. {
  167. if ((*it).attachToNode == attach && !(*it).resolved)
  168. ++cnt;
  169. }
  170. if (cnt) {
  171. aiNode** n = new aiNode*[cnt+attach->mNumChildren];
  172. if (attach->mNumChildren) {
  173. ::memcpy(n,attach->mChildren,sizeof(void*)*attach->mNumChildren);
  174. delete[] attach->mChildren;
  175. }
  176. attach->mChildren = n;
  177. n += attach->mNumChildren;
  178. attach->mNumChildren += cnt;
  179. for (unsigned int i = 0; i < srcList.size();++i) {
  180. NodeAttachmentInfo& att = srcList[i];
  181. if (att.attachToNode == attach && !att.resolved) {
  182. *n = att.node;
  183. (**n).mParent = attach;
  184. ++n;
  185. // mark this attachment as resolved
  186. att.resolved = true;
  187. }
  188. }
  189. }
  190. }
  191. // ------------------------------------------------------------------------------------------------
  192. void SceneCombiner::AttachToGraph ( aiScene* master,
  193. std::vector<NodeAttachmentInfo>& src)
  194. {
  195. ai_assert(NULL != master);
  196. AttachToGraph(master->mRootNode,src);
  197. }
  198. // ------------------------------------------------------------------------------------------------
  199. void SceneCombiner::MergeScenes(aiScene** _dest, aiScene* master,
  200. std::vector<AttachmentInfo>& srcList,
  201. unsigned int flags)
  202. {
  203. ai_assert(NULL != _dest);
  204. // if _dest points to NULL allocate a new scene. Otherwise clear the old and reuse it
  205. if (srcList.empty()) {
  206. if (*_dest) {
  207. SceneCombiner::CopySceneFlat(_dest,master);
  208. }
  209. else *_dest = master;
  210. return;
  211. }
  212. if (*_dest) {
  213. (*_dest)->~aiScene();
  214. new (*_dest) aiScene();
  215. }
  216. else *_dest = new aiScene();
  217. aiScene* dest = *_dest;
  218. std::vector<SceneHelper> src (srcList.size()+1);
  219. src[0].scene = master;
  220. for (unsigned int i = 0; i < srcList.size();++i) {
  221. src[i+1] = SceneHelper( srcList[i].scene );
  222. }
  223. // this helper array specifies which scenes are duplicates of others
  224. std::vector<unsigned int> duplicates(src.size(),UINT_MAX);
  225. // this helper array is used as lookup table several times
  226. std::vector<unsigned int> offset(src.size());
  227. // Find duplicate scenes
  228. for (unsigned int i = 0; i < src.size();++i) {
  229. if (duplicates[i] != i && duplicates[i] != UINT_MAX) {
  230. continue;
  231. }
  232. duplicates[i] = i;
  233. for ( unsigned int a = i+1; a < src.size(); ++a) {
  234. if (src[i].scene == src[a].scene) {
  235. duplicates[a] = i;
  236. }
  237. }
  238. }
  239. // Generate unique names for all named stuff?
  240. if (flags & AI_INT_MERGE_SCENE_GEN_UNIQUE_NAMES)
  241. {
  242. #if 0
  243. // Construct a proper random number generator
  244. boost::mt19937 rng( );
  245. boost::uniform_int<> dist(1u,1 << 24u);
  246. boost::variate_generator<boost::mt19937&, boost::uniform_int<> > rndGen(rng, dist);
  247. #endif
  248. for (unsigned int i = 1; i < src.size();++i)
  249. {
  250. //if (i != duplicates[i])
  251. //{
  252. // // duplicate scenes share the same UID
  253. // ::strcpy( src[i].id, src[duplicates[i]].id );
  254. // src[i].idlen = src[duplicates[i]].idlen;
  255. // continue;
  256. //}
  257. src[i].idlen = ::sprintf(src[i].id,"$%.6X$_",i);
  258. if (flags & AI_INT_MERGE_SCENE_GEN_UNIQUE_NAMES_IF_NECESSARY) {
  259. // Compute hashes for all identifiers in this scene and store them
  260. // in a sorted table (for convenience I'm using std::set). We hash
  261. // just the node and animation channel names, all identifiers except
  262. // the material names should be caught by doing this.
  263. AddNodeHashes(src[i]->mRootNode,src[i].hashes);
  264. for (unsigned int a = 0; a < src[i]->mNumAnimations;++a) {
  265. aiAnimation* anim = src[i]->mAnimations[a];
  266. src[i].hashes.insert(SuperFastHash(anim->mName.data,anim->mName.length));
  267. }
  268. }
  269. }
  270. }
  271. unsigned int cnt;
  272. // First find out how large the respective output arrays must be
  273. for ( unsigned int n = 0; n < src.size();++n )
  274. {
  275. SceneHelper* cur = &src[n];
  276. if (n == duplicates[n] || flags & AI_INT_MERGE_SCENE_DUPLICATES_DEEP_CPY) {
  277. dest->mNumTextures += (*cur)->mNumTextures;
  278. dest->mNumMaterials += (*cur)->mNumMaterials;
  279. dest->mNumMeshes += (*cur)->mNumMeshes;
  280. }
  281. dest->mNumLights += (*cur)->mNumLights;
  282. dest->mNumCameras += (*cur)->mNumCameras;
  283. dest->mNumAnimations += (*cur)->mNumAnimations;
  284. // Combine the flags of all scenes
  285. // We need to process them flag-by-flag here to get correct results
  286. // dest->mFlags ; //|= (*cur)->mFlags;
  287. if ((*cur)->mFlags & AI_SCENE_FLAGS_NON_VERBOSE_FORMAT) {
  288. dest->mFlags |= AI_SCENE_FLAGS_NON_VERBOSE_FORMAT;
  289. }
  290. }
  291. // generate the output texture list + an offset table for all texture indices
  292. if (dest->mNumTextures)
  293. {
  294. aiTexture** pip = dest->mTextures = new aiTexture*[dest->mNumMaterials];
  295. cnt = 0;
  296. for ( unsigned int n = 0; n < src.size();++n )
  297. {
  298. SceneHelper* cur = &src[n];
  299. for (unsigned int i = 0; i < (*cur)->mNumTextures;++i)
  300. {
  301. if (n != duplicates[n])
  302. {
  303. if ( flags & AI_INT_MERGE_SCENE_DUPLICATES_DEEP_CPY)
  304. Copy(pip,(*cur)->mTextures[i]);
  305. else continue;
  306. }
  307. else *pip = (*cur)->mTextures[i];
  308. ++pip;
  309. }
  310. offset[n] = cnt;
  311. cnt = (unsigned int)(pip - dest->mTextures);
  312. }
  313. }
  314. // generate the output material list + an offset table for all material indices
  315. if (dest->mNumMaterials)
  316. {
  317. aiMaterial** pip = dest->mMaterials = new aiMaterial*[dest->mNumMaterials];
  318. cnt = 0;
  319. for ( unsigned int n = 0; n < src.size();++n ) {
  320. SceneHelper* cur = &src[n];
  321. for (unsigned int i = 0; i < (*cur)->mNumMaterials;++i)
  322. {
  323. if (n != duplicates[n])
  324. {
  325. if ( flags & AI_INT_MERGE_SCENE_DUPLICATES_DEEP_CPY)
  326. Copy(pip,(*cur)->mMaterials[i]);
  327. else continue;
  328. }
  329. else *pip = (*cur)->mMaterials[i];
  330. if ((*cur)->mNumTextures != dest->mNumTextures) {
  331. // We need to update all texture indices of the mesh. So we need to search for
  332. // a material property called '$tex.file'
  333. for (unsigned int a = 0; a < (*pip)->mNumProperties;++a)
  334. {
  335. aiMaterialProperty* prop = (*pip)->mProperties[a];
  336. if (!strncmp(prop->mKey.data,"$tex.file",9))
  337. {
  338. // Check whether this texture is an embedded texture.
  339. // In this case the property looks like this: *<n>,
  340. // where n is the index of the texture.
  341. aiString& s = *((aiString*)prop->mData);
  342. if ('*' == s.data[0]) {
  343. // Offset the index and write it back ..
  344. const unsigned int idx = strtoul10(&s.data[1]) + offset[n];
  345. ASSIMP_itoa10(&s.data[1],sizeof(s.data)-1,idx);
  346. }
  347. }
  348. // Need to generate new, unique material names?
  349. else if (!::strcmp( prop->mKey.data,"$mat.name" ) && flags & AI_INT_MERGE_SCENE_GEN_UNIQUE_MATNAMES)
  350. {
  351. aiString* pcSrc = (aiString*) prop->mData;
  352. PrefixString(*pcSrc, (*cur).id, (*cur).idlen);
  353. }
  354. }
  355. }
  356. ++pip;
  357. }
  358. offset[n] = cnt;
  359. cnt = (unsigned int)(pip - dest->mMaterials);
  360. }
  361. }
  362. // generate the output mesh list + again an offset table for all mesh indices
  363. if (dest->mNumMeshes)
  364. {
  365. aiMesh** pip = dest->mMeshes = new aiMesh*[dest->mNumMeshes];
  366. cnt = 0;
  367. for ( unsigned int n = 0; n < src.size();++n )
  368. {
  369. SceneHelper* cur = &src[n];
  370. for (unsigned int i = 0; i < (*cur)->mNumMeshes;++i)
  371. {
  372. if (n != duplicates[n]) {
  373. if ( flags & AI_INT_MERGE_SCENE_DUPLICATES_DEEP_CPY)
  374. Copy(pip, (*cur)->mMeshes[i]);
  375. else continue;
  376. }
  377. else *pip = (*cur)->mMeshes[i];
  378. // update the material index of the mesh
  379. (*pip)->mMaterialIndex += offset[n];
  380. ++pip;
  381. }
  382. // reuse the offset array - store now the mesh offset in it
  383. offset[n] = cnt;
  384. cnt = (unsigned int)(pip - dest->mMeshes);
  385. }
  386. }
  387. std::vector <NodeAttachmentInfo> nodes;
  388. nodes.reserve(srcList.size());
  389. // ----------------------------------------------------------------------------
  390. // Now generate the output node graph. We need to make those
  391. // names in the graph that are referenced by anims or lights
  392. // or cameras unique. So we add a prefix to them ... $<rand>_
  393. // We could also use a counter, but using a random value allows us to
  394. // use just one prefix if we are joining multiple scene hierarchies recursively.
  395. // Chances are quite good we don't collide, so we try that ...
  396. // ----------------------------------------------------------------------------
  397. // Allocate space for light sources, cameras and animations
  398. aiLight** ppLights = dest->mLights = (dest->mNumLights
  399. ? new aiLight*[dest->mNumLights] : NULL);
  400. aiCamera** ppCameras = dest->mCameras = (dest->mNumCameras
  401. ? new aiCamera*[dest->mNumCameras] : NULL);
  402. aiAnimation** ppAnims = dest->mAnimations = (dest->mNumAnimations
  403. ? new aiAnimation*[dest->mNumAnimations] : NULL);
  404. for ( int n = src.size()-1; n >= 0 ;--n ) /* !!! important !!! */
  405. {
  406. SceneHelper* cur = &src[n];
  407. aiNode* node;
  408. // To offset or not to offset, this is the question
  409. if (n != (int)duplicates[n])
  410. {
  411. // Get full scenegraph copy
  412. Copy( &node, (*cur)->mRootNode );
  413. OffsetNodeMeshIndices(node,offset[duplicates[n]]);
  414. if (flags & AI_INT_MERGE_SCENE_DUPLICATES_DEEP_CPY) {
  415. // (note:) they are already 'offseted' by offset[duplicates[n]]
  416. OffsetNodeMeshIndices(node,offset[n] - offset[duplicates[n]]);
  417. }
  418. }
  419. else // if (n == duplicates[n])
  420. {
  421. node = (*cur)->mRootNode;
  422. OffsetNodeMeshIndices(node,offset[n]);
  423. }
  424. if (n) // src[0] is the master node
  425. nodes.push_back(NodeAttachmentInfo( node,srcList[n-1].attachToNode,n ));
  426. // add name prefixes?
  427. if (flags & AI_INT_MERGE_SCENE_GEN_UNIQUE_NAMES) {
  428. // or the whole scenegraph
  429. if (flags & AI_INT_MERGE_SCENE_GEN_UNIQUE_NAMES_IF_NECESSARY) {
  430. AddNodePrefixesChecked(node,(*cur).id,(*cur).idlen,src,n);
  431. }
  432. else AddNodePrefixes(node,(*cur).id,(*cur).idlen);
  433. // meshes
  434. for (unsigned int i = 0; i < (*cur)->mNumMeshes;++i) {
  435. aiMesh* mesh = (*cur)->mMeshes[i];
  436. // rename all bones
  437. for (unsigned int a = 0; a < mesh->mNumBones;++a) {
  438. if (flags & AI_INT_MERGE_SCENE_GEN_UNIQUE_NAMES_IF_NECESSARY) {
  439. if (!FindNameMatch(mesh->mBones[a]->mName,src,n))
  440. continue;
  441. }
  442. PrefixString(mesh->mBones[a]->mName,(*cur).id,(*cur).idlen);
  443. }
  444. }
  445. }
  446. // --------------------------------------------------------------------
  447. // Copy light sources
  448. for (unsigned int i = 0; i < (*cur)->mNumLights;++i,++ppLights)
  449. {
  450. if (n != (int)duplicates[n]) // duplicate scene?
  451. {
  452. Copy(ppLights, (*cur)->mLights[i]);
  453. }
  454. else *ppLights = (*cur)->mLights[i];
  455. // Add name prefixes?
  456. if (flags & AI_INT_MERGE_SCENE_GEN_UNIQUE_NAMES) {
  457. if (flags & AI_INT_MERGE_SCENE_GEN_UNIQUE_NAMES_IF_NECESSARY) {
  458. if (!FindNameMatch((*ppLights)->mName,src,n))
  459. continue;
  460. }
  461. PrefixString((*ppLights)->mName,(*cur).id,(*cur).idlen);
  462. }
  463. }
  464. // --------------------------------------------------------------------
  465. // Copy cameras
  466. for (unsigned int i = 0; i < (*cur)->mNumCameras;++i,++ppCameras) {
  467. if (n != (int)duplicates[n]) // duplicate scene?
  468. {
  469. Copy(ppCameras, (*cur)->mCameras[i]);
  470. }
  471. else *ppCameras = (*cur)->mCameras[i];
  472. // Add name prefixes?
  473. if (flags & AI_INT_MERGE_SCENE_GEN_UNIQUE_NAMES) {
  474. if (flags & AI_INT_MERGE_SCENE_GEN_UNIQUE_NAMES_IF_NECESSARY) {
  475. if (!FindNameMatch((*ppCameras)->mName,src,n))
  476. continue;
  477. }
  478. PrefixString((*ppCameras)->mName,(*cur).id,(*cur).idlen);
  479. }
  480. }
  481. // --------------------------------------------------------------------
  482. // Copy animations
  483. for (unsigned int i = 0; i < (*cur)->mNumAnimations;++i,++ppAnims) {
  484. if (n != (int)duplicates[n]) // duplicate scene?
  485. {
  486. Copy(ppAnims, (*cur)->mAnimations[i]);
  487. }
  488. else *ppAnims = (*cur)->mAnimations[i];
  489. // Add name prefixes?
  490. if (flags & AI_INT_MERGE_SCENE_GEN_UNIQUE_NAMES) {
  491. if (flags & AI_INT_MERGE_SCENE_GEN_UNIQUE_NAMES_IF_NECESSARY) {
  492. if (!FindNameMatch((*ppAnims)->mName,src,n))
  493. continue;
  494. }
  495. PrefixString((*ppAnims)->mName,(*cur).id,(*cur).idlen);
  496. // don't forget to update all node animation channels
  497. for (unsigned int a = 0; a < (*ppAnims)->mNumChannels;++a) {
  498. if (flags & AI_INT_MERGE_SCENE_GEN_UNIQUE_NAMES_IF_NECESSARY) {
  499. if (!FindNameMatch((*ppAnims)->mChannels[a]->mNodeName,src,n))
  500. continue;
  501. }
  502. PrefixString((*ppAnims)->mChannels[a]->mNodeName,(*cur).id,(*cur).idlen);
  503. }
  504. }
  505. }
  506. }
  507. // Now build the output graph
  508. AttachToGraph ( master, nodes);
  509. dest->mRootNode = master->mRootNode;
  510. // Check whether we succeeded at building the output graph
  511. for (std::vector <NodeAttachmentInfo> ::iterator it = nodes.begin();
  512. it != nodes.end(); ++it)
  513. {
  514. if (!(*it).resolved) {
  515. if (flags & AI_INT_MERGE_SCENE_RESOLVE_CROSS_ATTACHMENTS) {
  516. // search for this attachment point in all other imported scenes, too.
  517. for ( unsigned int n = 0; n < src.size();++n ) {
  518. if (n != (*it).src_idx) {
  519. AttachToGraph(src[n].scene,nodes);
  520. if ((*it).resolved)
  521. break;
  522. }
  523. }
  524. }
  525. if (!(*it).resolved) {
  526. DefaultLogger::get()->error(std::string("SceneCombiner: Failed to resolve attachment ")
  527. + (*it).node->mName.data + " " + (*it).attachToNode->mName.data);
  528. }
  529. }
  530. }
  531. // now delete all input scenes. Make sure duplicate scenes aren't
  532. // deleted more than one time
  533. for ( unsigned int n = 0; n < src.size();++n ) {
  534. if (n != duplicates[n]) // duplicate scene?
  535. continue;
  536. aiScene* deleteMe = src[n].scene;
  537. // We need to delete the arrays before the destructor is called -
  538. // we are reusing the array members
  539. delete[] deleteMe->mMeshes; deleteMe->mMeshes = NULL;
  540. delete[] deleteMe->mCameras; deleteMe->mCameras = NULL;
  541. delete[] deleteMe->mLights; deleteMe->mLights = NULL;
  542. delete[] deleteMe->mMaterials; deleteMe->mMaterials = NULL;
  543. delete[] deleteMe->mAnimations; deleteMe->mAnimations = NULL;
  544. deleteMe->mRootNode = NULL;
  545. // Now we can safely delete the scene
  546. delete deleteMe;
  547. }
  548. // Check flags
  549. if (!dest->mNumMeshes || !dest->mNumMaterials) {
  550. dest->mFlags |= AI_SCENE_FLAGS_INCOMPLETE;
  551. }
  552. // We're finished
  553. }
  554. // ------------------------------------------------------------------------------------------------
  555. // Build a list of unique bones
  556. void SceneCombiner::BuildUniqueBoneList(std::list<BoneWithHash>& asBones,
  557. std::vector<aiMesh*>::const_iterator it,
  558. std::vector<aiMesh*>::const_iterator end)
  559. {
  560. unsigned int iOffset = 0;
  561. for (; it != end;++it) {
  562. for (unsigned int l = 0; l < (*it)->mNumBones;++l) {
  563. aiBone* p = (*it)->mBones[l];
  564. uint32_t itml = SuperFastHash(p->mName.data,(unsigned int)p->mName.length);
  565. std::list<BoneWithHash>::iterator it2 = asBones.begin();
  566. std::list<BoneWithHash>::iterator end2 = asBones.end();
  567. for (;it2 != end2;++it2) {
  568. if ((*it2).first == itml) {
  569. (*it2).pSrcBones.push_back(BoneSrcIndex(p,iOffset));
  570. break;
  571. }
  572. }
  573. if (end2 == it2) {
  574. // need to begin a new bone entry
  575. asBones.push_back(BoneWithHash());
  576. BoneWithHash& btz = asBones.back();
  577. // setup members
  578. btz.first = itml;
  579. btz.second = &p->mName;
  580. btz.pSrcBones.push_back(BoneSrcIndex(p,iOffset));
  581. }
  582. }
  583. iOffset += (*it)->mNumVertices;
  584. }
  585. }
  586. // ------------------------------------------------------------------------------------------------
  587. // Merge a list of bones
  588. void SceneCombiner::MergeBones(aiMesh* out,std::vector<aiMesh*>::const_iterator it,
  589. std::vector<aiMesh*>::const_iterator end)
  590. {
  591. ai_assert(NULL != out && !out->mNumBones);
  592. // find we need to build an unique list of all bones.
  593. // we work with hashes to make the comparisons MUCH faster,
  594. // at least if we have many bones.
  595. std::list<BoneWithHash> asBones;
  596. BuildUniqueBoneList(asBones, it,end);
  597. // now create the output bones
  598. out->mNumBones = 0;
  599. out->mBones = new aiBone*[asBones.size()];
  600. for (std::list<BoneWithHash>::const_iterator it = asBones.begin(),end = asBones.end(); it != end;++it) {
  601. // Allocate a bone and setup it's name
  602. aiBone* pc = out->mBones[out->mNumBones++] = new aiBone();
  603. pc->mName = aiString( *((*it).second ));
  604. std::vector< BoneSrcIndex >::const_iterator wend = (*it).pSrcBones.end();
  605. // Loop through all bones to be joined for this bone
  606. for (std::vector< BoneSrcIndex >::const_iterator wmit = (*it).pSrcBones.begin(); wmit != wend; ++wmit) {
  607. pc->mNumWeights += (*wmit).first->mNumWeights;
  608. // NOTE: different offset matrices for bones with equal names
  609. // are - at the moment - not handled correctly.
  610. if (wmit != (*it).pSrcBones.begin() && pc->mOffsetMatrix != (*wmit).first->mOffsetMatrix) {
  611. DefaultLogger::get()->warn("Bones with equal names but different offset matrices can't be joined at the moment");
  612. continue;
  613. }
  614. pc->mOffsetMatrix = (*wmit).first->mOffsetMatrix;
  615. }
  616. // Allocate the vertex weight array
  617. aiVertexWeight* avw = pc->mWeights = new aiVertexWeight[pc->mNumWeights];
  618. // And copy the final weights - adjust the vertex IDs by the
  619. // face index offset of the coresponding mesh.
  620. for (std::vector< BoneSrcIndex >::const_iterator wmit = (*it).pSrcBones.begin(); wmit != wend; ++wmit) {
  621. aiBone* pip = (*wmit).first;
  622. for (unsigned int mp = 0; mp < pip->mNumWeights;++mp,++avw) {
  623. const aiVertexWeight& vfi = pip->mWeights[mp];
  624. avw->mWeight = vfi.mWeight;
  625. avw->mVertexId = vfi.mVertexId + (*wmit).second;
  626. }
  627. }
  628. }
  629. }
  630. // ------------------------------------------------------------------------------------------------
  631. // Merge a list of meshes
  632. void SceneCombiner::MergeMeshes(aiMesh** _out,unsigned int /*flags*/,
  633. std::vector<aiMesh*>::const_iterator begin,
  634. std::vector<aiMesh*>::const_iterator end)
  635. {
  636. ai_assert(NULL != _out);
  637. if (begin == end) {
  638. *_out = NULL; // no meshes ...
  639. return;
  640. }
  641. // Allocate the output mesh
  642. aiMesh* out = *_out = new aiMesh();
  643. out->mMaterialIndex = (*begin)->mMaterialIndex;
  644. // Find out how much output storage we'll need
  645. for (std::vector<aiMesh*>::const_iterator it = begin; it != end;++it) {
  646. out->mNumVertices += (*it)->mNumVertices;
  647. out->mNumFaces += (*it)->mNumFaces;
  648. out->mNumBones += (*it)->mNumBones;
  649. // combine primitive type flags
  650. out->mPrimitiveTypes |= (*it)->mPrimitiveTypes;
  651. }
  652. if (out->mNumVertices) {
  653. aiVector3D* pv2;
  654. // copy vertex positions
  655. if ((**begin).HasPositions()) {
  656. pv2 = out->mVertices = new aiVector3D[out->mNumVertices];
  657. for (std::vector<aiMesh*>::const_iterator it = begin; it != end;++it) {
  658. if ((*it)->mVertices) {
  659. ::memcpy(pv2,(*it)->mVertices,(*it)->mNumVertices*sizeof(aiVector3D));
  660. }
  661. else DefaultLogger::get()->warn("JoinMeshes: Positions expected but input mesh contains no positions");
  662. pv2 += (*it)->mNumVertices;
  663. }
  664. }
  665. // copy normals
  666. if ((**begin).HasNormals()) {
  667. pv2 = out->mNormals = new aiVector3D[out->mNumVertices];
  668. for (std::vector<aiMesh*>::const_iterator it = begin; it != end;++it) {
  669. if ((*it)->mNormals) {
  670. ::memcpy(pv2,(*it)->mNormals,(*it)->mNumVertices*sizeof(aiVector3D));
  671. }
  672. else DefaultLogger::get()->warn("JoinMeshes: Normals expected but input mesh contains no normals");
  673. pv2 += (*it)->mNumVertices;
  674. }
  675. }
  676. // copy tangents and bitangents
  677. if ((**begin).HasTangentsAndBitangents()) {
  678. pv2 = out->mTangents = new aiVector3D[out->mNumVertices];
  679. aiVector3D* pv2b = out->mBitangents = new aiVector3D[out->mNumVertices];
  680. for (std::vector<aiMesh*>::const_iterator it = begin; it != end;++it) {
  681. if ((*it)->mTangents) {
  682. ::memcpy(pv2, (*it)->mTangents, (*it)->mNumVertices*sizeof(aiVector3D));
  683. ::memcpy(pv2b,(*it)->mBitangents,(*it)->mNumVertices*sizeof(aiVector3D));
  684. }
  685. else DefaultLogger::get()->warn("JoinMeshes: Tangents expected but input mesh contains no tangents");
  686. pv2 += (*it)->mNumVertices;
  687. pv2b += (*it)->mNumVertices;
  688. }
  689. }
  690. // copy texture coordinates
  691. unsigned int n = 0;
  692. while ((**begin).HasTextureCoords(n)) {
  693. out->mNumUVComponents[n] = (*begin)->mNumUVComponents[n];
  694. pv2 = out->mTextureCoords[n] = new aiVector3D[out->mNumVertices];
  695. for (std::vector<aiMesh*>::const_iterator it = begin; it != end;++it) {
  696. if ((*it)->mTextureCoords[n]) {
  697. ::memcpy(pv2,(*it)->mTextureCoords[n],(*it)->mNumVertices*sizeof(aiVector3D));
  698. }
  699. else DefaultLogger::get()->warn("JoinMeshes: UVs expected but input mesh contains no UVs");
  700. pv2 += (*it)->mNumVertices;
  701. }
  702. ++n;
  703. }
  704. // copy vertex colors
  705. n = 0;
  706. while ((**begin).HasVertexColors(n)) {
  707. aiColor4D* pv2 = out->mColors[n] = new aiColor4D[out->mNumVertices];
  708. for (std::vector<aiMesh*>::const_iterator it = begin; it != end;++it) {
  709. if ((*it)->mColors[n]) {
  710. ::memcpy(pv2,(*it)->mColors[n],(*it)->mNumVertices*sizeof(aiColor4D));
  711. }
  712. else DefaultLogger::get()->warn("JoinMeshes: VCs expected but input mesh contains no VCs");
  713. pv2 += (*it)->mNumVertices;
  714. }
  715. ++n;
  716. }
  717. }
  718. if (out->mNumFaces) // just for safety
  719. {
  720. // copy faces
  721. out->mFaces = new aiFace[out->mNumFaces];
  722. aiFace* pf2 = out->mFaces;
  723. unsigned int ofs = 0;
  724. for (std::vector<aiMesh*>::const_iterator it = begin; it != end;++it) {
  725. for (unsigned int m = 0; m < (*it)->mNumFaces;++m,++pf2) {
  726. aiFace& face = (*it)->mFaces[m];
  727. pf2->mNumIndices = face.mNumIndices;
  728. pf2->mIndices = face.mIndices;
  729. if (ofs) {
  730. // add the offset to the vertex
  731. for (unsigned int q = 0; q < face.mNumIndices; ++q)
  732. face.mIndices[q] += ofs;
  733. }
  734. face.mIndices = NULL;
  735. }
  736. ofs += (*it)->mNumVertices;
  737. }
  738. }
  739. // bones - as this is quite lengthy, I moved the code to a separate function
  740. if (out->mNumBones)
  741. MergeBones(out,begin,end);
  742. // delete all source meshes
  743. for (std::vector<aiMesh*>::const_iterator it = begin; it != end;++it)
  744. delete *it;
  745. }
  746. // ------------------------------------------------------------------------------------------------
  747. void SceneCombiner::MergeMaterials(aiMaterial** dest,
  748. std::vector<aiMaterial*>::const_iterator begin,
  749. std::vector<aiMaterial*>::const_iterator end)
  750. {
  751. ai_assert(NULL != dest);
  752. if (begin == end) {
  753. *dest = NULL; // no materials ...
  754. return;
  755. }
  756. // Allocate the output material
  757. aiMaterial* out = *dest = new aiMaterial();
  758. // Get the maximal number of properties
  759. unsigned int size = 0;
  760. for (std::vector<aiMaterial*>::const_iterator it = begin; it != end; ++it) {
  761. size += (*it)->mNumProperties;
  762. }
  763. out->Clear();
  764. delete[] out->mProperties;
  765. out->mNumAllocated = size;
  766. out->mNumProperties = 0;
  767. out->mProperties = new aiMaterialProperty*[out->mNumAllocated];
  768. for (std::vector<aiMaterial*>::const_iterator it = begin; it != end; ++it) {
  769. for(unsigned int i = 0; i < (*it)->mNumProperties; ++i) {
  770. aiMaterialProperty* sprop = (*it)->mProperties[i];
  771. // Test if we already have a matching property
  772. const aiMaterialProperty* prop_exist;
  773. if(aiGetMaterialProperty(out, sprop->mKey.C_Str(), sprop->mType, sprop->mIndex, &prop_exist) != AI_SUCCESS) {
  774. // If not, we add it to the new material
  775. aiMaterialProperty* prop = out->mProperties[out->mNumProperties] = new aiMaterialProperty();
  776. prop->mDataLength = sprop->mDataLength;
  777. prop->mData = new char[prop->mDataLength];
  778. ::memcpy(prop->mData, sprop->mData, prop->mDataLength);
  779. prop->mIndex = sprop->mIndex;
  780. prop->mSemantic = sprop->mSemantic;
  781. prop->mKey = sprop->mKey;
  782. prop->mType = sprop->mType;
  783. out->mNumProperties++;
  784. }
  785. }
  786. }
  787. }
  788. // ------------------------------------------------------------------------------------------------
  789. template <typename Type>
  790. inline void CopyPtrArray (Type**& dest, const Type* const * src, unsigned int num)
  791. {
  792. if (!num)
  793. {
  794. dest = NULL;
  795. return;
  796. }
  797. dest = new Type*[num];
  798. for (unsigned int i = 0; i < num;++i) {
  799. SceneCombiner::Copy(&dest[i],src[i]);
  800. }
  801. }
  802. // ------------------------------------------------------------------------------------------------
  803. template <typename Type>
  804. inline void GetArrayCopy (Type*& dest, unsigned int num )
  805. {
  806. if (!dest)return;
  807. Type* old = dest;
  808. dest = new Type[num];
  809. ::memcpy(dest, old, sizeof(Type) * num);
  810. }
  811. // ------------------------------------------------------------------------------------------------
  812. void SceneCombiner::CopySceneFlat(aiScene** _dest,const aiScene* src)
  813. {
  814. // reuse the old scene or allocate a new?
  815. if (*_dest) {
  816. (*_dest)->~aiScene();
  817. new (*_dest) aiScene();
  818. }
  819. else *_dest = new aiScene();
  820. ::memcpy(*_dest,src,sizeof(aiScene));
  821. }
  822. // ------------------------------------------------------------------------------------------------
  823. void SceneCombiner::CopyScene(aiScene** _dest,const aiScene* src,bool allocate)
  824. {
  825. ai_assert(NULL != _dest && NULL != src);
  826. if (allocate) {
  827. *_dest = new aiScene();
  828. }
  829. aiScene* dest = *_dest;
  830. ai_assert(dest);
  831. // copy animations
  832. dest->mNumAnimations = src->mNumAnimations;
  833. CopyPtrArray(dest->mAnimations,src->mAnimations,
  834. dest->mNumAnimations);
  835. // copy textures
  836. dest->mNumTextures = src->mNumTextures;
  837. CopyPtrArray(dest->mTextures,src->mTextures,
  838. dest->mNumTextures);
  839. // copy materials
  840. dest->mNumMaterials = src->mNumMaterials;
  841. CopyPtrArray(dest->mMaterials,src->mMaterials,
  842. dest->mNumMaterials);
  843. // copy lights
  844. dest->mNumLights = src->mNumLights;
  845. CopyPtrArray(dest->mLights,src->mLights,
  846. dest->mNumLights);
  847. // copy cameras
  848. dest->mNumCameras = src->mNumCameras;
  849. CopyPtrArray(dest->mCameras,src->mCameras,
  850. dest->mNumCameras);
  851. // copy meshes
  852. dest->mNumMeshes = src->mNumMeshes;
  853. CopyPtrArray(dest->mMeshes,src->mMeshes,
  854. dest->mNumMeshes);
  855. // now - copy the root node of the scene (deep copy, too)
  856. Copy( &dest->mRootNode, src->mRootNode);
  857. // and keep the flags ...
  858. dest->mFlags = src->mFlags;
  859. // source private data might be NULL if the scene is user-allocated (i.e. for use with the export API)
  860. ScenePriv(dest)->mPPStepsApplied = ScenePriv(src) ? ScenePriv(src)->mPPStepsApplied : 0;
  861. }
  862. // ------------------------------------------------------------------------------------------------
  863. void SceneCombiner::Copy (aiMesh** _dest, const aiMesh* src)
  864. {
  865. ai_assert(NULL != _dest && NULL != src);
  866. aiMesh* dest = *_dest = new aiMesh();
  867. // get a flat copy
  868. ::memcpy(dest,src,sizeof(aiMesh));
  869. // and reallocate all arrays
  870. GetArrayCopy( dest->mVertices, dest->mNumVertices );
  871. GetArrayCopy( dest->mNormals , dest->mNumVertices );
  872. GetArrayCopy( dest->mTangents, dest->mNumVertices );
  873. GetArrayCopy( dest->mBitangents, dest->mNumVertices );
  874. unsigned int n = 0;
  875. while (dest->HasTextureCoords(n))
  876. GetArrayCopy( dest->mTextureCoords[n++], dest->mNumVertices );
  877. n = 0;
  878. while (dest->HasVertexColors(n))
  879. GetArrayCopy( dest->mColors[n++], dest->mNumVertices );
  880. // make a deep copy of all bones
  881. CopyPtrArray(dest->mBones,dest->mBones,dest->mNumBones);
  882. // make a deep copy of all faces
  883. GetArrayCopy(dest->mFaces,dest->mNumFaces);
  884. for (unsigned int i = 0; i < dest->mNumFaces;++i)
  885. {
  886. aiFace& f = dest->mFaces[i];
  887. GetArrayCopy(f.mIndices,f.mNumIndices);
  888. }
  889. }
  890. // ------------------------------------------------------------------------------------------------
  891. void SceneCombiner::Copy (aiMaterial** _dest, const aiMaterial* src)
  892. {
  893. ai_assert(NULL != _dest && NULL != src);
  894. aiMaterial* dest = (aiMaterial*) ( *_dest = new aiMaterial() );
  895. dest->Clear();
  896. delete[] dest->mProperties;
  897. dest->mNumAllocated = src->mNumAllocated;
  898. dest->mNumProperties = src->mNumProperties;
  899. dest->mProperties = new aiMaterialProperty* [dest->mNumAllocated];
  900. for (unsigned int i = 0; i < dest->mNumProperties;++i)
  901. {
  902. aiMaterialProperty* prop = dest->mProperties[i] = new aiMaterialProperty();
  903. aiMaterialProperty* sprop = src->mProperties[i];
  904. prop->mDataLength = sprop->mDataLength;
  905. prop->mData = new char[prop->mDataLength];
  906. ::memcpy(prop->mData,sprop->mData,prop->mDataLength);
  907. prop->mIndex = sprop->mIndex;
  908. prop->mSemantic = sprop->mSemantic;
  909. prop->mKey = sprop->mKey;
  910. prop->mType = sprop->mType;
  911. }
  912. }
  913. // ------------------------------------------------------------------------------------------------
  914. void SceneCombiner::Copy (aiTexture** _dest, const aiTexture* src)
  915. {
  916. ai_assert(NULL != _dest && NULL != src);
  917. aiTexture* dest = *_dest = new aiTexture();
  918. // get a flat copy
  919. ::memcpy(dest,src,sizeof(aiTexture));
  920. // and reallocate all arrays. We must do it manually here
  921. const char* old = (const char*)dest->pcData;
  922. if (old)
  923. {
  924. unsigned int cpy;
  925. if (!dest->mHeight)cpy = dest->mWidth;
  926. else cpy = dest->mHeight * dest->mWidth * sizeof(aiTexel);
  927. if (!cpy)
  928. {
  929. dest->pcData = NULL;
  930. return;
  931. }
  932. // the cast is legal, the aiTexel c'tor does nothing important
  933. dest->pcData = (aiTexel*) new char[cpy];
  934. ::memcpy(dest->pcData, old, cpy);
  935. }
  936. }
  937. // ------------------------------------------------------------------------------------------------
  938. void SceneCombiner::Copy (aiAnimation** _dest, const aiAnimation* src)
  939. {
  940. ai_assert(NULL != _dest && NULL != src);
  941. aiAnimation* dest = *_dest = new aiAnimation();
  942. // get a flat copy
  943. ::memcpy(dest,src,sizeof(aiAnimation));
  944. // and reallocate all arrays
  945. CopyPtrArray( dest->mChannels, src->mChannels, dest->mNumChannels );
  946. }
  947. // ------------------------------------------------------------------------------------------------
  948. void SceneCombiner::Copy (aiNodeAnim** _dest, const aiNodeAnim* src)
  949. {
  950. ai_assert(NULL != _dest && NULL != src);
  951. aiNodeAnim* dest = *_dest = new aiNodeAnim();
  952. // get a flat copy
  953. ::memcpy(dest,src,sizeof(aiNodeAnim));
  954. // and reallocate all arrays
  955. GetArrayCopy( dest->mPositionKeys, dest->mNumPositionKeys );
  956. GetArrayCopy( dest->mScalingKeys, dest->mNumScalingKeys );
  957. GetArrayCopy( dest->mRotationKeys, dest->mNumRotationKeys );
  958. }
  959. // ------------------------------------------------------------------------------------------------
  960. void SceneCombiner::Copy (aiCamera** _dest,const aiCamera* src)
  961. {
  962. ai_assert(NULL != _dest && NULL != src);
  963. aiCamera* dest = *_dest = new aiCamera();
  964. // get a flat copy, that's already OK
  965. ::memcpy(dest,src,sizeof(aiCamera));
  966. }
  967. // ------------------------------------------------------------------------------------------------
  968. void SceneCombiner::Copy (aiLight** _dest, const aiLight* src)
  969. {
  970. ai_assert(NULL != _dest && NULL != src);
  971. aiLight* dest = *_dest = new aiLight();
  972. // get a flat copy, that's already OK
  973. ::memcpy(dest,src,sizeof(aiLight));
  974. }
  975. // ------------------------------------------------------------------------------------------------
  976. void SceneCombiner::Copy (aiBone** _dest, const aiBone* src)
  977. {
  978. ai_assert(NULL != _dest && NULL != src);
  979. aiBone* dest = *_dest = new aiBone();
  980. // get a flat copy
  981. ::memcpy(dest,src,sizeof(aiBone));
  982. // and reallocate all arrays
  983. GetArrayCopy( dest->mWeights, dest->mNumWeights );
  984. }
  985. // ------------------------------------------------------------------------------------------------
  986. void SceneCombiner::Copy (aiNode** _dest, const aiNode* src)
  987. {
  988. ai_assert(NULL != _dest && NULL != src);
  989. aiNode* dest = *_dest = new aiNode();
  990. // get a flat copy
  991. ::memcpy(dest,src,sizeof(aiNode));
  992. // and reallocate all arrays
  993. GetArrayCopy( dest->mMeshes, dest->mNumMeshes );
  994. CopyPtrArray( dest->mChildren, src->mChildren,dest->mNumChildren);
  995. }
  996. }