SceneCombiner.cpp 37 KB

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