SceneCombiner.cpp 33 KB

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