glTFExporter.cpp 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367
  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 <assimp/version.h>
  40. #include <assimp/IOSystem.hpp>
  41. #include <assimp/Exporter.hpp>
  42. #include <assimp/material.h>
  43. #include <assimp/scene.h>
  44. #include <boost/foreach.hpp>
  45. #include <boost/scoped_ptr.hpp>
  46. #include <boost/shared_ptr.hpp>
  47. #include "glTFAssetWriter.h"
  48. using namespace rapidjson;
  49. using namespace Assimp;
  50. using namespace glTF;
  51. namespace Assimp {
  52. // ------------------------------------------------------------------------------------------------
  53. // Worker function for exporting a scene to GLTF. Prototyped and registered in Exporter.cpp
  54. void ExportSceneGLTF(const char* pFile, IOSystem* pIOSystem, const aiScene* pScene, const ExportProperties* pProperties)
  55. {
  56. // invoke the exporter
  57. glTFExporter exporter(pFile, pIOSystem, pScene, pProperties, false);
  58. }
  59. // ------------------------------------------------------------------------------------------------
  60. // Worker function for exporting a scene to GLB. Prototyped and registered in Exporter.cpp
  61. void ExportSceneGLB(const char* pFile, IOSystem* pIOSystem, const aiScene* pScene, const ExportProperties* pProperties)
  62. {
  63. // invoke the exporter
  64. glTFExporter exporter(pFile, pIOSystem, pScene, pProperties, true);
  65. }
  66. } // end of namespace Assimp
  67. glTFExporter::glTFExporter(const char* filename, IOSystem* pIOSystem, const aiScene* pScene,
  68. const ExportProperties* pProperties, bool isBinary)
  69. : mFilename(filename)
  70. , mIOSystem(pIOSystem)
  71. , mScene(pScene)
  72. , mProperties(pProperties)
  73. {
  74. boost::scoped_ptr<Asset> asset(new glTF::Asset(pIOSystem));
  75. mAsset = asset.get();
  76. if (isBinary) {
  77. asset->SetAsBinary();
  78. }
  79. ExportMetadata();
  80. //for (unsigned int i = 0; i < pScene->mNumAnimations; ++i) {}
  81. //for (unsigned int i = 0; i < pScene->mNumCameras; ++i) {}
  82. //for (unsigned int i = 0; i < pScene->mNumLights; ++i) {}
  83. ExportMaterials();
  84. ExportMeshes();
  85. //for (unsigned int i = 0; i < pScene->mNumTextures; ++i) {}
  86. if (mScene->mRootNode) {
  87. ExportNode(mScene->mRootNode);
  88. }
  89. ExportScene();
  90. glTF::AssetWriter writer(*mAsset);
  91. writer.WriteFile(filename);
  92. }
  93. static void CopyValue(const aiMatrix4x4& v, glTF::mat4& o)
  94. {
  95. o[ 0] = v.a1; o[ 1] = v.b1; o[ 2] = v.c1; o[ 3] = v.d1;
  96. o[ 4] = v.a2; o[ 5] = v.b2; o[ 6] = v.c2; o[ 7] = v.d2;
  97. o[ 8] = v.a3; o[ 9] = v.b3; o[10] = v.c3; o[11] = v.d3;
  98. o[12] = v.a4; o[13] = v.b4; o[14] = v.c4; o[15] = v.d4;
  99. }
  100. inline Ref<Accessor> ExportData(Asset& a, std::string& meshName, Ref<Buffer>& buffer,
  101. unsigned int count, void* data, AttribType::Value typeIn, AttribType::Value typeOut, ComponentType compType, bool isIndices = false)
  102. {
  103. if (!count || !data) return Ref<Accessor>();
  104. unsigned int numCompsIn = AttribType::GetNumComponents(typeIn);
  105. unsigned int numCompsOut = AttribType::GetNumComponents(typeOut);
  106. unsigned int bytesPerComp = ComponentTypeSize(compType);
  107. size_t offset = buffer->byteLength;
  108. size_t length = count * numCompsOut * bytesPerComp;
  109. buffer->Grow(length);
  110. // bufferView
  111. Ref<BufferView> bv = a.bufferViews.Create(a.FindUniqueID(meshName, "view"));
  112. bv->buffer = buffer;
  113. bv->byteOffset = 0;
  114. bv->byteLength = length; //! The target that the WebGL buffer should be bound to.
  115. bv->target = isIndices ? BufferViewTarget_ELEMENT_ARRAY_BUFFER : BufferViewTarget_ARRAY_BUFFER;
  116. // accessor
  117. Ref<Accessor> acc = a.accessors.Create(a.FindUniqueID(meshName, "accessor"));
  118. acc->bufferView = bv;
  119. acc->byteOffset = offset;
  120. acc->byteStride = 0;
  121. acc->componentType = compType;
  122. acc->count = count;
  123. acc->type = typeOut;
  124. // copy the data
  125. acc->WriteData(count, data, numCompsIn*bytesPerComp);
  126. return acc;
  127. }
  128. namespace {
  129. void GetMatScalar(const aiMaterial* mat, float& val, const char* propName, int type, int idx) {
  130. if (mat->Get(propName, type, idx, val) == AI_SUCCESS) {}
  131. }
  132. }
  133. void glTFExporter::GetMatColorOrTex(const aiMaterial* mat, glTF::TexProperty& prop, const char* propName, int type, int idx, aiTextureType tt)
  134. {
  135. aiString tex;
  136. aiColor4D col;
  137. if (mat->GetTextureCount(tt) > 0) {
  138. if (mat->Get(AI_MATKEY_TEXTURE(tt, 0), tex) == AI_SUCCESS) {
  139. std::string path = tex.C_Str();
  140. if (path.size() > 0) {
  141. if (path[0] != '*') {
  142. std::map<std::string, size_t>::iterator it = mTexturesByPath.find(path);
  143. if (it != mTexturesByPath.end()) {
  144. prop.texture = mAsset->textures.Get(it->second);
  145. }
  146. }
  147. if (!prop.texture) {
  148. std::string texId = mAsset->FindUniqueID("", "texture");
  149. prop.texture = mAsset->textures.Create(texId);
  150. mTexturesByPath[path] = prop.texture.GetIndex();
  151. std::string imgId = mAsset->FindUniqueID("", "image");
  152. prop.texture->source = mAsset->images.Create(imgId);
  153. if (path[0] == '*') { // embedded
  154. aiTexture* tex = mScene->mTextures[atoi(&path[1])];
  155. uint8_t* data = reinterpret_cast<uint8_t*>(tex->pcData);
  156. prop.texture->source->SetData(data, tex->mWidth, *mAsset);
  157. if (tex->achFormatHint[0]) {
  158. std::string mimeType = "image/";
  159. mimeType += (memcmp(tex->achFormatHint, "jpg", 3) == 0) ? "jpeg" : tex->achFormatHint;
  160. prop.texture->source->mimeType = mimeType;
  161. }
  162. }
  163. else {
  164. prop.texture->source->uri = path;
  165. }
  166. }
  167. }
  168. }
  169. }
  170. if (mat->Get(propName, type, idx, col) == AI_SUCCESS) {
  171. prop.color[0] = col.r; prop.color[1] = col.g; prop.color[2] = col.b; prop.color[3] = col.a;
  172. }
  173. }
  174. void glTFExporter::ExportMaterials()
  175. {
  176. aiString aiName;
  177. for (unsigned int i = 0; i < mScene->mNumMaterials; ++i) {
  178. const aiMaterial* mat = mScene->mMaterials[i];
  179. std::string name;
  180. if (mat->Get(AI_MATKEY_NAME, aiName) == AI_SUCCESS) {
  181. name = aiName.C_Str();
  182. }
  183. name = mAsset->FindUniqueID(name, "material");
  184. Ref<Material> m = mAsset->materials.Create(name);
  185. GetMatColorOrTex(mat, m->ambient, AI_MATKEY_COLOR_AMBIENT, aiTextureType_AMBIENT);
  186. GetMatColorOrTex(mat, m->diffuse, AI_MATKEY_COLOR_DIFFUSE, aiTextureType_DIFFUSE);
  187. GetMatColorOrTex(mat, m->specular, AI_MATKEY_COLOR_SPECULAR, aiTextureType_SPECULAR);
  188. GetMatColorOrTex(mat, m->emission, AI_MATKEY_COLOR_EMISSIVE, aiTextureType_EMISSIVE);
  189. GetMatScalar(mat, m->shininess, AI_MATKEY_SHININESS);
  190. }
  191. }
  192. void glTFExporter::ExportMeshes()
  193. {
  194. for (unsigned int i = 0; i < mScene->mNumMeshes; ++i) {
  195. const aiMesh* aim = mScene->mMeshes[i];
  196. std::string meshId = mAsset->FindUniqueID(aim->mName.C_Str(), "mesh");
  197. Ref<Mesh> m = mAsset->meshes.Create(meshId);
  198. m->primitives.resize(1);
  199. Mesh::Primitive& p = m->primitives.back();
  200. p.material = mAsset->materials.Get(aim->mMaterialIndex);
  201. std::string bufferId = mAsset->FindUniqueID(meshId, "buffer");
  202. Ref<Buffer> b = mAsset->GetBodyBuffer();
  203. if (!b) {
  204. b = mAsset->buffers.Create(bufferId);
  205. }
  206. Ref<Accessor> v = ExportData(*mAsset, meshId, b, aim->mNumVertices, aim->mVertices, AttribType::VEC3, AttribType::VEC3, ComponentType_FLOAT);
  207. if (v) p.attributes.position.push_back(v);
  208. Ref<Accessor> n = ExportData(*mAsset, meshId, b, aim->mNumVertices, aim->mNormals, AttribType::VEC3, AttribType::VEC3, ComponentType_FLOAT);
  209. if (n) p.attributes.normal.push_back(n);
  210. for (int i = 0; i < AI_MAX_NUMBER_OF_TEXTURECOORDS; ++i) {
  211. if (aim->mNumUVComponents[i] > 0) {
  212. AttribType::Value type = (aim->mNumUVComponents[i] == 2) ? AttribType::VEC2 : AttribType::VEC3;
  213. Ref<Accessor> tc = ExportData(*mAsset, meshId, b, aim->mNumVertices, aim->mTextureCoords[i], AttribType::VEC3, type, ComponentType_FLOAT, true);
  214. if (tc) p.attributes.texcoord.push_back(tc);
  215. }
  216. }
  217. if (aim->mNumFaces > 0) {
  218. unsigned int nIndicesPerFace = aim->mFaces[0].mNumIndices;
  219. std::vector<uint16_t> indices;
  220. indices.resize(aim->mNumFaces * nIndicesPerFace);
  221. for (size_t i = 0; i < aim->mNumFaces; ++i) {
  222. for (size_t j = 0; j < nIndicesPerFace; ++j) {
  223. indices[i*nIndicesPerFace + j] = uint16_t(aim->mFaces[i].mIndices[j]);
  224. }
  225. }
  226. p.indices = ExportData(*mAsset, meshId, b, indices.size(), &indices[0], AttribType::SCALAR, AttribType::SCALAR, ComponentType_UNSIGNED_SHORT);
  227. }
  228. switch (aim->mPrimitiveTypes) {
  229. case aiPrimitiveType_POLYGON:
  230. p.mode = PrimitiveMode_TRIANGLES; break; // TODO implement this
  231. case aiPrimitiveType_LINE:
  232. p.mode = PrimitiveMode_LINES; break;
  233. case aiPrimitiveType_POINT:
  234. p.mode = PrimitiveMode_POINTS; break;
  235. default: // aiPrimitiveType_TRIANGLE
  236. p.mode = PrimitiveMode_TRIANGLES;
  237. }
  238. }
  239. }
  240. size_t glTFExporter::ExportNode(const aiNode* n)
  241. {
  242. Ref<Node> node = mAsset->nodes.Create(mAsset->FindUniqueID(n->mName.C_Str(), "node"));
  243. if (!n->mTransformation.IsIdentity()) {
  244. node->matrix.isPresent = true;
  245. CopyValue(n->mTransformation, node->matrix.value);
  246. }
  247. for (unsigned int i = 0; i < n->mNumMeshes; ++i) {
  248. node->meshes.push_back(mAsset->meshes.Get(n->mMeshes[i]));
  249. }
  250. for (unsigned int i = 0; i < n->mNumChildren; ++i) {
  251. size_t idx = ExportNode(n->mChildren[i]);
  252. node->children.push_back(mAsset->nodes.Get(idx));
  253. }
  254. return node.GetIndex();
  255. }
  256. void glTFExporter::ExportScene()
  257. {
  258. const char* sceneName = "defaultScene";
  259. Ref<Scene> scene = mAsset->scenes.Create(sceneName);
  260. // root node will be the first one exported (idx 0)
  261. if (mAsset->nodes.Size() > 0) {
  262. scene->nodes.push_back(mAsset->nodes.Get(size_t(0)));
  263. }
  264. // set as the default scene
  265. mAsset->scene = scene;
  266. }
  267. void glTFExporter::ExportMetadata()
  268. {
  269. glTF::AssetMetadata& asset = mAsset->asset;
  270. asset.version = 1;
  271. char buffer[256];
  272. ai_snprintf(buffer, 256, "Open Asset Import Library (assimp v%d.%d.%d)",
  273. aiGetVersionMajor(), aiGetVersionMinor(), aiGetVersionRevision());
  274. asset.generator = buffer;
  275. }
  276. #endif // ASSIMP_BUILD_NO_GLTF_EXPORTER
  277. #endif // ASSIMP_BUILD_NO_EXPORT