AMFImporter_Postprocess.cpp 40 KB

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