AMFImporter_Postprocess.cpp 35 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969
  1. /*
  2. ---------------------------------------------------------------------------
  3. Open Asset Import Library (assimp)
  4. ---------------------------------------------------------------------------
  5. Copyright (c) 2006-2016, assimp team
  6. All rights reserved.
  7. Redistribution and use of this software in source and binary forms,
  8. with or without modification, are permitted provided that the following
  9. conditions are met:
  10. * Redistributions of source code must retain the above
  11. copyright notice, this list of conditions and the
  12. following disclaimer.
  13. * Redistributions in binary form must reproduce the above
  14. copyright notice, this list of conditions and the
  15. following disclaimer in the documentation and/or other
  16. materials provided with the distribution.
  17. * Neither the name of the assimp team, nor the names of its
  18. contributors may be used to endorse or promote products
  19. derived from this software without specific prior
  20. written permission of the assimp team.
  21. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
  22. "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
  23. LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
  24. A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
  25. OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
  26. SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
  27. LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
  28. DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
  29. THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
  30. (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
  31. OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
  32. ---------------------------------------------------------------------------
  33. */
  34. /// \file AMFImporter_Postprocess.cpp
  35. /// \brief Convert built scenegraph and objects to Assimp scenegraph.
  36. /// \date 2016
  37. /// \author [email protected]
  38. #ifndef ASSIMP_BUILD_NO_AMF_IMPORTER
  39. #include "AMFImporter.hpp"
  40. // Header files, Assimp.
  41. #include "SceneCombiner.h"
  42. #include "StandardShapes.h"
  43. // Header files, stdlib.
  44. #include <algorithm>
  45. #include <iterator>
  46. namespace Assimp
  47. {
  48. aiColor4D AMFImporter::SPP_Material::GetColor(const float pX, const float pY, const float pZ) const
  49. {
  50. aiColor4D tcol;
  51. // Check if stored data are supported.
  52. if(Composition.size() != 0)
  53. {
  54. throw DeadlyImportError("IME. GetColor for composition");
  55. }
  56. else if(Color->Composed)
  57. {
  58. throw DeadlyImportError("IME. GetColor, composed color");
  59. }
  60. else
  61. {
  62. tcol = Color->Color;
  63. }
  64. // Check if default color must be used
  65. if((tcol.r == 0) && (tcol.g == 0) && (tcol.b == 0) && (tcol.a == 0))
  66. {
  67. tcol.r = 0.5f;
  68. tcol.g = 0.5f;
  69. tcol.b = 0.5f;
  70. tcol.a = 1;
  71. }
  72. return tcol;
  73. }
  74. void AMFImporter::PostprocessHelper_CreateMeshDataArray(const CAMFImporter_NodeElement_Mesh& pNodeElement, std::vector<aiVector3D>& pVertexCoordinateArray,
  75. std::vector<CAMFImporter_NodeElement_Color*>& pVertexColorArray) const
  76. {
  77. CAMFImporter_NodeElement_Vertices* vn = nullptr;
  78. size_t col_idx;
  79. // All data stored in "vertices", search for it.
  80. for(CAMFImporter_NodeElement* ne_child: pNodeElement.Child)
  81. {
  82. if(ne_child->Type == CAMFImporter_NodeElement::ENET_Vertices) vn = (CAMFImporter_NodeElement_Vertices*)ne_child;
  83. }
  84. // If "vertices" not found then no work for us.
  85. if(vn == nullptr) return;
  86. pVertexCoordinateArray.reserve(vn->Child.size());// all coordinates stored as child and we need to reserve space for future push_back's.
  87. pVertexColorArray.resize(vn->Child.size());// colors count equal vertices count.
  88. col_idx = 0;
  89. // Inside vertices collect all data and place to arrays
  90. for(CAMFImporter_NodeElement* vn_child: vn->Child)
  91. {
  92. // vertices, colors
  93. if(vn_child->Type == CAMFImporter_NodeElement::ENET_Vertex)
  94. {
  95. // by default clear color for current vertex
  96. pVertexColorArray[col_idx] = nullptr;
  97. for(CAMFImporter_NodeElement* vtx: vn_child->Child)
  98. {
  99. if(vtx->Type == CAMFImporter_NodeElement::ENET_Coordinates)
  100. {
  101. pVertexCoordinateArray.push_back(((CAMFImporter_NodeElement_Coordinates*)vtx)->Coordinate);
  102. continue;
  103. }
  104. if(vtx->Type == CAMFImporter_NodeElement::ENET_Color)
  105. {
  106. pVertexColorArray[col_idx] = (CAMFImporter_NodeElement_Color*)vtx;
  107. continue;
  108. }
  109. }// for(CAMFImporter_NodeElement* vtx: vn_child->Child)
  110. col_idx++;
  111. }// if(vn_child->Type == CAMFImporter_NodeElement::ENET_Vertex)
  112. }// for(CAMFImporter_NodeElement* vn_child: vn->Child)
  113. }
  114. size_t AMFImporter::PostprocessHelper_GetTextureID_Or_Create(const std::string& pID_R, const std::string& pID_G, const std::string& pID_B,
  115. const std::string& pID_A)
  116. {
  117. size_t TextureConverted_Index;
  118. std::string TextureConverted_ID;
  119. // check input data
  120. if(pID_R.empty() && pID_G.empty() && pID_B.empty() && pID_A.empty())
  121. throw DeadlyImportError("PostprocessHelper_GetTextureID_Or_Create. At least one texture ID must be defined.");
  122. // Create ID
  123. TextureConverted_ID = pID_R + "_" + pID_G + "_" + pID_B + "_" + pID_A;
  124. // Check if texture specified by set of IDs is converted already.
  125. TextureConverted_Index = 0;
  126. for(const SPP_Texture& tex_convd: mTexture_Converted)
  127. {
  128. if(tex_convd.ID == TextureConverted_ID)
  129. return TextureConverted_Index;
  130. else
  131. TextureConverted_Index++;
  132. }
  133. //
  134. // Converted texture not found, create it.
  135. //
  136. CAMFImporter_NodeElement_Texture* src_texture[4]{nullptr};
  137. std::vector<CAMFImporter_NodeElement_Texture*> src_texture_4check;
  138. SPP_Texture converted_texture;
  139. {// find all specified source textures
  140. CAMFImporter_NodeElement* t_tex;
  141. // R
  142. if(!pID_R.empty())
  143. {
  144. if(!Find_NodeElement(pID_R, CAMFImporter_NodeElement::ENET_Texture, &t_tex)) Throw_ID_NotFound(pID_R);
  145. src_texture[0] = (CAMFImporter_NodeElement_Texture*)t_tex;
  146. src_texture_4check.push_back((CAMFImporter_NodeElement_Texture*)t_tex);
  147. }
  148. else
  149. {
  150. src_texture[0] = nullptr;
  151. }
  152. // G
  153. if(!pID_G.empty())
  154. {
  155. if(!Find_NodeElement(pID_G, CAMFImporter_NodeElement::ENET_Texture, &t_tex)) Throw_ID_NotFound(pID_G);
  156. src_texture[1] = (CAMFImporter_NodeElement_Texture*)t_tex;
  157. src_texture_4check.push_back((CAMFImporter_NodeElement_Texture*)t_tex);
  158. }
  159. else
  160. {
  161. src_texture[1] = nullptr;
  162. }
  163. // B
  164. if(!pID_B.empty())
  165. {
  166. if(!Find_NodeElement(pID_B, CAMFImporter_NodeElement::ENET_Texture, &t_tex)) Throw_ID_NotFound(pID_B);
  167. src_texture[2] = (CAMFImporter_NodeElement_Texture*)t_tex;
  168. src_texture_4check.push_back((CAMFImporter_NodeElement_Texture*)t_tex);
  169. }
  170. else
  171. {
  172. src_texture[2] = nullptr;
  173. }
  174. // A
  175. if(!pID_A.empty())
  176. {
  177. if(!Find_NodeElement(pID_A, CAMFImporter_NodeElement::ENET_Texture, &t_tex)) Throw_ID_NotFound(pID_A);
  178. src_texture[3] = (CAMFImporter_NodeElement_Texture*)t_tex;
  179. src_texture_4check.push_back((CAMFImporter_NodeElement_Texture*)t_tex);
  180. }
  181. else
  182. {
  183. src_texture[3] = nullptr;
  184. }
  185. }// END: find all specified source textures
  186. // check that all textures has same size
  187. if(src_texture_4check.size() > 1)
  188. {
  189. for(uint8_t i = 0, i_e = (src_texture_4check.size() - 1); i < i_e; i++)
  190. {
  191. if((src_texture_4check[i]->Width != src_texture_4check[i + 1]->Width) || (src_texture_4check[i]->Height != src_texture_4check[i + 1]->Height) ||
  192. (src_texture_4check[i]->Depth != src_texture_4check[i + 1]->Depth))
  193. {
  194. throw DeadlyImportError("PostprocessHelper_GetTextureID_Or_Create. Source texture must has the same size.");
  195. }
  196. }
  197. }// if(src_texture_4check.size() > 1)
  198. // set texture attributes
  199. converted_texture.Width = src_texture_4check[0]->Width;
  200. converted_texture.Height = src_texture_4check[0]->Height;
  201. converted_texture.Depth = src_texture_4check[0]->Depth;
  202. // if one of source texture is tiled then converted texture is tiled too.
  203. converted_texture.Tiled = false;
  204. for(uint8_t i = 0; i < src_texture_4check.size(); i++) converted_texture.Tiled |= src_texture_4check[i]->Tiled;
  205. // Create format hint.
  206. strcpy(converted_texture.FormatHint, "rgba0000");// copy initial string.
  207. if(!pID_R.empty()) converted_texture.FormatHint[4] = '8';
  208. if(!pID_G.empty()) converted_texture.FormatHint[5] = '8';
  209. if(!pID_B.empty()) converted_texture.FormatHint[6] = '8';
  210. if(!pID_A.empty()) converted_texture.FormatHint[7] = '8';
  211. //
  212. // Сopy data of textures.
  213. //
  214. size_t tex_size = 0;
  215. size_t step = 0;
  216. size_t off_g = 0;
  217. size_t off_b = 0;
  218. // Calculate size of the target array and rule how data will be copied.
  219. if(!pID_R.empty()) { tex_size += src_texture[0]->Data.size(); step++, off_g++, off_b++; }
  220. if(!pID_G.empty()) { tex_size += src_texture[1]->Data.size(); step++, off_b++; }
  221. if(!pID_B.empty()) { tex_size += src_texture[2]->Data.size(); step++; }
  222. if(!pID_A.empty()) { tex_size += src_texture[3]->Data.size(); step++; }
  223. // Create target array.
  224. converted_texture.Data = new uint8_t[tex_size];
  225. // And copy data
  226. auto CopyTextureData = [&](const std::string& pID, const size_t pOffset, const size_t pStep, const uint8_t pSrcTexNum) -> void
  227. {
  228. if(!pID.empty())
  229. {
  230. for(size_t idx_target = pOffset, idx_src = 0; idx_target < tex_size; idx_target += pStep, idx_src++)
  231. converted_texture.Data[idx_target] = src_texture[pSrcTexNum]->Data.at(idx_src);
  232. }
  233. };// auto CopyTextureData = [&](const size_t pOffset, const size_t pStep, const uint8_t pSrcTexNum) -> void
  234. CopyTextureData(pID_R, 0, step, 0);
  235. CopyTextureData(pID_G, off_g, step, 1);
  236. CopyTextureData(pID_B, off_b, step, 2);
  237. CopyTextureData(pID_A, step - 1, step, 3);
  238. // Store new converted texture ID
  239. converted_texture.ID = TextureConverted_ID;
  240. // Store new converted texture
  241. mTexture_Converted.push_back(converted_texture);
  242. return TextureConverted_Index;
  243. }
  244. void AMFImporter::PostprocessHelper_SplitFacesByTextureID(std::list<SComplexFace>& pInputList, std::list<std::list<SComplexFace> >& pOutputList_Separated)
  245. {
  246. auto texmap_is_equal = [](const CAMFImporter_NodeElement_TexMap* pTexMap1, const CAMFImporter_NodeElement_TexMap* pTexMap2) -> bool
  247. {
  248. if((pTexMap1 == nullptr) && (pTexMap2 == nullptr)) return true;
  249. if(pTexMap1 == nullptr) return false;
  250. if(pTexMap2 == nullptr) return false;
  251. if(pTexMap1->TextureID_R != pTexMap2->TextureID_R) return false;
  252. if(pTexMap1->TextureID_G != pTexMap2->TextureID_G) return false;
  253. if(pTexMap1->TextureID_B != pTexMap2->TextureID_B) return false;
  254. if(pTexMap1->TextureID_A != pTexMap2->TextureID_A) return false;
  255. return true;
  256. };
  257. pOutputList_Separated.clear();
  258. if(pInputList.size() == 0) return;
  259. do
  260. {
  261. SComplexFace face_start = pInputList.front();
  262. std::list<SComplexFace> face_list_cur;
  263. for(std::list<SComplexFace>::iterator it = pInputList.begin(), it_end = pInputList.end(); it != it_end;)
  264. {
  265. if(texmap_is_equal(face_start.TexMap, it->TexMap))
  266. {
  267. auto it_old = it;
  268. it++;
  269. face_list_cur.push_back(*it_old);
  270. pInputList.erase(it_old);
  271. }
  272. else
  273. {
  274. it++;
  275. }
  276. }
  277. if(face_list_cur.size() > 0) pOutputList_Separated.push_back(face_list_cur);
  278. } while(pInputList.size() > 0);
  279. }
  280. void AMFImporter::Postprocess_AddMetadata(const std::list<CAMFImporter_NodeElement_Metadata*>& pMetadataList, aiNode& pSceneNode) const
  281. {
  282. if(pMetadataList.size() > 0)
  283. {
  284. if(pSceneNode.mMetaData != nullptr) throw DeadlyImportError("Postprocess. MetaData member in node are not nullptr. Something went wrong.");
  285. // copy collected metadata to output node.
  286. pSceneNode.mMetaData = new aiMetadata();
  287. pSceneNode.mMetaData->mNumProperties = pMetadataList.size();
  288. pSceneNode.mMetaData->mKeys = new aiString[pSceneNode.mMetaData->mNumProperties];
  289. pSceneNode.mMetaData->mValues = new aiMetadataEntry[pSceneNode.mMetaData->mNumProperties];
  290. size_t meta_idx = 0;
  291. for(const CAMFImporter_NodeElement_Metadata& metadata: pMetadataList)
  292. {
  293. pSceneNode.mMetaData->Set(meta_idx++, metadata.Type, metadata.Value.c_str());
  294. }
  295. }// if(pMetadataList.size() > 0)
  296. }
  297. void AMFImporter::Postprocess_BuildNodeAndObject(const CAMFImporter_NodeElement_Object& pNodeElement, std::list<aiMesh*>& pMeshList, aiNode** pSceneNode)
  298. {
  299. CAMFImporter_NodeElement_Color* object_color = nullptr;
  300. // create new aiNode and set name as <object> has.
  301. *pSceneNode = new aiNode;
  302. (*pSceneNode)->mName = pNodeElement.ID;
  303. // read mesh and color
  304. for(const CAMFImporter_NodeElement* ne_child: pNodeElement.Child)
  305. {
  306. std::vector<aiVector3D> vertex_arr;
  307. std::vector<CAMFImporter_NodeElement_Color*> color_arr;
  308. // color for object
  309. if(ne_child->Type == CAMFImporter_NodeElement::ENET_Color) object_color = (CAMFImporter_NodeElement_Color*)ne_child;
  310. if(ne_child->Type == CAMFImporter_NodeElement::ENET_Mesh)
  311. {
  312. // Create arrays from children of mesh: vertices.
  313. PostprocessHelper_CreateMeshDataArray(*((CAMFImporter_NodeElement_Mesh*)ne_child), vertex_arr, color_arr);
  314. // Use this arrays as a source when creating every aiMesh
  315. Postprocess_BuildMeshSet(*((CAMFImporter_NodeElement_Mesh*)ne_child), vertex_arr, color_arr, object_color, pMeshList, **pSceneNode);
  316. }
  317. }// for(const CAMFImporter_NodeElement* ne_child: pNodeElement)
  318. }
  319. void AMFImporter::Postprocess_BuildMeshSet(const CAMFImporter_NodeElement_Mesh& pNodeElement, const std::vector<aiVector3D>& pVertexCoordinateArray,
  320. const std::vector<CAMFImporter_NodeElement_Color*>& pVertexColorArray,
  321. const CAMFImporter_NodeElement_Color* pObjectColor, std::list<aiMesh*>& pMeshList, aiNode& pSceneNode)
  322. {
  323. std::list<unsigned int> mesh_idx;
  324. // all data stored in "volume", search for it.
  325. for(const CAMFImporter_NodeElement* ne_child: pNodeElement.Child)
  326. {
  327. const CAMFImporter_NodeElement_Color* ne_volume_color = nullptr;
  328. const SPP_Material* cur_mat = nullptr;
  329. if(ne_child->Type == CAMFImporter_NodeElement::ENET_Volume)
  330. {
  331. /******************* Get faces *******************/
  332. const CAMFImporter_NodeElement_Volume* ne_volume = reinterpret_cast<const CAMFImporter_NodeElement_Volume*>(ne_child);
  333. std::list<SComplexFace> complex_faces_list;// List of the faces of the volume.
  334. std::list<std::list<SComplexFace> > complex_faces_toplist;// List of the face list for every mesh.
  335. // check if volume use material
  336. if(!ne_volume->MaterialID.empty())
  337. {
  338. if(!Find_ConvertedMaterial(ne_volume->MaterialID, &cur_mat)) Throw_ID_NotFound(ne_volume->MaterialID);
  339. }
  340. // inside "volume" collect all data and place to arrays or create new objects
  341. for(const CAMFImporter_NodeElement* ne_volume_child: ne_volume->Child)
  342. {
  343. // color for volume
  344. if(ne_volume_child->Type == CAMFImporter_NodeElement::ENET_Color)
  345. {
  346. ne_volume_color = reinterpret_cast<const CAMFImporter_NodeElement_Color*>(ne_volume_child);
  347. }
  348. else if(ne_volume_child->Type == CAMFImporter_NodeElement::ENET_Triangle)// triangles, triangles colors
  349. {
  350. const CAMFImporter_NodeElement_Triangle& tri_al = *reinterpret_cast<const CAMFImporter_NodeElement_Triangle*>(ne_volume_child);
  351. SComplexFace complex_face;
  352. // initialize pointers
  353. complex_face.Color = nullptr;
  354. complex_face.TexMap = nullptr;
  355. // get data from triangle children: color, texture coordinates.
  356. if(tri_al.Child.size())
  357. {
  358. for(const CAMFImporter_NodeElement* ne_triangle_child: tri_al.Child)
  359. {
  360. if(ne_triangle_child->Type == CAMFImporter_NodeElement::ENET_Color)
  361. complex_face.Color = reinterpret_cast<const CAMFImporter_NodeElement_Color*>(ne_triangle_child);
  362. else if(ne_triangle_child->Type == CAMFImporter_NodeElement::ENET_TexMap)
  363. complex_face.TexMap = reinterpret_cast<const CAMFImporter_NodeElement_TexMap*>(ne_triangle_child);
  364. }
  365. }// if(tri_al.Child.size())
  366. // create new face and store it.
  367. complex_face.Face.mNumIndices = 3;
  368. complex_face.Face.mIndices = new unsigned int[3];
  369. complex_face.Face.mIndices[0] = tri_al.V[0];
  370. complex_face.Face.mIndices[1] = tri_al.V[1];
  371. complex_face.Face.mIndices[2] = tri_al.V[2];
  372. complex_faces_list.push_back(complex_face);
  373. }
  374. }// for(const CAMFImporter_NodeElement* ne_volume_child: ne_volume->Child)
  375. /**** Split faces list: one list per mesh ****/
  376. PostprocessHelper_SplitFacesByTextureID(complex_faces_list, complex_faces_toplist);
  377. /***** Create mesh for every faces list ******/
  378. for(std::list<SComplexFace>& face_list_cur: complex_faces_toplist)
  379. {
  380. auto VertexIndex_GetMinimal = [](const std::list<SComplexFace>& pFaceList, const size_t* pBiggerThan) -> size_t
  381. {
  382. size_t rv;
  383. if(pBiggerThan != nullptr)
  384. {
  385. bool found = false;
  386. for(const SComplexFace& face: pFaceList)
  387. {
  388. for(size_t idx_vert = 0; idx_vert < face.Face.mNumIndices; idx_vert++)
  389. {
  390. if(face.Face.mIndices[idx_vert] > *pBiggerThan)
  391. {
  392. rv = face.Face.mIndices[idx_vert];
  393. found = true;
  394. break;
  395. }
  396. }
  397. if(found) break;
  398. }
  399. if(!found) return *pBiggerThan;
  400. }
  401. else
  402. {
  403. rv = pFaceList.front().Face.mIndices[0];
  404. }// if(pBiggerThan != nullptr) else
  405. for(const SComplexFace& face: pFaceList)
  406. {
  407. for(size_t vi = 0; vi < face.Face.mNumIndices; vi++)
  408. {
  409. if(face.Face.mIndices[vi] < rv)
  410. {
  411. if(pBiggerThan != nullptr)
  412. {
  413. if(face.Face.mIndices[vi] > *pBiggerThan) rv = face.Face.mIndices[vi];
  414. }
  415. else
  416. {
  417. rv = face.Face.mIndices[vi];
  418. }
  419. }
  420. }
  421. }// for(const SComplexFace& face: pFaceList)
  422. return rv;
  423. };// auto VertexIndex_GetMinimal = [](const std::list<SComplexFace>& pFaceList, const size_t* pBiggerThan) -> size_t
  424. auto VertexIndex_Replace = [](std::list<SComplexFace>& pFaceList, const size_t pIdx_From, const size_t pIdx_To) -> void
  425. {
  426. for(const SComplexFace& face: pFaceList)
  427. {
  428. for(size_t vi = 0; vi < face.Face.mNumIndices; vi++)
  429. {
  430. if(face.Face.mIndices[vi] == pIdx_From) face.Face.mIndices[vi] = pIdx_To;
  431. }
  432. }
  433. };// auto VertexIndex_Replace = [](std::list<SComplexFace>& pFaceList, const size_t pIdx_From, const size_t pIdx_To) -> void
  434. auto Vertex_CalculateColor = [&](const size_t pIdx) -> aiColor4D
  435. {
  436. // Color priorities(In descending order):
  437. // 1. triangle color;
  438. // 2. vertex color;
  439. // 3. volume color;
  440. // 4. object color;
  441. // 5. material;
  442. // 6. default - invisible coat.
  443. //
  444. // Fill vertices colors in color priority list above that's points from 1 to 6.
  445. if((pIdx < pVertexColorArray.size()) && (pVertexColorArray[pIdx] != nullptr))// check for vertex color
  446. {
  447. if(pVertexColorArray[pIdx]->Composed)
  448. throw DeadlyImportError("IME: vertex color composed");
  449. else
  450. return pVertexColorArray[pIdx]->Color;
  451. }
  452. else if(ne_volume_color != nullptr)// check for volume color
  453. {
  454. if(ne_volume_color->Composed)
  455. throw DeadlyImportError("IME: volume color composed");
  456. else
  457. return ne_volume_color->Color;
  458. }
  459. else if(pObjectColor != nullptr)// check for object color
  460. {
  461. if(pObjectColor->Composed)
  462. throw DeadlyImportError("IME: object color composed");
  463. else
  464. return pObjectColor->Color;
  465. }
  466. else if(cur_mat != nullptr)// check for material
  467. {
  468. return cur_mat->GetColor(pVertexCoordinateArray.at(pIdx).x, pVertexCoordinateArray.at(pIdx).y, pVertexCoordinateArray.at(pIdx).z);
  469. }
  470. else// set default color.
  471. {
  472. return {0, 0, 0, 0};
  473. }// if((vi < pVertexColorArray.size()) && (pVertexColorArray[vi] != nullptr)) else
  474. };// auto Vertex_CalculateColor = [&](const size_t pIdx) -> aiColor4D
  475. aiMesh* tmesh = new aiMesh;
  476. tmesh->mPrimitiveTypes = aiPrimitiveType_TRIANGLE;// Only triangles is supported by AMF.
  477. //
  478. // set geometry and colors (vertices)
  479. //
  480. // copy faces/triangles
  481. tmesh->mNumFaces = face_list_cur.size();
  482. tmesh->mFaces = new aiFace[tmesh->mNumFaces];
  483. // Create vertices list and optimize indices. Optimisation mean following.In AMF all volumes use one big list of vertices. And one volume
  484. // can use only part of vertices list, for example: vertices list contain few thousands of vertices and volume use vertices 1, 3, 10.
  485. // Do you need all this thousands of garbage? Of course no. So, optimisation step transformate sparse indices set to continuous.
  486. size_t VertexCount_Max = tmesh->mNumFaces * 3;// 3 - triangles.
  487. std::vector<aiVector3D> vert_arr, texcoord_arr;
  488. std::vector<aiColor4D> col_arr;
  489. vert_arr.reserve(VertexCount_Max * 2);// "* 2" - see below TODO.
  490. col_arr.reserve(VertexCount_Max * 2);
  491. {// fill arrays
  492. size_t vert_idx_from, vert_idx_to;
  493. // first iteration.
  494. vert_idx_to = 0;
  495. vert_idx_from = VertexIndex_GetMinimal(face_list_cur, nullptr);
  496. vert_arr.push_back(pVertexCoordinateArray.at(vert_idx_from));
  497. col_arr.push_back(Vertex_CalculateColor(vert_idx_from));
  498. if(vert_idx_from != vert_idx_to) VertexIndex_Replace(face_list_cur, vert_idx_from, vert_idx_to);
  499. // rest iterations
  500. do
  501. {
  502. vert_idx_from = VertexIndex_GetMinimal(face_list_cur, &vert_idx_to);
  503. if(vert_idx_from == vert_idx_to) break;// all indices are transfered,
  504. vert_arr.push_back(pVertexCoordinateArray.at(vert_idx_from));
  505. col_arr.push_back(Vertex_CalculateColor(vert_idx_from));
  506. vert_idx_to++;
  507. if(vert_idx_from != vert_idx_to) VertexIndex_Replace(face_list_cur, vert_idx_from, vert_idx_to);
  508. } while(true);
  509. }// fill arrays. END.
  510. //
  511. // check if triangle colors are used and create additional faces if needed.
  512. //
  513. for(const SComplexFace& face_cur: face_list_cur)
  514. {
  515. if(face_cur.Color != nullptr)
  516. {
  517. aiColor4D face_color;
  518. size_t vert_idx_new = vert_arr.size();
  519. if(face_cur.Color->Composed)
  520. throw DeadlyImportError("IME: face color composed");
  521. else
  522. face_color = face_cur.Color->Color;
  523. for(size_t idx_ind = 0; idx_ind < face_cur.Face.mNumIndices; idx_ind++)
  524. {
  525. vert_arr.push_back(vert_arr.at(face_cur.Face.mIndices[idx_ind]));
  526. col_arr.push_back(face_color);
  527. face_cur.Face.mIndices[idx_ind] = vert_idx_new++;
  528. }
  529. }// if(face_cur.Color != nullptr)
  530. }// for(const SComplexFace& face_cur: face_list_cur)
  531. //
  532. // if texture is used then copy texture coordinates too.
  533. //
  534. if(face_list_cur.front().TexMap != nullptr)
  535. {
  536. size_t idx_vert_new = vert_arr.size();
  537. ///TODO: clean unused vertices. "* 2": in certain cases - mesh full of triangle colors - vert_arr will contain duplicated vertices for
  538. /// colored triangles and initial vertices (for colored vertices) which in real became unused. This part need more thinking about
  539. /// optimisation.
  540. bool* idx_vert_used;
  541. idx_vert_used = new bool[VertexCount_Max * 2];
  542. for(size_t i = 0, i_e = VertexCount_Max * 2; i < i_e; i++) idx_vert_used[i] = false;
  543. // This ID's will be used when set materials ID in scene.
  544. tmesh->mMaterialIndex = PostprocessHelper_GetTextureID_Or_Create(face_list_cur.front().TexMap->TextureID_R,
  545. face_list_cur.front().TexMap->TextureID_G,
  546. face_list_cur.front().TexMap->TextureID_B,
  547. face_list_cur.front().TexMap->TextureID_A);
  548. texcoord_arr.resize(VertexCount_Max * 2);
  549. for(const SComplexFace& face_cur: face_list_cur)
  550. {
  551. for(size_t idx_ind = 0; idx_ind < face_cur.Face.mNumIndices; idx_ind++)
  552. {
  553. const size_t idx_vert = face_cur.Face.mIndices[idx_ind];
  554. if(!idx_vert_used[idx_vert])
  555. {
  556. texcoord_arr.at(idx_vert) = face_cur.TexMap->TextureCoordinate[idx_ind];
  557. idx_vert_used[idx_vert] = true;
  558. }
  559. else if(texcoord_arr.at(idx_vert) != face_cur.TexMap->TextureCoordinate[idx_ind])
  560. {
  561. // in that case one vertex is shared with many texture coordinates. We need to duplicate vertex with another texture
  562. // coordinates.
  563. vert_arr.push_back(vert_arr.at(idx_vert));
  564. col_arr.push_back(col_arr.at(idx_vert));
  565. texcoord_arr.at(idx_vert_new) = face_cur.TexMap->TextureCoordinate[idx_ind];
  566. face_cur.Face.mIndices[idx_ind] = idx_vert_new++;
  567. }
  568. }// for(size_t idx_ind = 0; idx_ind < face_cur.Face.mNumIndices; idx_ind++)
  569. }// for(const SComplexFace& face_cur: face_list_cur)
  570. delete [] idx_vert_used;
  571. // shrink array
  572. texcoord_arr.resize(idx_vert_new);
  573. }// if(face_list_cur.front().TexMap != nullptr)
  574. //
  575. // copy collected data to mesh
  576. //
  577. tmesh->mNumVertices = vert_arr.size();
  578. tmesh->mVertices = new aiVector3D[tmesh->mNumVertices];
  579. tmesh->mColors[0] = new aiColor4D[tmesh->mNumVertices];
  580. tmesh->mFaces = new aiFace[face_list_cur.size()];
  581. memcpy(tmesh->mVertices, vert_arr.data(), tmesh->mNumVertices * sizeof(aiVector3D));
  582. memcpy(tmesh->mColors[0], col_arr.data(), tmesh->mNumVertices * sizeof(aiColor4D));
  583. if(texcoord_arr.size() > 0)
  584. {
  585. tmesh->mTextureCoords[0] = new aiVector3D[tmesh->mNumVertices];
  586. memcpy(tmesh->mTextureCoords[0], texcoord_arr.data(), tmesh->mNumVertices * sizeof(aiVector3D));
  587. tmesh->mNumUVComponents[0] = 2;// U and V stored in "x", "y" of aiVector3D.
  588. }
  589. size_t idx_face = 0;
  590. for(const SComplexFace& face_cur: face_list_cur) tmesh->mFaces[idx_face++] = face_cur.Face;
  591. // store new aiMesh
  592. mesh_idx.push_back(pMeshList.size());
  593. pMeshList.push_back(tmesh);
  594. }// for(const std::list<SComplexFace>& face_list_cur: complex_faces_toplist)
  595. }// if(ne_child->Type == CAMFImporter_NodeElement::ENET_Volume)
  596. }// for(const CAMFImporter_NodeElement* ne_child: pNodeElement.Child)
  597. // if meshes was created then assign new indices with current aiNode
  598. if(mesh_idx.size() > 0)
  599. {
  600. std::list<unsigned int>::const_iterator mit = mesh_idx.begin();
  601. pSceneNode.mNumMeshes = mesh_idx.size();
  602. pSceneNode.mMeshes = new unsigned int[pSceneNode.mNumMeshes];
  603. for(size_t i = 0; i < pSceneNode.mNumMeshes; i++) pSceneNode.mMeshes[i] = *mit++;
  604. }// if(mesh_idx.size() > 0)
  605. }
  606. void AMFImporter::Postprocess_BuildMaterial(const CAMFImporter_NodeElement_Material& pMaterial)
  607. {
  608. SPP_Material new_mat;
  609. new_mat.ID = pMaterial.ID;
  610. for(const CAMFImporter_NodeElement* mat_child: pMaterial.Child)
  611. {
  612. if(mat_child->Type == CAMFImporter_NodeElement::ENET_Color)
  613. {
  614. new_mat.Color = (CAMFImporter_NodeElement_Color*)mat_child;
  615. }
  616. else if(mat_child->Type == CAMFImporter_NodeElement::ENET_Metadata)
  617. {
  618. new_mat.Metadata.push_back((CAMFImporter_NodeElement_Metadata*)mat_child);
  619. }
  620. }// for(const CAMFImporter_NodeElement* mat_child; pMaterial.Child)
  621. // place converted material to special list
  622. mMaterial_Converted.push_back(new_mat);
  623. }
  624. void AMFImporter::Postprocess_BuildConstellation(CAMFImporter_NodeElement_Constellation& pConstellation, std::list<aiNode*>& pNodeList) const
  625. {
  626. aiNode* con_node;
  627. std::list<aiNode*> ch_node;
  628. // We will build next hierarchy:
  629. // aiNode as parent (<constellation>) for set of nodes as a children
  630. // |- aiNode for transformation (<instance> -> <delta...>, <r...>) - aiNode for pointing to object ("objectid")
  631. // ...
  632. // \_ aiNode for transformation (<instance> -> <delta...>, <r...>) - aiNode for pointing to object ("objectid")
  633. con_node = new aiNode;
  634. con_node->mName = pConstellation.ID;
  635. // Walk thru children and search for instances of another objects, constellations.
  636. for(const CAMFImporter_NodeElement* ne: pConstellation.Child)
  637. {
  638. aiMatrix4x4 tmat;
  639. aiNode* t_node;
  640. aiNode* found_node;
  641. if(ne->Type == CAMFImporter_NodeElement::ENET_Metadata) continue;
  642. if(ne->Type != CAMFImporter_NodeElement::ENET_Instance) throw DeadlyImportError("Only <instance> nodes can be in <constellation>.");
  643. // create alias for conveniance
  644. CAMFImporter_NodeElement_Instance& als = *((CAMFImporter_NodeElement_Instance*)ne);
  645. // find referenced object
  646. if(!Find_ConvertedNode(als.ObjectID, pNodeList, &found_node)) Throw_ID_NotFound(als.ObjectID);
  647. // create node for apllying transformation
  648. t_node = new aiNode;
  649. t_node->mParent = con_node;
  650. // apply transformation
  651. aiMatrix4x4::Translation(als.Delta, tmat), t_node->mTransformation *= tmat;
  652. aiMatrix4x4::RotationX(als.Rotation.x, tmat), t_node->mTransformation *= tmat;
  653. aiMatrix4x4::RotationY(als.Rotation.y, tmat), t_node->mTransformation *= tmat;
  654. aiMatrix4x4::RotationZ(als.Rotation.z, tmat), t_node->mTransformation *= tmat;
  655. // create array for one child node
  656. t_node->mNumChildren = 1;
  657. t_node->mChildren = new aiNode*[t_node->mNumChildren];
  658. SceneCombiner::Copy(&t_node->mChildren[0], found_node);
  659. t_node->mChildren[0]->mParent = t_node;
  660. ch_node.push_back(t_node);
  661. }// for(const CAMFImporter_NodeElement* ne: pConstellation.Child)
  662. // copy found aiNode's as children
  663. if(ch_node.size() == 0) throw DeadlyImportError("<constellation> must have at least one <instance>.");
  664. size_t ch_idx = 0;
  665. con_node->mNumChildren = ch_node.size();
  666. con_node->mChildren = new aiNode*[con_node->mNumChildren];
  667. for(aiNode* node: ch_node) con_node->mChildren[ch_idx++] = node;
  668. // and place "root" of <constellation> node to node list
  669. pNodeList.push_back(con_node);
  670. }
  671. void AMFImporter::Postprocess_BuildScene(aiScene* pScene)
  672. {
  673. std::list<aiNode*> node_list;
  674. std::list<aiMesh*> mesh_list;
  675. std::list<CAMFImporter_NodeElement_Metadata*> meta_list;
  676. //
  677. // Because for AMF "material" is just complex colors mixing so aiMaterial will not be used.
  678. // For building aiScene we are must to do few steps:
  679. // at first creating root node for aiScene.
  680. pScene->mRootNode = new aiNode;
  681. pScene->mRootNode->mParent = nullptr;
  682. pScene->mFlags |= AI_SCENE_FLAGS_ALLOW_SHARED;
  683. // search for root(<amf>) element
  684. CAMFImporter_NodeElement* root_el = nullptr;
  685. for(CAMFImporter_NodeElement* ne: mNodeElement_List)
  686. {
  687. if(ne->Type != CAMFImporter_NodeElement::ENET_Root) continue;
  688. root_el = ne;
  689. break;
  690. }// for(const CAMFImporter_NodeElement* ne: mNodeElement_List)
  691. // Check if root element are found.
  692. if(root_el == nullptr) throw DeadlyImportError("Root(<amf>) element not found.");
  693. // after that walk thru children of root and collect data. Five types of nodes can be placed at top level - in <amf>: <object>, <material>, <texture>,
  694. // <constellation> and <metadata>. But at first we must read <material> and <texture> because they will be used in <object>. <metadata> can be read
  695. // at any moment.
  696. //
  697. // 1. <material>
  698. // 2. <texture> will be converted later when processing triangles list. \sa Postprocess_BuildMeshSet
  699. for(const CAMFImporter_NodeElement* root_child: root_el->Child)
  700. {
  701. if(root_child->Type == CAMFImporter_NodeElement::ENET_Material) Postprocess_BuildMaterial(*((CAMFImporter_NodeElement_Material*)root_child));
  702. }
  703. // After "appearance" nodes we must read <object> because it will be used in <constellation> -> <instance>.
  704. //
  705. // 3. <object>
  706. for(const CAMFImporter_NodeElement* root_child: root_el->Child)
  707. {
  708. if(root_child->Type == CAMFImporter_NodeElement::ENET_Object)
  709. {
  710. aiNode* tnode = nullptr;
  711. // for <object> mesh and node must be built: object ID assigned to aiNode name and will be used in future for <instance>
  712. Postprocess_BuildNodeAndObject(*((CAMFImporter_NodeElement_Object*)root_child), mesh_list, &tnode);
  713. if(tnode != nullptr) node_list.push_back(tnode);
  714. }
  715. }// for(const CAMFImporter_NodeElement* root_child: root_el->Child)
  716. // And finally read rest of nodes.
  717. //
  718. for(const CAMFImporter_NodeElement* root_child: root_el->Child)
  719. {
  720. // 4. <constellation>
  721. if(root_child->Type == CAMFImporter_NodeElement::ENET_Constellation)
  722. {
  723. // <object> and <constellation> at top of self abstraction use aiNode. So we can use only aiNode list for creating new aiNode's.
  724. Postprocess_BuildConstellation(*((CAMFImporter_NodeElement_Constellation*)root_child), node_list);
  725. }
  726. // 5, <metadata>
  727. if(root_child->Type == CAMFImporter_NodeElement::ENET_Metadata) meta_list.push_back((CAMFImporter_NodeElement_Metadata*)root_child);
  728. }// for(const CAMFImporter_NodeElement* root_child: root_el->Child)
  729. // at now we can add collected metadata to root node
  730. Postprocess_AddMetadata(meta_list, *pScene->mRootNode);
  731. //
  732. // Check constellation children
  733. //
  734. // As said in specification:
  735. // "When multiple objects and constellations are defined in a single file, only the top level objects and constellations are available for printing."
  736. // What that means? For example: if some object is used in constellation then you must show only constellation but not original object.
  737. // And at this step we are checking that relations.
  738. nl_clean_loop:
  739. if(node_list.size() > 1)
  740. {
  741. // walk thru all nodes
  742. for(std::list<aiNode*>::iterator nl_it = node_list.begin(); nl_it != node_list.end(); nl_it++)
  743. {
  744. // and try to find them in another top nodes.
  745. std::list<aiNode*>::const_iterator next_it = nl_it;
  746. next_it++;
  747. for(; next_it != node_list.end(); next_it++)
  748. {
  749. if((*next_it)->FindNode((*nl_it)->mName) != nullptr)
  750. {
  751. // if current top node(nl_it) found in another top node then erase it from node_list and restart search loop.
  752. node_list.erase(nl_it);
  753. goto nl_clean_loop;
  754. }
  755. }// for(; next_it != node_list.end(); next_it++)
  756. }// for(std::list<aiNode*>::const_iterator nl_it = node_list.begin(); nl_it != node_list.end(); nl_it++)
  757. }
  758. //
  759. // move created objects to aiScene
  760. //
  761. //
  762. // Nodes
  763. if(node_list.size() > 0)
  764. {
  765. std::list<aiNode*>::const_iterator nl_it = node_list.begin();
  766. pScene->mRootNode->mNumChildren = node_list.size();
  767. pScene->mRootNode->mChildren = new aiNode*[pScene->mRootNode->mNumChildren];
  768. for(size_t i = 0; i < pScene->mRootNode->mNumChildren; i++)
  769. {
  770. // Objects and constellation that must be showed placed at top of hierarchy in <amf> node. So all aiNode's in node_list must have
  771. // mRootNode only as parent.
  772. (*nl_it)->mParent = pScene->mRootNode;
  773. pScene->mRootNode->mChildren[i] = *nl_it++;
  774. }
  775. }// if(node_list.size() > 0)
  776. //
  777. // Meshes
  778. if(mesh_list.size() > 0)
  779. {
  780. std::list<aiMesh*>::const_iterator ml_it = mesh_list.begin();
  781. pScene->mNumMeshes = mesh_list.size();
  782. pScene->mMeshes = new aiMesh*[pScene->mNumMeshes];
  783. for(size_t i = 0; i < pScene->mNumMeshes; i++) pScene->mMeshes[i] = *ml_it++;
  784. }// if(mesh_list.size() > 0)
  785. //
  786. // Textures
  787. pScene->mNumTextures = mTexture_Converted.size();
  788. if(pScene->mNumTextures > 0)
  789. {
  790. size_t idx;
  791. idx = 0;
  792. pScene->mTextures = new aiTexture*[pScene->mNumTextures];
  793. for(const SPP_Texture& tex_convd: mTexture_Converted)
  794. {
  795. pScene->mTextures[idx] = new aiTexture;
  796. pScene->mTextures[idx]->mWidth = tex_convd.Width;
  797. pScene->mTextures[idx]->mHeight = tex_convd.Height;
  798. pScene->mTextures[idx]->pcData = (aiTexel*)tex_convd.Data;
  799. // texture format description.
  800. strcpy(pScene->mTextures[idx]->achFormatHint, tex_convd.FormatHint);
  801. idx++;
  802. }// for(const SPP_Texture& tex_convd: mTexture_Converted)
  803. // Create materials for embedded textures.
  804. idx = 0;
  805. pScene->mNumMaterials = mTexture_Converted.size();
  806. pScene->mMaterials = new aiMaterial*[pScene->mNumMaterials];
  807. for(const SPP_Texture& tex_convd: mTexture_Converted)
  808. {
  809. const aiString texture_id(AI_EMBEDDED_TEXNAME_PREFIX + std::to_string(idx));
  810. const int mode = aiTextureOp_Multiply;
  811. const int repeat = tex_convd.Tiled ? 1 : 0;
  812. pScene->mMaterials[idx] = new aiMaterial;
  813. pScene->mMaterials[idx]->AddProperty(&texture_id, AI_MATKEY_TEXTURE_DIFFUSE(0));
  814. pScene->mMaterials[idx]->AddProperty(&mode, 1, AI_MATKEY_TEXOP_DIFFUSE(0));
  815. pScene->mMaterials[idx]->AddProperty(&repeat, 1, AI_MATKEY_MAPPINGMODE_U_DIFFUSE(0));
  816. pScene->mMaterials[idx]->AddProperty(&repeat, 1, AI_MATKEY_MAPPINGMODE_V_DIFFUSE(0));
  817. idx++;
  818. }
  819. }// if(pScene->mNumTextures > 0)
  820. }// END: after that walk thru children of root and collect data
  821. }// namespace Assimp
  822. #endif // !ASSIMP_BUILD_NO_AMF_IMPORTER