M3DExporter.cpp 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412
  1. /*
  2. Open Asset Import Library (assimp)
  3. ----------------------------------------------------------------------
  4. Copyright (c) 2006-2019, assimp team
  5. Copyright (c) 2019 bzt
  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
  9. following 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. #ifndef ASSIMP_BUILD_NO_EXPORT
  35. #ifndef ASSIMP_BUILD_NO_M3D_EXPORTER
  36. #define M3D_IMPLEMENTATION
  37. #define M3D_NOIMPORTER
  38. #define M3D_EXPORTER
  39. #define M3D_ASCII
  40. #ifndef ASSIMP_BUILD_NO_M3D_IMPORTER
  41. #define M3D_NODUP
  42. #endif
  43. // Header files, standard library.
  44. #include <memory> // shared_ptr
  45. #include <string>
  46. #include <vector>
  47. #include <assimp/Exceptional.h> // DeadlyExportError
  48. #include <assimp/StreamWriter.h> // StreamWriterLE
  49. #include <assimp/material.h> // aiTextureType
  50. #include <assimp/mesh.h>
  51. #include <assimp/scene.h>
  52. #include <assimp/version.h> // aiGetVersion
  53. #include <assimp/DefaultLogger.hpp>
  54. #include <assimp/Exporter.hpp>
  55. #include <assimp/IOSystem.hpp>
  56. #include "M3DExporter.h"
  57. #include "M3DMaterials.h"
  58. #include "M3DWrapper.h"
  59. // RESOURCES:
  60. // https://gitlab.com/bztsrc/model3d/blob/master/docs/m3d_format.md
  61. // https://gitlab.com/bztsrc/model3d/blob/master/docs/a3d_format.md
  62. /*
  63. * Currently supports static meshes, vertex colors, materials, textures
  64. *
  65. * For animation, it would require the following conversions:
  66. * - aiNode (bones) -> m3d_t.bone (with parent id, position vector and oriantation quaternion)
  67. * - aiMesh.aiBone -> m3d_t.skin (per vertex, with bone id, weight pairs)
  68. * - aiAnimation -> m3d_action (frame with timestamp and list of bone id, position, orientation
  69. * triplets, instead of per bone timestamp + lists)
  70. */
  71. // ------------------------------------------------------------------------------------------------
  72. // Conversion functions
  73. // ------------------------------------------------------------------------------------------------
  74. // helper to add a vertex (private to NodeWalk)
  75. m3dv_t *AddVrtx(m3dv_t *vrtx, uint32_t *numvrtx, m3dv_t *v, uint32_t *idx) {
  76. if (v->x == (M3D_FLOAT)-0.0) v->x = (M3D_FLOAT)0.0;
  77. if (v->y == (M3D_FLOAT)-0.0) v->y = (M3D_FLOAT)0.0;
  78. if (v->z == (M3D_FLOAT)-0.0) v->z = (M3D_FLOAT)0.0;
  79. if (v->w == (M3D_FLOAT)-0.0) v->w = (M3D_FLOAT)0.0;
  80. vrtx = (m3dv_t *)M3D_REALLOC(vrtx, ((*numvrtx) + 1) * sizeof(m3dv_t));
  81. memcpy(&vrtx[*numvrtx], v, sizeof(m3dv_t));
  82. *idx = *numvrtx;
  83. (*numvrtx)++;
  84. return vrtx;
  85. }
  86. // ------------------------------------------------------------------------------------------------
  87. // helper to add a tmap (private to NodeWalk)
  88. m3dti_t *AddTmap(m3dti_t *tmap, uint32_t *numtmap, m3dti_t *ti, uint32_t *idx) {
  89. tmap = (m3dti_t *)M3D_REALLOC(tmap, ((*numtmap) + 1) * sizeof(m3dti_t));
  90. memcpy(&tmap[*numtmap], ti, sizeof(m3dti_t));
  91. *idx = *numtmap;
  92. (*numtmap)++;
  93. return tmap;
  94. }
  95. // ------------------------------------------------------------------------------------------------
  96. // convert aiColor4D into uint32_t
  97. uint32_t mkColor(aiColor4D *c) {
  98. return ((uint8_t)(c->a * 255) << 24L) |
  99. ((uint8_t)(c->b * 255) << 16L) |
  100. ((uint8_t)(c->g * 255) << 8L) |
  101. ((uint8_t)(c->r * 255) << 0L);
  102. }
  103. // ------------------------------------------------------------------------------------------------
  104. // add a material property to the output
  105. void addProp(m3dm_t *m, uint8_t type, uint32_t value) {
  106. unsigned int i;
  107. i = m->numprop++;
  108. m->prop = (m3dp_t *)M3D_REALLOC(m->prop, m->numprop * sizeof(m3dp_t));
  109. if (!m->prop) {
  110. throw DeadlyExportError("memory allocation error");
  111. }
  112. m->prop[i].type = type;
  113. m->prop[i].value.num = value;
  114. }
  115. // ------------------------------------------------------------------------------------------------
  116. // add a material to the output
  117. M3D_INDEX addMaterial(const Assimp::M3DWrapper &m3d, const aiMaterial *mat) {
  118. unsigned int mi = -1U;
  119. aiColor4D c;
  120. aiString name;
  121. ai_real f;
  122. char *fn;
  123. if (mat && mat->Get(AI_MATKEY_NAME, name) == AI_SUCCESS && name.length &&
  124. strcmp((char *)&name.data, AI_DEFAULT_MATERIAL_NAME)) {
  125. // check if we have saved a material by this name. This has to be done
  126. // because only the referenced materials should be added to the output
  127. for (unsigned int i = 0; i < m3d->nummaterial; i++)
  128. if (!strcmp((char *)&name.data, m3d->material[i].name)) {
  129. mi = i;
  130. break;
  131. }
  132. // if not found, add the material to the output
  133. if (mi == -1U) {
  134. unsigned int k;
  135. mi = m3d->nummaterial++;
  136. m3d->material = (m3dm_t *)M3D_REALLOC(m3d->material, m3d->nummaterial * sizeof(m3dm_t));
  137. if (!m3d->material) {
  138. throw DeadlyExportError("memory allocation error");
  139. }
  140. m3d->material[mi].name = _m3d_safestr((char *)&name.data, 0);
  141. m3d->material[mi].numprop = 0;
  142. m3d->material[mi].prop = NULL;
  143. // iterate through the material property table and see what we got
  144. for (k = 0; k < 15; k++) {
  145. unsigned int j;
  146. if (m3d_propertytypes[k].format == m3dpf_map)
  147. continue;
  148. if (aiProps[k].pKey) {
  149. switch (m3d_propertytypes[k].format) {
  150. case m3dpf_color:
  151. if (mat->Get(aiProps[k].pKey, aiProps[k].type,
  152. aiProps[k].index, c) == AI_SUCCESS)
  153. addProp(&m3d->material[mi],
  154. m3d_propertytypes[k].id, mkColor(&c));
  155. break;
  156. case m3dpf_float:
  157. if (mat->Get(aiProps[k].pKey, aiProps[k].type,
  158. aiProps[k].index, f) == AI_SUCCESS)
  159. addProp(&m3d->material[mi],
  160. m3d_propertytypes[k].id,
  161. /* not (uint32_t)f, because we don't want to convert
  162. * it, we want to see it as 32 bits of memory */
  163. *((uint32_t *)&f));
  164. break;
  165. case m3dpf_uint8:
  166. if (mat->Get(aiProps[k].pKey, aiProps[k].type,
  167. aiProps[k].index, j) == AI_SUCCESS) {
  168. // special conversion for illumination model property
  169. if (m3d_propertytypes[k].id == m3dp_il) {
  170. switch (j) {
  171. case aiShadingMode_NoShading: j = 0; break;
  172. case aiShadingMode_Phong: j = 2; break;
  173. default: j = 1; break;
  174. }
  175. }
  176. addProp(&m3d->material[mi],
  177. m3d_propertytypes[k].id, j);
  178. }
  179. break;
  180. default:
  181. if (mat->Get(aiProps[k].pKey, aiProps[k].type,
  182. aiProps[k].index, j) == AI_SUCCESS)
  183. addProp(&m3d->material[mi],
  184. m3d_propertytypes[k].id, j);
  185. break;
  186. }
  187. }
  188. if (aiTxProps[k].pKey &&
  189. mat->GetTexture((aiTextureType)aiTxProps[k].type,
  190. aiTxProps[k].index, &name, NULL, NULL, NULL,
  191. NULL, NULL) == AI_SUCCESS) {
  192. unsigned int i;
  193. for (j = name.length - 1; j > 0 && name.data[j] != '.'; j++)
  194. ;
  195. if (j && name.data[j] == '.' &&
  196. (name.data[j + 1] == 'p' || name.data[j + 1] == 'P') &&
  197. (name.data[j + 1] == 'n' || name.data[j + 1] == 'N') &&
  198. (name.data[j + 1] == 'g' || name.data[j + 1] == 'G'))
  199. name.data[j] = 0;
  200. // do we have this texture saved already?
  201. fn = _m3d_safestr((char *)&name.data, 0);
  202. for (j = 0, i = -1U; j < m3d->numtexture; j++)
  203. if (!strcmp(fn, m3d->texture[j].name)) {
  204. i = j;
  205. free(fn);
  206. break;
  207. }
  208. if (i == -1U) {
  209. i = m3d->numtexture++;
  210. m3d->texture = (m3dtx_t *)M3D_REALLOC(
  211. m3d->texture,
  212. m3d->numtexture * sizeof(m3dtx_t));
  213. if (!m3d->texture) {
  214. throw DeadlyExportError("memory allocation error");
  215. }
  216. // we don't need the texture itself, only its name
  217. m3d->texture[i].name = fn;
  218. m3d->texture[i].w = 0;
  219. m3d->texture[i].h = 0;
  220. m3d->texture[i].d = NULL;
  221. }
  222. addProp(&m3d->material[mi],
  223. m3d_propertytypes[k].id + 128, i);
  224. }
  225. }
  226. }
  227. }
  228. return mi;
  229. }
  230. namespace Assimp {
  231. // ---------------------------------------------------------------------
  232. // Worker function for exporting a scene to binary M3D.
  233. // Prototyped and registered in Exporter.cpp
  234. void ExportSceneM3D(
  235. const char *pFile,
  236. IOSystem *pIOSystem,
  237. const aiScene *pScene,
  238. const ExportProperties *pProperties) {
  239. // initialize the exporter
  240. M3DExporter exporter(pScene, pProperties);
  241. // perform binary export
  242. exporter.doExport(pFile, pIOSystem, false);
  243. }
  244. // ---------------------------------------------------------------------
  245. // Worker function for exporting a scene to ASCII A3D.
  246. // Prototyped and registered in Exporter.cpp
  247. void ExportSceneA3D(
  248. const char *pFile,
  249. IOSystem *pIOSystem,
  250. const aiScene *pScene,
  251. const ExportProperties *pProperties
  252. ) {
  253. // initialize the exporter
  254. M3DExporter exporter(pScene, pProperties);
  255. // perform ascii export
  256. exporter.doExport(pFile, pIOSystem, true);
  257. }
  258. // ------------------------------------------------------------------------------------------------
  259. M3DExporter::M3DExporter(const aiScene *pScene, const ExportProperties *pProperties) :
  260. mScene(pScene),
  261. mProperties(pProperties),
  262. outfile() {}
  263. // ------------------------------------------------------------------------------------------------
  264. void M3DExporter::doExport(
  265. const char *pFile,
  266. IOSystem *pIOSystem,
  267. bool toAscii) {
  268. // TODO: convert mProperties into M3D_EXP_* flags
  269. (void)mProperties;
  270. // open the indicated file for writing (in binary / ASCII mode)
  271. outfile.reset(pIOSystem->Open(pFile, toAscii ? "wt" : "wb"));
  272. if (!outfile) {
  273. throw DeadlyExportError("could not open output .m3d file: " + std::string(pFile));
  274. }
  275. M3DWrapper m3d;
  276. if (!m3d) {
  277. throw DeadlyExportError("memory allocation error");
  278. }
  279. m3d->name = _m3d_safestr((char *)&mScene->mRootNode->mName.data, 2);
  280. // Create a model from assimp structures
  281. aiMatrix4x4 m;
  282. NodeWalk(m3d, mScene->mRootNode, m);
  283. // serialize the structures
  284. unsigned int size;
  285. unsigned char *output = m3d.Save(M3D_EXP_FLOAT, M3D_EXP_EXTRA | (toAscii ? M3D_EXP_ASCII : 0), size);
  286. if (!output || size < 8) {
  287. throw DeadlyExportError("unable to serialize into Model 3D");
  288. }
  289. // Write out serialized model
  290. outfile->Write(output, size, 1);
  291. // explicitly release file pointer,
  292. // so we don't have to rely on class destruction.
  293. outfile.reset();
  294. }
  295. // ------------------------------------------------------------------------------------------------
  296. // recursive node walker
  297. void M3DExporter::NodeWalk(const M3DWrapper &m3d, const aiNode *pNode, aiMatrix4x4 m) {
  298. aiMatrix4x4 nm = m * pNode->mTransformation;
  299. for (unsigned int i = 0; i < pNode->mNumMeshes; i++) {
  300. const aiMesh *mesh = mScene->mMeshes[pNode->mMeshes[i]];
  301. unsigned int mi = (M3D_INDEX)-1U;
  302. if (mScene->mMaterials) {
  303. // get the material for this mesh
  304. mi = addMaterial(m3d, mScene->mMaterials[mesh->mMaterialIndex]);
  305. }
  306. // iterate through the mesh faces
  307. for (unsigned int j = 0; j < mesh->mNumFaces; j++) {
  308. unsigned int n;
  309. const aiFace *face = &(mesh->mFaces[j]);
  310. // only triangle meshes supported for now
  311. if (face->mNumIndices != 3) {
  312. throw DeadlyExportError("use aiProcess_Triangulate before export");
  313. }
  314. // add triangle to the output
  315. n = m3d->numface++;
  316. m3d->face = (m3df_t *)M3D_REALLOC(m3d->face,
  317. m3d->numface * sizeof(m3df_t));
  318. if (!m3d->face) {
  319. throw DeadlyExportError("memory allocation error");
  320. }
  321. /* set all index to -1 by default */
  322. m3d->face[n].vertex[0] = m3d->face[n].vertex[1] = m3d->face[n].vertex[2] =
  323. m3d->face[n].normal[0] = m3d->face[n].normal[1] = m3d->face[n].normal[2] =
  324. m3d->face[n].texcoord[0] = m3d->face[n].texcoord[1] = m3d->face[n].texcoord[2] = -1U;
  325. m3d->face[n].materialid = mi;
  326. for (unsigned int k = 0; k < face->mNumIndices; k++) {
  327. // get the vertex's index
  328. unsigned int l = face->mIndices[k];
  329. unsigned int idx;
  330. m3dv_t vertex;
  331. m3dti_t ti;
  332. // multiply the position vector by the transformation matrix
  333. aiVector3D v = mesh->mVertices[l];
  334. v *= nm;
  335. vertex.x = v.x;
  336. vertex.y = v.y;
  337. vertex.z = v.z;
  338. vertex.w = 1.0;
  339. vertex.color = 0;
  340. vertex.skinid = -1U;
  341. // add color if defined
  342. if (mesh->HasVertexColors(0))
  343. vertex.color = mkColor(&mesh->mColors[0][l]);
  344. // save the vertex to the output
  345. m3d->vertex = AddVrtx(m3d->vertex, &m3d->numvertex,
  346. &vertex, &idx);
  347. m3d->face[n].vertex[k] = (M3D_INDEX)idx;
  348. // do we have texture coordinates?
  349. if (mesh->HasTextureCoords(0)) {
  350. ti.u = mesh->mTextureCoords[0][l].x;
  351. ti.v = mesh->mTextureCoords[0][l].y;
  352. m3d->tmap = AddTmap(m3d->tmap, &m3d->numtmap, &ti, &idx);
  353. m3d->face[n].texcoord[k] = (M3D_INDEX)idx;
  354. }
  355. // do we have normal vectors?
  356. if (mesh->HasNormals()) {
  357. vertex.x = mesh->mNormals[l].x;
  358. vertex.y = mesh->mNormals[l].y;
  359. vertex.z = mesh->mNormals[l].z;
  360. vertex.color = 0;
  361. m3d->vertex = AddVrtx(m3d->vertex, &m3d->numvertex, &vertex, &idx);
  362. m3d->face[n].normal[k] = (M3D_INDEX)idx;
  363. }
  364. }
  365. }
  366. }
  367. // repeat for the children nodes
  368. for (unsigned int i = 0; i < pNode->mNumChildren; i++) {
  369. NodeWalk(m3d, pNode->mChildren[i], nm);
  370. }
  371. }
  372. } // namespace Assimp
  373. #endif // ASSIMP_BUILD_NO_M3D_EXPORTER
  374. #endif // ASSIMP_BUILD_NO_EXPORT