M3DExporter.cpp 18 KB

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