glTFExporter.cpp 34 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899
  1. /*
  2. Open Asset Import Library (assimp)
  3. ----------------------------------------------------------------------
  4. Copyright (c) 2006-2016, assimp team
  5. All rights reserved.
  6. Redistribution and use of this software in source and binary forms,
  7. with or without modification, are permitted provided that the
  8. following conditions are met:
  9. * Redistributions of source code must retain the above
  10. copyright notice, this list of conditions and the
  11. following disclaimer.
  12. * Redistributions in binary form must reproduce the above
  13. copyright notice, this list of conditions and the
  14. following disclaimer in the documentation and/or other
  15. materials provided with the distribution.
  16. * Neither the name of the assimp team, nor the names of its
  17. contributors may be used to endorse or promote products
  18. derived from this software without specific prior
  19. written permission of the assimp team.
  20. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
  21. "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
  22. LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
  23. A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
  24. OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
  25. SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
  26. LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
  27. DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
  28. THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
  29. (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
  30. OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
  31. ----------------------------------------------------------------------
  32. */
  33. #ifndef ASSIMP_BUILD_NO_EXPORT
  34. #ifndef ASSIMP_BUILD_NO_GLTF_EXPORTER
  35. #include "glTFExporter.h"
  36. #include "Exceptional.h"
  37. #include "StringComparison.h"
  38. #include "ByteSwapper.h"
  39. #include "SplitLargeMeshes.h"
  40. #include "SceneCombiner.h"
  41. #include <assimp/version.h>
  42. #include <assimp/IOSystem.hpp>
  43. #include <assimp/Exporter.hpp>
  44. #include <assimp/material.h>
  45. #include <assimp/scene.h>
  46. // Header files, standart library.
  47. #include <memory>
  48. #include <inttypes.h>
  49. #include "glTFAssetWriter.h"
  50. #ifdef ASSIMP_IMPORTER_GLTF_USE_OPEN3DGC
  51. // Header files, Open3DGC.
  52. # include <Open3DGC/o3dgcSC3DMCEncoder.h>
  53. #endif
  54. using namespace rapidjson;
  55. using namespace Assimp;
  56. using namespace glTF;
  57. namespace Assimp {
  58. // ------------------------------------------------------------------------------------------------
  59. // Worker function for exporting a scene to GLTF. Prototyped and registered in Exporter.cpp
  60. void ExportSceneGLTF(const char* pFile, IOSystem* pIOSystem, const aiScene* pScene, const ExportProperties* pProperties)
  61. {
  62. // invoke the exporter
  63. glTFExporter exporter(pFile, pIOSystem, pScene, pProperties, false);
  64. }
  65. // ------------------------------------------------------------------------------------------------
  66. // Worker function for exporting a scene to GLB. Prototyped and registered in Exporter.cpp
  67. void ExportSceneGLB(const char* pFile, IOSystem* pIOSystem, const aiScene* pScene, const ExportProperties* pProperties)
  68. {
  69. // invoke the exporter
  70. glTFExporter exporter(pFile, pIOSystem, pScene, pProperties, true);
  71. }
  72. } // end of namespace Assimp
  73. glTFExporter::glTFExporter(const char* filename, IOSystem* pIOSystem, const aiScene* pScene,
  74. const ExportProperties* pProperties, bool isBinary)
  75. : mFilename(filename)
  76. , mIOSystem(pIOSystem)
  77. , mProperties(pProperties)
  78. {
  79. aiScene* sceneCopy_tmp;
  80. SceneCombiner::CopyScene(&sceneCopy_tmp, pScene);
  81. std::unique_ptr<aiScene> sceneCopy(sceneCopy_tmp);
  82. SplitLargeMeshesProcess_Triangle tri_splitter;
  83. tri_splitter.SetLimit(0xffff);
  84. tri_splitter.Execute(sceneCopy.get());
  85. SplitLargeMeshesProcess_Vertex vert_splitter;
  86. vert_splitter.SetLimit(0xffff);
  87. vert_splitter.Execute(sceneCopy.get());
  88. mScene = sceneCopy.get();
  89. std::unique_ptr<Asset> asset();
  90. mAsset.reset( new glTF::Asset( pIOSystem ) );
  91. if (isBinary) {
  92. mAsset->SetAsBinary();
  93. }
  94. ExportMetadata();
  95. //for (unsigned int i = 0; i < pScene->mNumCameras; ++i) {}
  96. //for (unsigned int i = 0; i < pScene->mNumLights; ++i) {}
  97. ExportMaterials();
  98. if (mScene->mRootNode) {
  99. ExportNode(mScene->mRootNode);
  100. }
  101. ExportMeshes();
  102. //for (unsigned int i = 0; i < pScene->mNumTextures; ++i) {}
  103. ExportScene();
  104. ExportAnimations();
  105. glTF::AssetWriter writer(*mAsset);
  106. if (isBinary) {
  107. writer.WriteGLBFile(filename);
  108. } else {
  109. writer.WriteFile(filename);
  110. }
  111. }
  112. /*
  113. * Copy a 4x4 matrix from struct aiMatrix to typedef mat4.
  114. * Also converts from row-major to column-major storage.
  115. */
  116. static void CopyValue(const aiMatrix4x4& v, glTF::mat4& o)
  117. {
  118. o[ 0] = v.a1; o[ 1] = v.b1; o[ 2] = v.c1; o[ 3] = v.d1;
  119. o[ 4] = v.a2; o[ 5] = v.b2; o[ 6] = v.c2; o[ 7] = v.d2;
  120. o[ 8] = v.a3; o[ 9] = v.b3; o[10] = v.c3; o[11] = v.d3;
  121. o[12] = v.a4; o[13] = v.b4; o[14] = v.c4; o[15] = v.d4;
  122. }
  123. static void IdentityMatrix4(glTF::mat4& o)
  124. {
  125. o[ 0] = 1; o[ 1] = 0; o[ 2] = 0; o[ 3] = 0;
  126. o[ 4] = 0; o[ 5] = 1; o[ 6] = 0; o[ 7] = 0;
  127. o[ 8] = 0; o[ 9] = 0; o[10] = 1; o[11] = 0;
  128. o[12] = 0; o[13] = 0; o[14] = 0; o[15] = 1;
  129. }
  130. inline Ref<Accessor> ExportData(Asset& a, std::string& meshName, Ref<Buffer>& buffer,
  131. unsigned int count, void* data, AttribType::Value typeIn, AttribType::Value typeOut, ComponentType compType, bool isIndices = false)
  132. {
  133. if (!count || !data) return Ref<Accessor>();
  134. unsigned int numCompsIn = AttribType::GetNumComponents(typeIn);
  135. unsigned int numCompsOut = AttribType::GetNumComponents(typeOut);
  136. unsigned int bytesPerComp = ComponentTypeSize(compType);
  137. size_t offset = buffer->byteLength;
  138. size_t length = count * numCompsOut * bytesPerComp;
  139. buffer->Grow(length);
  140. // bufferView
  141. Ref<BufferView> bv = a.bufferViews.Create(a.FindUniqueID(meshName, "view"));
  142. bv->buffer = buffer;
  143. bv->byteOffset = unsigned(offset);
  144. bv->byteLength = length; //! The target that the WebGL buffer should be bound to.
  145. bv->target = isIndices ? BufferViewTarget_ELEMENT_ARRAY_BUFFER : BufferViewTarget_ARRAY_BUFFER;
  146. // accessor
  147. Ref<Accessor> acc = a.accessors.Create(a.FindUniqueID(meshName, "accessor"));
  148. acc->bufferView = bv;
  149. acc->byteOffset = 0;
  150. acc->byteStride = 0;
  151. acc->componentType = compType;
  152. acc->count = count;
  153. acc->type = typeOut;
  154. // calculate min and max values
  155. {
  156. // Allocate and initialize with large values.
  157. float float_MAX = 10000000000000;
  158. for (int i = 0 ; i < numCompsOut ; i++) {
  159. acc->min.push_back( float_MAX);
  160. acc->max.push_back(-float_MAX);
  161. }
  162. // Search and set extreme values.
  163. float valueTmp;
  164. for (int i = 0 ; i < count ; i++) {
  165. for (int j = 0 ; j < numCompsOut ; j++) {
  166. if (numCompsOut == 1) {
  167. valueTmp = static_cast<unsigned short*>(data)[i];
  168. } else {
  169. valueTmp = static_cast<aiVector3D*>(data)[i][j];
  170. }
  171. if (valueTmp < acc->min[j]) {
  172. acc->min[j] = valueTmp;
  173. }
  174. if (valueTmp > acc->max[j]) {
  175. acc->max[j] = valueTmp;
  176. }
  177. }
  178. }
  179. }
  180. // copy the data
  181. acc->WriteData(count, data, numCompsIn*bytesPerComp);
  182. return acc;
  183. }
  184. namespace {
  185. void GetMatScalar(const aiMaterial* mat, float& val, const char* propName, int type, int idx) {
  186. if (mat->Get(propName, type, idx, val) == AI_SUCCESS) {}
  187. }
  188. }
  189. void glTFExporter::GetTexSampler(const aiMaterial* mat, glTF::TexProperty& prop)
  190. {
  191. std::string samplerId = mAsset->FindUniqueID("", "sampler");
  192. prop.texture->sampler = mAsset->samplers.Create(samplerId);
  193. aiTextureMapMode mapU, mapV;
  194. aiGetMaterialInteger(mat,AI_MATKEY_MAPPINGMODE_U_DIFFUSE(0),(int*)&mapU);
  195. aiGetMaterialInteger(mat,AI_MATKEY_MAPPINGMODE_V_DIFFUSE(0),(int*)&mapV);
  196. switch (mapU) {
  197. case aiTextureMapMode_Wrap:
  198. prop.texture->sampler->wrapS = SamplerWrap_Repeat;
  199. break;
  200. case aiTextureMapMode_Clamp:
  201. prop.texture->sampler->wrapS = SamplerWrap_Clamp_To_Edge;
  202. break;
  203. case aiTextureMapMode_Mirror:
  204. prop.texture->sampler->wrapS = SamplerWrap_Mirrored_Repeat;
  205. break;
  206. case aiTextureMapMode_Decal:
  207. default:
  208. prop.texture->sampler->wrapS = SamplerWrap_Repeat;
  209. break;
  210. };
  211. switch (mapV) {
  212. case aiTextureMapMode_Wrap:
  213. prop.texture->sampler->wrapT = SamplerWrap_Repeat;
  214. break;
  215. case aiTextureMapMode_Clamp:
  216. prop.texture->sampler->wrapT = SamplerWrap_Clamp_To_Edge;
  217. break;
  218. case aiTextureMapMode_Mirror:
  219. prop.texture->sampler->wrapT = SamplerWrap_Mirrored_Repeat;
  220. break;
  221. case aiTextureMapMode_Decal:
  222. default:
  223. prop.texture->sampler->wrapT = SamplerWrap_Repeat;
  224. break;
  225. };
  226. // Hard coded Texture filtering options because I do not know where to find them in the aiMaterial.
  227. prop.texture->sampler->magFilter = SamplerMagFilter_Linear;
  228. prop.texture->sampler->minFilter = SamplerMinFilter_Linear;
  229. }
  230. void glTFExporter::GetMatColorOrTex(const aiMaterial* mat, glTF::TexProperty& prop, const char* propName, int type, int idx, aiTextureType tt)
  231. {
  232. aiString tex;
  233. aiColor4D col;
  234. if (mat->GetTextureCount(tt) > 0) {
  235. if (mat->Get(AI_MATKEY_TEXTURE(tt, 0), tex) == AI_SUCCESS) {
  236. std::string path = tex.C_Str();
  237. if (path.size() > 0) {
  238. if (path[0] != '*') {
  239. std::map<std::string, unsigned int>::iterator it = mTexturesByPath.find(path);
  240. if (it != mTexturesByPath.end()) {
  241. prop.texture = mAsset->textures.Get(it->second);
  242. }
  243. }
  244. if (!prop.texture) {
  245. std::string texId = mAsset->FindUniqueID("", "texture");
  246. prop.texture = mAsset->textures.Create(texId);
  247. mTexturesByPath[path] = prop.texture.GetIndex();
  248. std::string imgId = mAsset->FindUniqueID("", "image");
  249. prop.texture->source = mAsset->images.Create(imgId);
  250. if (path[0] == '*') { // embedded
  251. aiTexture* tex = mScene->mTextures[atoi(&path[1])];
  252. uint8_t* data = reinterpret_cast<uint8_t*>(tex->pcData);
  253. prop.texture->source->SetData(data, tex->mWidth, *mAsset);
  254. if (tex->achFormatHint[0]) {
  255. std::string mimeType = "image/";
  256. mimeType += (memcmp(tex->achFormatHint, "jpg", 3) == 0) ? "jpeg" : tex->achFormatHint;
  257. prop.texture->source->mimeType = mimeType;
  258. }
  259. }
  260. else {
  261. prop.texture->source->uri = path;
  262. }
  263. GetTexSampler(mat, prop);
  264. }
  265. }
  266. }
  267. }
  268. if (mat->Get(propName, type, idx, col) == AI_SUCCESS) {
  269. prop.color[0] = col.r; prop.color[1] = col.g; prop.color[2] = col.b; prop.color[3] = col.a;
  270. }
  271. }
  272. void glTFExporter::ExportMaterials()
  273. {
  274. aiString aiName;
  275. for (unsigned int i = 0; i < mScene->mNumMaterials; ++i) {
  276. const aiMaterial* mat = mScene->mMaterials[i];
  277. std::string name;
  278. if (mat->Get(AI_MATKEY_NAME, aiName) == AI_SUCCESS) {
  279. name = aiName.C_Str();
  280. }
  281. name = mAsset->FindUniqueID(name, "material");
  282. Ref<Material> m = mAsset->materials.Create(name);
  283. GetMatColorOrTex(mat, m->ambient, AI_MATKEY_COLOR_AMBIENT, aiTextureType_AMBIENT);
  284. GetMatColorOrTex(mat, m->diffuse, AI_MATKEY_COLOR_DIFFUSE, aiTextureType_DIFFUSE);
  285. GetMatColorOrTex(mat, m->specular, AI_MATKEY_COLOR_SPECULAR, aiTextureType_SPECULAR);
  286. GetMatColorOrTex(mat, m->emission, AI_MATKEY_COLOR_EMISSIVE, aiTextureType_EMISSIVE);
  287. m->transparent = mat->Get(AI_MATKEY_OPACITY, m->transparency) == aiReturn_SUCCESS && m->transparency != 1.0;
  288. GetMatScalar(mat, m->shininess, AI_MATKEY_SHININESS);
  289. }
  290. }
  291. /*
  292. * Search through node hierarchy and find the node containing the given meshID.
  293. * Returns true on success, and false otherwise.
  294. */
  295. bool FindMeshNode(Ref<Node>& nodeIn, Ref<Node>& meshNode, std::string meshID)
  296. {
  297. for (unsigned int i = 0; i < nodeIn->meshes.size(); ++i) {
  298. if (meshID.compare(nodeIn->meshes[i]->id) == 0) {
  299. meshNode = nodeIn;
  300. return true;
  301. }
  302. }
  303. for (unsigned int i = 0; i < nodeIn->children.size(); ++i) {
  304. if(FindMeshNode(nodeIn->children[i], meshNode, meshID)) {
  305. return true;
  306. }
  307. }
  308. return false;
  309. }
  310. /*
  311. * Find the root joint of the skeleton.
  312. */
  313. Ref<Node> FindSkeletonRootJoint(Ref<Skin>& skinRef)
  314. {
  315. Ref<Node> candidateNodeRef;
  316. Ref<Node> testNodeRef;
  317. for (unsigned int i = 0; i < skinRef->jointNames.size(); ++i) {
  318. candidateNodeRef = skinRef->jointNames[i];
  319. bool candidateIsRoot = true;
  320. for (unsigned int j = 0; j < skinRef->jointNames.size(); ++j) {
  321. if (i == j) continue;
  322. testNodeRef = skinRef->jointNames[j];
  323. for (unsigned int k = 0; k < testNodeRef->children.size(); ++k) {
  324. std::string childNodeRefID = testNodeRef->children[k]->id;
  325. if (childNodeRefID.compare(candidateNodeRef->id) == 0) {
  326. candidateIsRoot = false;
  327. }
  328. }
  329. }
  330. if(candidateIsRoot == true) {
  331. return candidateNodeRef;
  332. }
  333. }
  334. return candidateNodeRef;
  335. }
  336. void ExportSkin(Asset& mAsset, const aiMesh* aim, Ref<Mesh>& meshRef, Ref<Buffer>& bufferRef)
  337. {
  338. std::string skinName = aim->mName.C_Str();
  339. skinName = mAsset.FindUniqueID(skinName, "skin");
  340. Ref<Skin> skinRef = mAsset.skins.Create(skinName);
  341. skinRef->name = skinName;
  342. mat4* inverseBindMatricesData = new mat4[aim->mNumBones];
  343. // Store the vertex joint and weight data.
  344. vec4* vertexJointData = new vec4[aim->mNumVertices];
  345. vec4* vertexWeightData = new vec4[aim->mNumVertices];
  346. unsigned int* jointsPerVertex = new unsigned int[aim->mNumVertices];
  347. for (size_t i = 0; i < aim->mNumVertices; ++i) {
  348. jointsPerVertex[i] = 0;
  349. for (size_t j = 0; j < 4; ++j) {
  350. vertexJointData[i][j] = 0;
  351. vertexWeightData[i][j] = 0;
  352. }
  353. }
  354. for (unsigned int idx_bone = 0; idx_bone < aim->mNumBones; ++idx_bone) {
  355. const aiBone* aib = aim->mBones[idx_bone];
  356. // aib->mName =====> skinRef->jointNames
  357. // Find the node with id = mName.
  358. Ref<Node> nodeRef = mAsset.nodes.Get(aib->mName.C_Str());
  359. nodeRef->jointName = "joint_" + std::to_string(idx_bone);
  360. skinRef->jointNames.push_back(nodeRef);
  361. // Identity Matrix =====> skinRef->bindShapeMatrix
  362. // Temporary. Hard-coded identity matrix here
  363. skinRef->bindShapeMatrix.isPresent = true;
  364. IdentityMatrix4(skinRef->bindShapeMatrix.value);
  365. // aib->mOffsetMatrix =====> skinRef->inverseBindMatrices
  366. CopyValue(aib->mOffsetMatrix, inverseBindMatricesData[idx_bone]);
  367. // aib->mWeights =====> vertexWeightData
  368. for (unsigned int idx_weights = 0; idx_weights < aib->mNumWeights; ++idx_weights) {
  369. aiVertexWeight tmpVertWeight = aib->mWeights[idx_weights];
  370. vertexJointData[tmpVertWeight.mVertexId][jointsPerVertex[tmpVertWeight.mVertexId]] = idx_bone;
  371. vertexWeightData[tmpVertWeight.mVertexId][jointsPerVertex[tmpVertWeight.mVertexId]] = tmpVertWeight.mWeight;
  372. jointsPerVertex[tmpVertWeight.mVertexId] += 1;
  373. }
  374. } // End: for-loop mNumMeshes
  375. // Create the Accessor for skinRef->inverseBindMatrices
  376. Ref<Accessor> invBindMatrixAccessor = ExportData(mAsset, skinName, bufferRef, aim->mNumBones, inverseBindMatricesData, AttribType::MAT4, AttribType::MAT4, ComponentType_FLOAT);
  377. if (invBindMatrixAccessor) skinRef->inverseBindMatrices = invBindMatrixAccessor;
  378. Mesh::Primitive& p = meshRef->primitives.back();
  379. Ref<Accessor> vertexJointAccessor = ExportData(mAsset, skinName, bufferRef, aim->mNumVertices, vertexJointData, AttribType::VEC4, AttribType::VEC4, ComponentType_FLOAT);
  380. if (vertexJointAccessor) p.attributes.joint.push_back(vertexJointAccessor);
  381. Ref<Accessor> vertexWeightAccessor = ExportData(mAsset, skinName, bufferRef, aim->mNumVertices, vertexWeightData, AttribType::VEC4, AttribType::VEC4, ComponentType_FLOAT);
  382. if (vertexWeightAccessor) p.attributes.weight.push_back(vertexWeightAccessor);
  383. // Find node that contains this mesh and add "skeletons" and "skin" attributes to that node.
  384. Ref<Node> rootNode = mAsset.nodes.Get(unsigned(0));
  385. Ref<Node> meshNode;
  386. FindMeshNode(rootNode, meshNode, meshRef->id);
  387. Ref<Node> rootJoint = FindSkeletonRootJoint(skinRef);
  388. meshNode->skeletons.push_back(rootJoint);
  389. meshNode->skin = skinRef;
  390. }
  391. void glTFExporter::ExportMeshes()
  392. {
  393. // Not for
  394. // using IndicesType = decltype(aiFace::mNumIndices);
  395. // But yes for
  396. // using IndicesType = unsigned short;
  397. // because "ComponentType_UNSIGNED_SHORT" used for indices. And it's a maximal type according to glTF specification.
  398. typedef unsigned short IndicesType;
  399. // Variables needed for compression. BEGIN.
  400. // Indices, not pointers - because pointer to buffer is changing while writing to it.
  401. size_t idx_srcdata_begin;// Index of buffer before writing mesh data. Also, index of begin of coordinates array in buffer.
  402. size_t idx_srcdata_normal = SIZE_MAX;// Index of begin of normals array in buffer. SIZE_MAX - mean that mesh has no normals.
  403. std::vector<size_t> idx_srcdata_tc;// Array of indices. Every index point to begin of texture coordinates array in buffer.
  404. size_t idx_srcdata_ind;// Index of begin of coordinates indices array in buffer.
  405. bool comp_allow;// Point that data of current mesh can be compressed.
  406. // Variables needed for compression. END.
  407. std::string fname = std::string(mFilename);
  408. std::string bufferIdPrefix = fname.substr(0, fname.find("."));
  409. std::string bufferId = mAsset->FindUniqueID("", bufferIdPrefix.c_str());
  410. Ref<Buffer> b = mAsset->GetBodyBuffer();
  411. if (!b) {
  412. b = mAsset->buffers.Create(bufferId);
  413. }
  414. for (unsigned int idx_mesh = 0; idx_mesh < mScene->mNumMeshes; ++idx_mesh) {
  415. const aiMesh* aim = mScene->mMeshes[idx_mesh];
  416. // Check if compressing requested and mesh can be encoded.
  417. #ifdef ASSIMP_IMPORTER_GLTF_USE_OPEN3DGC
  418. comp_allow = mProperties->GetPropertyBool("extensions.Open3DGC.use", false);
  419. #else
  420. comp_allow = false;
  421. #endif
  422. if(comp_allow && (aim->mPrimitiveTypes == aiPrimitiveType_TRIANGLE) && (aim->mNumVertices > 0) && (aim->mNumFaces > 0))
  423. {
  424. idx_srcdata_tc.clear();
  425. idx_srcdata_tc.reserve(AI_MAX_NUMBER_OF_TEXTURECOORDS);
  426. }
  427. else
  428. {
  429. std::string msg;
  430. if(aim->mPrimitiveTypes != aiPrimitiveType_TRIANGLE)
  431. msg = "all primitives of the mesh must be a triangles.";
  432. else
  433. msg = "mesh must has vertices and faces.";
  434. DefaultLogger::get()->warn("GLTF: can not use Open3DGC-compression: " + msg);
  435. comp_allow = false;
  436. }
  437. std::string meshId = mAsset->FindUniqueID(aim->mName.C_Str(), "mesh");
  438. Ref<Mesh> m = mAsset->meshes.Create(meshId);
  439. m->primitives.resize(1);
  440. Mesh::Primitive& p = m->primitives.back();
  441. p.material = mAsset->materials.Get(aim->mMaterialIndex);
  442. /******************* Vertices ********************/
  443. // If compression is used then you need parameters of uncompressed region: begin and size. At this step "begin" is stored.
  444. if(comp_allow) idx_srcdata_begin = b->byteLength;
  445. Ref<Accessor> v = ExportData(*mAsset, meshId, b, aim->mNumVertices, aim->mVertices, AttribType::VEC3, AttribType::VEC3, ComponentType_FLOAT);
  446. if (v) p.attributes.position.push_back(v);
  447. /******************** Normals ********************/
  448. if(comp_allow && (aim->mNormals > 0)) idx_srcdata_normal = b->byteLength;// Store index of normals array.
  449. Ref<Accessor> n = ExportData(*mAsset, meshId, b, aim->mNumVertices, aim->mNormals, AttribType::VEC3, AttribType::VEC3, ComponentType_FLOAT);
  450. if (n) p.attributes.normal.push_back(n);
  451. /************** Texture coordinates **************/
  452. for (int i = 0; i < AI_MAX_NUMBER_OF_TEXTURECOORDS; ++i) {
  453. // Flip UV y coords
  454. if (aim -> mNumUVComponents[i] > 1) {
  455. for (unsigned int j = 0; j < aim->mNumVertices; ++j) {
  456. aim->mTextureCoords[i][j].y = 1 - aim->mTextureCoords[i][j].y;
  457. }
  458. }
  459. if (aim->mNumUVComponents[i] > 0) {
  460. AttribType::Value type = (aim->mNumUVComponents[i] == 2) ? AttribType::VEC2 : AttribType::VEC3;
  461. if(comp_allow) idx_srcdata_tc.push_back(b->byteLength);// Store index of texture coordinates array.
  462. Ref<Accessor> tc = ExportData(*mAsset, meshId, b, aim->mNumVertices, aim->mTextureCoords[i], AttribType::VEC3, type, ComponentType_FLOAT, false);
  463. if (tc) p.attributes.texcoord.push_back(tc);
  464. }
  465. }
  466. /*************** Vertices indices ****************/
  467. idx_srcdata_ind = b->byteLength;// Store index of indices array.
  468. if (aim->mNumFaces > 0) {
  469. std::vector<IndicesType> indices;
  470. unsigned int nIndicesPerFace = aim->mFaces[0].mNumIndices;
  471. indices.resize(aim->mNumFaces * nIndicesPerFace);
  472. for (size_t i = 0; i < aim->mNumFaces; ++i) {
  473. for (size_t j = 0; j < nIndicesPerFace; ++j) {
  474. indices[i*nIndicesPerFace + j] = uint16_t(aim->mFaces[i].mIndices[j]);
  475. }
  476. }
  477. p.indices = ExportData(*mAsset, meshId, b, unsigned(indices.size()), &indices[0], AttribType::SCALAR, AttribType::SCALAR, ComponentType_UNSIGNED_SHORT, true);
  478. }
  479. switch (aim->mPrimitiveTypes) {
  480. case aiPrimitiveType_POLYGON:
  481. p.mode = PrimitiveMode_TRIANGLES; break; // TODO implement this
  482. case aiPrimitiveType_LINE:
  483. p.mode = PrimitiveMode_LINES; break;
  484. case aiPrimitiveType_POINT:
  485. p.mode = PrimitiveMode_POINTS; break;
  486. default: // aiPrimitiveType_TRIANGLE
  487. p.mode = PrimitiveMode_TRIANGLES;
  488. }
  489. /*************** Skins ****************/
  490. if(aim->HasBones()) {
  491. ExportSkin(*mAsset, aim, m, b);
  492. }
  493. /****************** Compression ******************/
  494. ///TODO: animation: weights, joints.
  495. if(comp_allow)
  496. {
  497. #ifdef ASSIMP_IMPORTER_GLTF_USE_OPEN3DGC
  498. // Only one type of compression supported at now - Open3DGC.
  499. //
  500. o3dgc::BinaryStream bs;
  501. o3dgc::SC3DMCEncoder<IndicesType> encoder;
  502. o3dgc::IndexedFaceSet<IndicesType> comp_o3dgc_ifs;
  503. o3dgc::SC3DMCEncodeParams comp_o3dgc_params;
  504. //
  505. // Fill data for encoder.
  506. //
  507. // Quantization
  508. unsigned quant_coord = mProperties->GetPropertyInteger("extensions.Open3DGC.quantization.POSITION", 12);
  509. unsigned quant_normal = mProperties->GetPropertyInteger("extensions.Open3DGC.quantization.NORMAL", 10);
  510. unsigned quant_texcoord = mProperties->GetPropertyInteger("extensions.Open3DGC.quantization.TEXCOORD", 10);
  511. // Prediction
  512. o3dgc::O3DGCSC3DMCPredictionMode prediction_position = o3dgc::O3DGC_SC3DMC_PARALLELOGRAM_PREDICTION;
  513. o3dgc::O3DGCSC3DMCPredictionMode prediction_normal = o3dgc::O3DGC_SC3DMC_SURF_NORMALS_PREDICTION;
  514. o3dgc::O3DGCSC3DMCPredictionMode prediction_texcoord = o3dgc::O3DGC_SC3DMC_PARALLELOGRAM_PREDICTION;
  515. // IndexedFacesSet: "Crease angle", "solid", "convex" are set to default.
  516. comp_o3dgc_ifs.SetCCW(true);
  517. comp_o3dgc_ifs.SetIsTriangularMesh(true);
  518. comp_o3dgc_ifs.SetNumFloatAttributes(0);
  519. // Coordinates
  520. comp_o3dgc_params.SetCoordQuantBits(quant_coord);
  521. comp_o3dgc_params.SetCoordPredMode(prediction_position);
  522. comp_o3dgc_ifs.SetNCoord(aim->mNumVertices);
  523. comp_o3dgc_ifs.SetCoord((o3dgc::Real* const)&b->GetPointer()[idx_srcdata_begin]);
  524. // Normals
  525. if(idx_srcdata_normal != SIZE_MAX)
  526. {
  527. comp_o3dgc_params.SetNormalQuantBits(quant_normal);
  528. comp_o3dgc_params.SetNormalPredMode(prediction_normal);
  529. comp_o3dgc_ifs.SetNNormal(aim->mNumVertices);
  530. comp_o3dgc_ifs.SetNormal((o3dgc::Real* const)&b->GetPointer()[idx_srcdata_normal]);
  531. }
  532. // Texture coordinates
  533. for(size_t num_tc = 0; num_tc < idx_srcdata_tc.size(); num_tc++)
  534. {
  535. size_t num = comp_o3dgc_ifs.GetNumFloatAttributes();
  536. comp_o3dgc_params.SetFloatAttributeQuantBits(num, quant_texcoord);
  537. comp_o3dgc_params.SetFloatAttributePredMode(num, prediction_texcoord);
  538. comp_o3dgc_ifs.SetNFloatAttribute(num, aim->mNumVertices);// number of elements.
  539. comp_o3dgc_ifs.SetFloatAttributeDim(num, aim->mNumUVComponents[num_tc]);// components per element: aiVector3D => x * float
  540. comp_o3dgc_ifs.SetFloatAttributeType(num, o3dgc::O3DGC_IFS_FLOAT_ATTRIBUTE_TYPE_TEXCOORD);
  541. comp_o3dgc_ifs.SetFloatAttribute(num, (o3dgc::Real* const)&b->GetPointer()[idx_srcdata_tc[num_tc]]);
  542. comp_o3dgc_ifs.SetNumFloatAttributes(num + 1);
  543. }
  544. // Coordinates indices
  545. comp_o3dgc_ifs.SetNCoordIndex(aim->mNumFaces);
  546. comp_o3dgc_ifs.SetCoordIndex((IndicesType* const)&b->GetPointer()[idx_srcdata_ind]);
  547. // Prepare to enconding
  548. comp_o3dgc_params.SetNumFloatAttributes(comp_o3dgc_ifs.GetNumFloatAttributes());
  549. if(mProperties->GetPropertyBool("extensions.Open3DGC.binary", true))
  550. comp_o3dgc_params.SetStreamType(o3dgc::O3DGC_STREAM_TYPE_BINARY);
  551. else
  552. comp_o3dgc_params.SetStreamType(o3dgc::O3DGC_STREAM_TYPE_ASCII);
  553. comp_o3dgc_ifs.ComputeMinMax(o3dgc::O3DGC_SC3DMC_MAX_ALL_DIMS);
  554. //
  555. // Encoding
  556. //
  557. encoder.Encode(comp_o3dgc_params, comp_o3dgc_ifs, bs);
  558. // Replace data in buffer.
  559. b->ReplaceData(idx_srcdata_begin, b->byteLength - idx_srcdata_begin, bs.GetBuffer(), bs.GetSize());
  560. //
  561. // Add information about extension to mesh.
  562. //
  563. // Create extension structure.
  564. Mesh::SCompression_Open3DGC* ext = new Mesh::SCompression_Open3DGC;
  565. // Fill it.
  566. ext->Buffer = b->id;
  567. ext->Offset = idx_srcdata_begin;
  568. ext->Count = b->byteLength - idx_srcdata_begin;
  569. ext->Binary = mProperties->GetPropertyBool("extensions.Open3DGC.binary");
  570. ext->IndicesCount = comp_o3dgc_ifs.GetNCoordIndex() * 3;
  571. ext->VerticesCount = comp_o3dgc_ifs.GetNCoord();
  572. // And assign to mesh.
  573. m->Extension.push_back(ext);
  574. #endif
  575. }// if(comp_allow)
  576. }// for (unsigned int i = 0; i < mScene->mNumMeshes; ++i)
  577. }
  578. unsigned int glTFExporter::ExportNode(const aiNode* n)
  579. {
  580. Ref<Node> node = mAsset->nodes.Create(mAsset->FindUniqueID(n->mName.C_Str(), "node"));
  581. if (!n->mTransformation.IsIdentity()) {
  582. node->matrix.isPresent = true;
  583. CopyValue(n->mTransformation, node->matrix.value);
  584. }
  585. for (unsigned int i = 0; i < n->mNumMeshes; ++i) {
  586. node->meshes.push_back(mAsset->meshes.Get(n->mMeshes[i]));
  587. }
  588. for (unsigned int i = 0; i < n->mNumChildren; ++i) {
  589. unsigned int idx = ExportNode(n->mChildren[i]);
  590. node->children.push_back(mAsset->nodes.Get(idx));
  591. }
  592. return node.GetIndex();
  593. }
  594. void glTFExporter::ExportScene()
  595. {
  596. const char* sceneName = "defaultScene";
  597. Ref<Scene> scene = mAsset->scenes.Create(sceneName);
  598. // root node will be the first one exported (idx 0)
  599. if (mAsset->nodes.Size() > 0) {
  600. scene->nodes.push_back(mAsset->nodes.Get(0u));
  601. }
  602. // set as the default scene
  603. mAsset->scene = scene;
  604. }
  605. void glTFExporter::ExportMetadata()
  606. {
  607. glTF::AssetMetadata& asset = mAsset->asset;
  608. asset.version = 1;
  609. char buffer[256];
  610. ai_snprintf(buffer, 256, "Open Asset Import Library (assimp v%d.%d.%d)",
  611. aiGetVersionMajor(), aiGetVersionMinor(), aiGetVersionRevision());
  612. asset.generator = buffer;
  613. }
  614. inline void ExtractAnimationData(Asset& mAsset, std::string& animId, Ref<Animation>& animRef, Ref<Buffer>& buffer, const aiNodeAnim* nodeChannel)
  615. {
  616. // Loop over the data and check to see if it exactly matches an existing buffer.
  617. // If yes, then reference the existing corresponding accessor.
  618. // Otherwise, add to the buffer and create a new accessor.
  619. //-------------------------------------------------------
  620. // Extract TIME parameter data.
  621. // Check if the timeStamps are the same for mPositionKeys, mRotationKeys, and mScalingKeys.
  622. if(nodeChannel->mNumPositionKeys > 0) {
  623. typedef float TimeType;
  624. std::vector<TimeType> timeData;
  625. timeData.resize(nodeChannel->mNumPositionKeys);
  626. for (size_t i = 0; i < nodeChannel->mNumPositionKeys; ++i) {
  627. timeData[i] = nodeChannel->mPositionKeys[i].mTime; // Check if we have to cast type here. e.g. uint16_t()
  628. }
  629. Ref<Accessor> timeAccessor = ExportData(mAsset, animId, buffer, nodeChannel->mNumPositionKeys, &timeData[0], AttribType::SCALAR, AttribType::SCALAR, ComponentType_FLOAT);
  630. if (timeAccessor) animRef->Parameters.TIME = timeAccessor;
  631. }
  632. //-------------------------------------------------------
  633. // Extract translation parameter data
  634. if(nodeChannel->mNumPositionKeys > 0) {
  635. C_STRUCT aiVector3D* translationData = new aiVector3D[nodeChannel->mNumPositionKeys];
  636. for (size_t i = 0; i < nodeChannel->mNumPositionKeys; ++i) {
  637. translationData[i] = nodeChannel->mPositionKeys[i].mValue;
  638. }
  639. Ref<Accessor> tranAccessor = ExportData(mAsset, animId, buffer, nodeChannel->mNumPositionKeys, translationData, AttribType::VEC3, AttribType::VEC3, ComponentType_FLOAT);
  640. if (tranAccessor) animRef->Parameters.translation = tranAccessor;
  641. }
  642. //-------------------------------------------------------
  643. // Extract scale parameter data
  644. if(nodeChannel->mNumScalingKeys > 0) {
  645. C_STRUCT aiVector3D* scaleData = new aiVector3D[nodeChannel->mNumScalingKeys];
  646. for (size_t i = 0; i < nodeChannel->mNumScalingKeys; ++i) {
  647. scaleData[i] = nodeChannel->mScalingKeys[i].mValue;
  648. }
  649. Ref<Accessor> scaleAccessor = ExportData(mAsset, animId, buffer, nodeChannel->mNumScalingKeys, scaleData, AttribType::VEC3, AttribType::VEC3, ComponentType_FLOAT);
  650. if (scaleAccessor) animRef->Parameters.scale = scaleAccessor;
  651. }
  652. //-------------------------------------------------------
  653. // Extract rotation parameter data
  654. if(nodeChannel->mNumRotationKeys > 0) {
  655. vec4* rotationData = new vec4[nodeChannel->mNumRotationKeys];
  656. for (size_t i = 0; i < nodeChannel->mNumRotationKeys; ++i) {
  657. rotationData[i][0] = nodeChannel->mRotationKeys[i].mValue.x;
  658. rotationData[i][1] = nodeChannel->mRotationKeys[i].mValue.y;
  659. rotationData[i][2] = nodeChannel->mRotationKeys[i].mValue.z;
  660. rotationData[i][3] = nodeChannel->mRotationKeys[i].mValue.w;
  661. }
  662. Ref<Accessor> rotAccessor = ExportData(mAsset, animId, buffer, nodeChannel->mNumRotationKeys, rotationData, AttribType::VEC4, AttribType::VEC4, ComponentType_FLOAT);
  663. if (rotAccessor) animRef->Parameters.rotation = rotAccessor;
  664. }
  665. }
  666. void glTFExporter::ExportAnimations()
  667. {
  668. Ref<Buffer> bufferRef = mAsset->buffers.Get(unsigned (0));
  669. for (unsigned int i = 0; i < mScene->mNumAnimations; ++i) {
  670. const aiAnimation* anim = mScene->mAnimations[i];
  671. std::string nameAnim = "anim";
  672. if (anim->mName.length > 0) {
  673. nameAnim = anim->mName.C_Str();
  674. }
  675. for (unsigned int channelIndex = 0; channelIndex < anim->mNumChannels; ++channelIndex) {
  676. const aiNodeAnim* nodeChannel = anim->mChannels[channelIndex];
  677. // It appears that assimp stores this type of animation as multiple animations.
  678. // where each aiNodeAnim in mChannels animates a specific node.
  679. std::string name = nameAnim + "_" + std::to_string(channelIndex);
  680. name = mAsset->FindUniqueID(name, "animation");
  681. Ref<Animation> animRef = mAsset->animations.Create(name);
  682. /******************* Parameters ********************/
  683. ExtractAnimationData(*mAsset, name, animRef, bufferRef, nodeChannel);
  684. for (unsigned int j = 0; j < 3; ++j) {
  685. std::string channelType;
  686. int channelSize;
  687. switch (j) {
  688. case 0:
  689. channelType = "rotation";
  690. channelSize = nodeChannel->mNumRotationKeys;
  691. break;
  692. case 1:
  693. channelType = "scale";
  694. channelSize = nodeChannel->mNumScalingKeys;
  695. break;
  696. case 2:
  697. channelType = "translation";
  698. channelSize = nodeChannel->mNumPositionKeys;
  699. break;
  700. }
  701. if (channelSize < 1) { continue; }
  702. Animation::AnimChannel tmpAnimChannel;
  703. Animation::AnimSampler tmpAnimSampler;
  704. tmpAnimChannel.sampler = name + "_" + channelType;
  705. tmpAnimChannel.target.path = channelType;
  706. tmpAnimSampler.output = channelType;
  707. tmpAnimSampler.id = name + "_" + channelType;
  708. tmpAnimChannel.target.id = mAsset->nodes.Get(nodeChannel->mNodeName.C_Str());
  709. tmpAnimSampler.input = "TIME";
  710. tmpAnimSampler.interpolation = "LINEAR";
  711. animRef->Channels.push_back(tmpAnimChannel);
  712. animRef->Samplers.push_back(tmpAnimSampler);
  713. }
  714. }
  715. // Assimp documentation staes this is not used (not implemented)
  716. // for (unsigned int channelIndex = 0; channelIndex < anim->mNumMeshChannels; ++channelIndex) {
  717. // const aiMeshAnim* meshChannel = anim->mMeshChannels[channelIndex];
  718. // }
  719. } // End: for-loop mNumAnimations
  720. }
  721. #endif // ASSIMP_BUILD_NO_GLTF_EXPORTER
  722. #endif // ASSIMP_BUILD_NO_EXPORT