M3DExporter.cpp 18 KB

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