M3DExporter.cpp 16 KB

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