SceneCombiner.cpp 33 KB

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