SceneCombiner.cpp 34 KB

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