SceneCombiner.cpp 33 KB

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