glTF2Asset.h 38 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131
  1. /*
  2. Open Asset Import Library (assimp)
  3. ----------------------------------------------------------------------
  4. Copyright (c) 2006-2017, 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. /** @file glTFAsset.h
  34. * Declares a glTF class to handle gltf/glb files
  35. *
  36. * glTF Extensions Support:
  37. * KHR_materials_pbrSpecularGlossiness full
  38. */
  39. #ifndef GLTF2ASSET_H_INC
  40. #define GLTF2ASSET_H_INC
  41. #ifndef ASSIMP_BUILD_NO_GLTF_IMPORTER
  42. #include <map>
  43. #include <string>
  44. #include <list>
  45. #include <vector>
  46. #include <algorithm>
  47. #include <stdexcept>
  48. #define RAPIDJSON_HAS_STDSTRING 1
  49. #include <rapidjson/rapidjson.h>
  50. #include <rapidjson/document.h>
  51. #include <rapidjson/error/en.h>
  52. #ifdef ASSIMP_API
  53. # include <memory>
  54. # include <assimp/DefaultIOSystem.h>
  55. # include "ByteSwapper.h"
  56. #else
  57. # include <memory>
  58. # define AI_SWAP4(p)
  59. # define ai_assert
  60. #endif
  61. #if _MSC_VER > 1500 || (defined __GNUC___)
  62. # define ASSIMP_GLTF_USE_UNORDERED_MULTIMAP
  63. # else
  64. # define gltf_unordered_map map
  65. #endif
  66. #ifdef ASSIMP_GLTF_USE_UNORDERED_MULTIMAP
  67. # include <unordered_map>
  68. # if _MSC_VER > 1600
  69. # define gltf_unordered_map unordered_map
  70. # else
  71. # define gltf_unordered_map tr1::unordered_map
  72. # endif
  73. #endif
  74. #include "StringUtils.h"
  75. namespace glTF2
  76. {
  77. #ifdef ASSIMP_API
  78. using Assimp::IOStream;
  79. using Assimp::IOSystem;
  80. using std::shared_ptr;
  81. #else
  82. using std::shared_ptr;
  83. typedef std::runtime_error DeadlyImportError;
  84. typedef std::runtime_error DeadlyExportError;
  85. enum aiOrigin { aiOrigin_SET = 0, aiOrigin_CUR = 1, aiOrigin_END = 2 };
  86. class IOSystem;
  87. class IOStream
  88. {
  89. FILE* f;
  90. public:
  91. IOStream(FILE* file) : f(file) {}
  92. ~IOStream() { fclose(f); f = 0; }
  93. size_t Read(void* b, size_t sz, size_t n) { return fread(b, sz, n, f); }
  94. size_t Write(const void* b, size_t sz, size_t n) { return fwrite(b, sz, n, f); }
  95. int Seek(size_t off, aiOrigin orig) { return fseek(f, off, int(orig)); }
  96. size_t Tell() const { return ftell(f); }
  97. size_t FileSize() {
  98. long p = Tell(), len = (Seek(0, aiOrigin_END), Tell());
  99. return size_t((Seek(p, aiOrigin_SET), len));
  100. }
  101. };
  102. #endif
  103. using rapidjson::Value;
  104. using rapidjson::Document;
  105. class Asset;
  106. class AssetWriter;
  107. struct BufferView; // here due to cross-reference
  108. struct Texture;
  109. struct Skin;
  110. // Vec/matrix types, as raw float arrays
  111. typedef float (vec3)[3];
  112. typedef float (vec4)[4];
  113. typedef float (mat4)[16];
  114. namespace Util
  115. {
  116. void EncodeBase64(const uint8_t* in, size_t inLength, std::string& out);
  117. size_t DecodeBase64(const char* in, size_t inLength, uint8_t*& out);
  118. inline size_t DecodeBase64(const char* in, uint8_t*& out)
  119. {
  120. return DecodeBase64(in, strlen(in), out);
  121. }
  122. struct DataURI
  123. {
  124. const char* mediaType;
  125. const char* charset;
  126. bool base64;
  127. const char* data;
  128. size_t dataLength;
  129. };
  130. //! Check if a uri is a data URI
  131. inline bool ParseDataURI(const char* uri, size_t uriLen, DataURI& out);
  132. }
  133. //! Magic number for GLB files
  134. #define AI_GLB_MAGIC_NUMBER "glTF"
  135. #define AI_MATKEY_GLTF_PBRMETALLICROUGHNESS_BASE_COLOR_FACTOR "$mat.gltf.pbrMetallicRoughness.baseColorFactor", 0, 0
  136. #define AI_MATKEY_GLTF_PBRMETALLICROUGHNESS_METALLIC_FACTOR "$mat.gltf.pbrMetallicRoughness.metallicFactor", 0, 0
  137. #define AI_MATKEY_GLTF_PBRMETALLICROUGHNESS_ROUGHNESS_FACTOR "$mat.gltf.pbrMetallicRoughness.roughnessFactor", 0, 0
  138. #define AI_MATKEY_GLTF_PBRMETALLICROUGHNESS_BASE_COLOR_TEXTURE aiTextureType_DIFFUSE, 1
  139. #define AI_MATKEY_GLTF_PBRMETALLICROUGHNESS_METALLICROUGHNESS_TEXTURE aiTextureType_UNKNOWN, 0
  140. #define AI_MATKEY_GLTF_ALPHAMODE "$mat.gltf.alphaMode", 0, 0
  141. #define AI_MATKEY_GLTF_ALPHACUTOFF "$mat.gltf.alphaCutoff", 0, 0
  142. #define AI_MATKEY_GLTF_PBRSPECULARGLOSSINESS "$mat.gltf.pbrSpecularGlossiness", 0, 0
  143. #define AI_MATKEY_GLTF_PBRSPECULARGLOSSINESS_GLOSSINESS_FACTOR "$mat.gltf.pbrMetallicRoughness.glossinessFactor", 0, 0
  144. #define _AI_MATKEY_GLTF_TEXTURE_TEXCOORD_BASE "$tex.file.texCoord"
  145. #define _AI_MATKEY_GLTF_MAPPINGNAME_BASE "$tex.mappingname"
  146. #define _AI_MATKEY_GLTF_MAPPINGID_BASE "$tex.mappingid"
  147. #define _AI_MATKEY_GLTF_MAPPINGFILTER_MAG_BASE "$tex.mappingfiltermag"
  148. #define _AI_MATKEY_GLTF_MAPPINGFILTER_MIN_BASE "$tex.mappingfiltermin"
  149. #define AI_MATKEY_GLTF_TEXTURE_TEXCOORD _AI_MATKEY_GLTF_TEXTURE_TEXCOORD_BASE, type, N
  150. #define AI_MATKEY_GLTF_MAPPINGNAME(type, N) _AI_MATKEY_GLTF_MAPPINGNAME_BASE, type, N
  151. #define AI_MATKEY_GLTF_MAPPINGID(type, N) _AI_MATKEY_GLTF_MAPPINGID_BASE, type, N
  152. #define AI_MATKEY_GLTF_MAPPINGFILTER_MAG(type, N) _AI_MATKEY_GLTF_MAPPINGFILTER_MAG_BASE, type, N
  153. #define AI_MATKEY_GLTF_MAPPINGFILTER_MIN(type, N) _AI_MATKEY_GLTF_MAPPINGFILTER_MIN_BASE, type, N
  154. #ifdef ASSIMP_API
  155. #include "./../include/assimp/Compiler/pushpack1.h"
  156. #endif
  157. //! For binary .glb files
  158. //! 12-byte header (+ the JSON + a "body" data section)
  159. struct GLB_Header
  160. {
  161. uint8_t magic[4]; //!< Magic number: "glTF"
  162. uint32_t version; //!< Version number (always 2 as of the last update)
  163. uint32_t length; //!< Total length of the Binary glTF, including header, scene, and body, in bytes
  164. } PACK_STRUCT;
  165. struct GLB_Chunk
  166. {
  167. uint32_t chunkLength;
  168. uint32_t chunkType;
  169. } PACK_STRUCT;
  170. #ifdef ASSIMP_API
  171. #include "./../include/assimp/Compiler/poppack1.h"
  172. #endif
  173. //! Values for the GLB_Chunk::chunkType field
  174. enum ChunkType
  175. {
  176. ChunkType_JSON = 0x4E4F534A,
  177. ChunkType_BIN = 0x004E4942
  178. };
  179. //! Values for the mesh primitive modes
  180. enum PrimitiveMode
  181. {
  182. PrimitiveMode_POINTS = 0,
  183. PrimitiveMode_LINES = 1,
  184. PrimitiveMode_LINE_LOOP = 2,
  185. PrimitiveMode_LINE_STRIP = 3,
  186. PrimitiveMode_TRIANGLES = 4,
  187. PrimitiveMode_TRIANGLE_STRIP = 5,
  188. PrimitiveMode_TRIANGLE_FAN = 6
  189. };
  190. //! Values for the Accessor::componentType field
  191. enum ComponentType
  192. {
  193. ComponentType_BYTE = 5120,
  194. ComponentType_UNSIGNED_BYTE = 5121,
  195. ComponentType_SHORT = 5122,
  196. ComponentType_UNSIGNED_SHORT = 5123,
  197. ComponentType_UNSIGNED_INT = 5125,
  198. ComponentType_FLOAT = 5126
  199. };
  200. inline unsigned int ComponentTypeSize(ComponentType t)
  201. {
  202. switch (t) {
  203. case ComponentType_SHORT:
  204. case ComponentType_UNSIGNED_SHORT:
  205. return 2;
  206. case ComponentType_UNSIGNED_INT:
  207. case ComponentType_FLOAT:
  208. return 4;
  209. case ComponentType_BYTE:
  210. case ComponentType_UNSIGNED_BYTE:
  211. return 1;
  212. default:
  213. throw DeadlyImportError("GLTF: Unsupported Component Type " + to_string(t));
  214. }
  215. }
  216. //! Values for the BufferView::target field
  217. enum BufferViewTarget
  218. {
  219. BufferViewTarget_ARRAY_BUFFER = 34962,
  220. BufferViewTarget_ELEMENT_ARRAY_BUFFER = 34963
  221. };
  222. //! Values for the Sampler::magFilter field
  223. enum class SamplerMagFilter: unsigned int
  224. {
  225. UNSET = 0,
  226. SamplerMagFilter_Nearest = 9728,
  227. SamplerMagFilter_Linear = 9729
  228. };
  229. //! Values for the Sampler::minFilter field
  230. enum class SamplerMinFilter: unsigned int
  231. {
  232. UNSET = 0,
  233. SamplerMinFilter_Nearest = 9728,
  234. SamplerMinFilter_Linear = 9729,
  235. SamplerMinFilter_Nearest_Mipmap_Nearest = 9984,
  236. SamplerMinFilter_Linear_Mipmap_Nearest = 9985,
  237. SamplerMinFilter_Nearest_Mipmap_Linear = 9986,
  238. SamplerMinFilter_Linear_Mipmap_Linear = 9987
  239. };
  240. //! Values for the Sampler::wrapS and Sampler::wrapT field
  241. enum class SamplerWrap: unsigned int
  242. {
  243. UNSET = 0,
  244. Clamp_To_Edge = 33071,
  245. Mirrored_Repeat = 33648,
  246. Repeat = 10497
  247. };
  248. //! Values for the Texture::format and Texture::internalFormat fields
  249. enum TextureFormat
  250. {
  251. TextureFormat_ALPHA = 6406,
  252. TextureFormat_RGB = 6407,
  253. TextureFormat_RGBA = 6408,
  254. TextureFormat_LUMINANCE = 6409,
  255. TextureFormat_LUMINANCE_ALPHA = 6410
  256. };
  257. //! Values for the Texture::target field
  258. enum TextureTarget
  259. {
  260. TextureTarget_TEXTURE_2D = 3553
  261. };
  262. //! Values for the Texture::type field
  263. enum TextureType
  264. {
  265. TextureType_UNSIGNED_BYTE = 5121,
  266. TextureType_UNSIGNED_SHORT_5_6_5 = 33635,
  267. TextureType_UNSIGNED_SHORT_4_4_4_4 = 32819,
  268. TextureType_UNSIGNED_SHORT_5_5_5_1 = 32820
  269. };
  270. //! Values for the Accessor::type field (helper class)
  271. class AttribType
  272. {
  273. public:
  274. enum Value
  275. { SCALAR, VEC2, VEC3, VEC4, MAT2, MAT3, MAT4 };
  276. private:
  277. static const size_t NUM_VALUES = static_cast<size_t>(MAT4)+1;
  278. struct Info
  279. { const char* name; unsigned int numComponents; };
  280. template<int N> struct data
  281. { static const Info infos[NUM_VALUES]; };
  282. public:
  283. inline static Value FromString(const char* str)
  284. {
  285. for (size_t i = 0; i < NUM_VALUES; ++i) {
  286. if (strcmp(data<0>::infos[i].name, str) == 0) {
  287. return static_cast<Value>(i);
  288. }
  289. }
  290. return SCALAR;
  291. }
  292. inline static const char* ToString(Value type)
  293. {
  294. return data<0>::infos[static_cast<size_t>(type)].name;
  295. }
  296. inline static unsigned int GetNumComponents(Value type)
  297. {
  298. return data<0>::infos[static_cast<size_t>(type)].numComponents;
  299. }
  300. };
  301. // must match the order of the AttribTypeTraits::Value enum!
  302. template<int N> const AttribType::Info
  303. AttribType::data<N>::infos[AttribType::NUM_VALUES] = {
  304. { "SCALAR", 1 }, { "VEC2", 2 }, { "VEC3", 3 }, { "VEC4", 4 }, { "MAT2", 4 }, { "MAT3", 9 }, { "MAT4", 16 }
  305. };
  306. //! A reference to one top-level object, which is valid
  307. //! until the Asset instance is destroyed
  308. template<class T>
  309. class Ref
  310. {
  311. std::vector<T*>* vector;
  312. unsigned int index;
  313. public:
  314. Ref() : vector(0), index(0) {}
  315. Ref(std::vector<T*>& vec, unsigned int idx) : vector(&vec), index(idx) {}
  316. inline unsigned int GetIndex() const
  317. { return index; }
  318. operator bool() const
  319. { return vector != 0; }
  320. T* operator->()
  321. { return (*vector)[index]; }
  322. T& operator*()
  323. { return *((*vector)[index]); }
  324. };
  325. //! Helper struct to represent values that might not be present
  326. template<class T>
  327. struct Nullable
  328. {
  329. T value;
  330. bool isPresent;
  331. Nullable() : isPresent(false) {}
  332. Nullable(T& val) : value(val), isPresent(true) {}
  333. };
  334. //! Base classe for all glTF top-level objects
  335. struct Object
  336. {
  337. int index; //!< The index of this object within its property container
  338. int oIndex; //!< The original index of this object defined in the JSON
  339. std::string id; //!< The globally unique ID used to reference this object
  340. std::string name; //!< The user-defined name of this object
  341. //! Objects marked as special are not exported (used to emulate the binary body buffer)
  342. virtual bool IsSpecial() const
  343. { return false; }
  344. virtual ~Object() {}
  345. //! Maps special IDs to another ID, where needed. Subclasses may override it (statically)
  346. static const char* TranslateId(Asset& /*r*/, const char* id)
  347. { return id; }
  348. };
  349. //
  350. // Classes for each glTF top-level object type
  351. //
  352. //! A typed view into a BufferView. A BufferView contains raw binary data.
  353. //! An accessor provides a typed view into a BufferView or a subset of a BufferView
  354. //! similar to how WebGL's vertexAttribPointer() defines an attribute in a buffer.
  355. struct Accessor : public Object
  356. {
  357. Ref<BufferView> bufferView; //!< The ID of the bufferView. (required)
  358. unsigned int byteOffset; //!< The offset relative to the start of the bufferView in bytes. (required)
  359. ComponentType componentType; //!< The datatype of components in the attribute. (required)
  360. unsigned int count; //!< The number of attributes referenced by this accessor. (required)
  361. AttribType::Value type; //!< Specifies if the attribute is a scalar, vector, or matrix. (required)
  362. std::vector<float> max; //!< Maximum value of each component in this attribute.
  363. std::vector<float> min; //!< Minimum value of each component in this attribute.
  364. unsigned int GetNumComponents();
  365. unsigned int GetBytesPerComponent();
  366. unsigned int GetElementSize();
  367. inline uint8_t* GetPointer();
  368. template<class T>
  369. bool ExtractData(T*& outData);
  370. void WriteData(size_t count, const void* src_buffer, size_t src_stride);
  371. //! Helper class to iterate the data
  372. class Indexer
  373. {
  374. friend struct Accessor;
  375. Accessor& accessor;
  376. uint8_t* data;
  377. size_t elemSize, stride;
  378. Indexer(Accessor& acc);
  379. public:
  380. //! Accesses the i-th value as defined by the accessor
  381. template<class T>
  382. T GetValue(int i);
  383. //! Accesses the i-th value as defined by the accessor
  384. inline unsigned int GetUInt(int i)
  385. {
  386. return GetValue<unsigned int>(i);
  387. }
  388. inline bool IsValid() const
  389. {
  390. return data != 0;
  391. }
  392. };
  393. inline Indexer GetIndexer()
  394. {
  395. return Indexer(*this);
  396. }
  397. Accessor() {}
  398. void Read(Value& obj, Asset& r);
  399. };
  400. //! A buffer points to binary geometry, animation, or skins.
  401. struct Buffer : public Object
  402. {
  403. /********************* Types *********************/
  404. public:
  405. enum Type
  406. {
  407. Type_arraybuffer,
  408. Type_text
  409. };
  410. /// \struct SEncodedRegion
  411. /// Descriptor of encoded region in "bufferView".
  412. struct SEncodedRegion
  413. {
  414. const size_t Offset;///< Offset from begin of "bufferView" to encoded region, in bytes.
  415. const size_t EncodedData_Length;///< Size of encoded region, in bytes.
  416. uint8_t* const DecodedData;///< Cached encoded data.
  417. const size_t DecodedData_Length;///< Size of decoded region, in bytes.
  418. const std::string ID;///< ID of the region.
  419. /// \fn SEncodedRegion(const size_t pOffset, const size_t pEncodedData_Length, uint8_t* pDecodedData, const size_t pDecodedData_Length, const std::string pID)
  420. /// Constructor.
  421. /// \param [in] pOffset - offset from begin of "bufferView" to encoded region, in bytes.
  422. /// \param [in] pEncodedData_Length - size of encoded region, in bytes.
  423. /// \param [in] pDecodedData - pointer to decoded data array.
  424. /// \param [in] pDecodedData_Length - size of encoded region, in bytes.
  425. /// \param [in] pID - ID of the region.
  426. SEncodedRegion(const size_t pOffset, const size_t pEncodedData_Length, uint8_t* pDecodedData, const size_t pDecodedData_Length, const std::string pID)
  427. : Offset(pOffset), EncodedData_Length(pEncodedData_Length), DecodedData(pDecodedData), DecodedData_Length(pDecodedData_Length), ID(pID)
  428. {}
  429. /// \fn ~SEncodedRegion()
  430. /// Destructor.
  431. ~SEncodedRegion() { delete[] DecodedData; }
  432. };
  433. /******************* Variables *******************/
  434. //std::string uri; //!< The uri of the buffer. Can be a filepath, a data uri, etc. (required)
  435. size_t byteLength; //!< The length of the buffer in bytes. (default: 0)
  436. //std::string type; //!< XMLHttpRequest responseType (default: "arraybuffer")
  437. Type type;
  438. /// \var EncodedRegion_Current
  439. /// Pointer to currently active encoded region.
  440. /// Why not decoding all regions at once and not to set one buffer with decoded data?
  441. /// Yes, why not? Even "accessor" point to decoded data. I mean that fields "byteOffset", "byteStride" and "count" has values which describes decoded
  442. /// data array. But only in range of mesh while is active parameters from "compressedData". For another mesh accessors point to decoded data too. But
  443. /// offset is counted for another regions is encoded.
  444. /// Example. You have two meshes. For every of it you have 4 bytes of data. That data compressed to 2 bytes. So, you have buffer with encoded data:
  445. /// M1_E0, M1_E1, M2_E0, M2_E1.
  446. /// After decoding you'll get:
  447. /// M1_D0, M1_D1, M1_D2, M1_D3, M2_D0, M2_D1, M2_D2, M2_D3.
  448. /// "accessors" must to use values that point to decoded data - obviously. So, you'll expect "accessors" like
  449. /// "accessor_0" : { byteOffset: 0, byteLength: 4}, "accessor_1" : { byteOffset: 4, byteLength: 4}
  450. /// but in real life you'll get:
  451. /// "accessor_0" : { byteOffset: 0, byteLength: 4}, "accessor_1" : { byteOffset: 2, byteLength: 4}
  452. /// Yes, accessor of next mesh has offset and length which mean: current mesh data is decoded, all other data is encoded.
  453. /// And when before you start to read data of current mesh (with encoded data ofcourse) you must decode region of "bufferView", after read finished
  454. /// delete encoding mark. And after that you can repeat process: decode data of mesh, read, delete decoded data.
  455. ///
  456. /// Remark. Encoding all data at once is good in world with computers which do not has RAM limitation. So, you must use step by step encoding in
  457. /// exporter and importer. And, thanks to such way, there is no need to load whole file into memory.
  458. SEncodedRegion* EncodedRegion_Current;
  459. private:
  460. shared_ptr<uint8_t> mData; //!< Pointer to the data
  461. bool mIsSpecial; //!< Set to true for special cases (e.g. the body buffer)
  462. /// \var EncodedRegion_List
  463. /// List of encoded regions.
  464. std::list<SEncodedRegion*> EncodedRegion_List;
  465. /******************* Functions *******************/
  466. public:
  467. Buffer();
  468. ~Buffer();
  469. void Read(Value& obj, Asset& r);
  470. bool LoadFromStream(IOStream& stream, size_t length = 0, size_t baseOffset = 0);
  471. /// \fn void EncodedRegion_Mark(const size_t pOffset, const size_t pEncodedData_Length, uint8_t* pDecodedData, const size_t pDecodedData_Length, const std::string& pID)
  472. /// Mark region of "bufferView" as encoded. When data is request from such region then "bufferView" use decoded data.
  473. /// \param [in] pOffset - offset from begin of "bufferView" to encoded region, in bytes.
  474. /// \param [in] pEncodedData_Length - size of encoded region, in bytes.
  475. /// \param [in] pDecodedData - pointer to decoded data array.
  476. /// \param [in] pDecodedData_Length - size of encoded region, in bytes.
  477. /// \param [in] pID - ID of the region.
  478. void EncodedRegion_Mark(const size_t pOffset, const size_t pEncodedData_Length, uint8_t* pDecodedData, const size_t pDecodedData_Length, const std::string& pID);
  479. /// \fn void EncodedRegion_SetCurrent(const std::string& pID)
  480. /// Select current encoded region by ID. \sa EncodedRegion_Current.
  481. /// \param [in] pID - ID of the region.
  482. void EncodedRegion_SetCurrent(const std::string& pID);
  483. /// \fn bool ReplaceData(const size_t pBufferData_Offset, const size_t pBufferData_Count, const uint8_t* pReplace_Data, const size_t pReplace_Count)
  484. /// Replace part of buffer data. Pay attention that function work with original array of data (\ref mData) not with encoded regions.
  485. /// \param [in] pBufferData_Offset - index of first element in buffer from which new data will be placed.
  486. /// \param [in] pBufferData_Count - count of bytes in buffer which will be replaced.
  487. /// \param [in] pReplace_Data - pointer to array with new data for buffer.
  488. /// \param [in] pReplace_Count - count of bytes in new data.
  489. /// \return true - if successfully replaced, false if input arguments is out of range.
  490. bool ReplaceData(const size_t pBufferData_Offset, const size_t pBufferData_Count, const uint8_t* pReplace_Data, const size_t pReplace_Count);
  491. size_t AppendData(uint8_t* data, size_t length);
  492. void Grow(size_t amount);
  493. uint8_t* GetPointer()
  494. { return mData.get(); }
  495. void MarkAsSpecial()
  496. { mIsSpecial = true; }
  497. bool IsSpecial() const
  498. { return mIsSpecial; }
  499. std::string GetURI()
  500. { return std::string(this->id) + ".bin"; }
  501. static const char* TranslateId(Asset& r, const char* id);
  502. };
  503. //! A view into a buffer generally representing a subset of the buffer.
  504. struct BufferView : public Object
  505. {
  506. Ref<Buffer> buffer; //! The ID of the buffer. (required)
  507. size_t byteOffset; //! The offset into the buffer in bytes. (required)
  508. size_t byteLength; //! The length of the bufferView in bytes. (default: 0)
  509. unsigned int byteStride; //!< The stride, in bytes, between attributes referenced by this accessor. (default: 0)
  510. BufferViewTarget target; //! The target that the WebGL buffer should be bound to.
  511. void Read(Value& obj, Asset& r);
  512. };
  513. struct Camera : public Object
  514. {
  515. enum Type
  516. {
  517. Perspective,
  518. Orthographic
  519. };
  520. Type type;
  521. union
  522. {
  523. struct {
  524. float aspectRatio; //!<The floating - point aspect ratio of the field of view. (0 = undefined = use the canvas one)
  525. float yfov; //!<The floating - point vertical field of view in radians. (required)
  526. float zfar; //!<The floating - point distance to the far clipping plane. (required)
  527. float znear; //!< The floating - point distance to the near clipping plane. (required)
  528. } perspective;
  529. struct {
  530. float xmag; //! The floating-point horizontal magnification of the view. (required)
  531. float ymag; //! The floating-point vertical magnification of the view. (required)
  532. float zfar; //! The floating-point distance to the far clipping plane. (required)
  533. float znear; //! The floating-point distance to the near clipping plane. (required)
  534. } ortographic;
  535. } cameraProperties;
  536. Camera() {}
  537. void Read(Value& obj, Asset& r);
  538. };
  539. //! Image data used to create a texture.
  540. struct Image : public Object
  541. {
  542. std::string uri; //! The uri of the image, that can be a file path, a data URI, etc.. (required)
  543. Ref<BufferView> bufferView;
  544. std::string mimeType;
  545. int width, height;
  546. private:
  547. uint8_t* mData;
  548. size_t mDataLength;
  549. public:
  550. Image();
  551. void Read(Value& obj, Asset& r);
  552. inline bool HasData() const
  553. { return mDataLength > 0; }
  554. inline size_t GetDataLength() const
  555. { return mDataLength; }
  556. inline const uint8_t* GetData() const
  557. { return mData; }
  558. inline uint8_t* StealData();
  559. inline void SetData(uint8_t* data, size_t length, Asset& r);
  560. };
  561. const vec4 defaultBaseColor = {1, 1, 1, 1};
  562. const vec3 defaultEmissiveFactor = {0, 0, 0};
  563. const vec4 defaultDiffuseFactor = {1, 1, 1, 1};
  564. const vec3 defaultSpecularFactor = {1, 1, 1};
  565. struct TextureInfo
  566. {
  567. Ref<Texture> texture;
  568. unsigned int index;
  569. unsigned int texCoord = 0;
  570. };
  571. struct NormalTextureInfo : TextureInfo
  572. {
  573. float scale = 1;
  574. };
  575. struct OcclusionTextureInfo : TextureInfo
  576. {
  577. float strength = 1;
  578. };
  579. struct PbrMetallicRoughness
  580. {
  581. vec4 baseColorFactor;
  582. TextureInfo baseColorTexture;
  583. TextureInfo metallicRoughnessTexture;
  584. float metallicFactor;
  585. float roughnessFactor;
  586. };
  587. struct PbrSpecularGlossiness
  588. {
  589. vec4 diffuseFactor;
  590. vec3 specularFactor;
  591. float glossinessFactor;
  592. TextureInfo diffuseTexture;
  593. TextureInfo specularGlossinessTexture;
  594. PbrSpecularGlossiness() { SetDefaults(); }
  595. void SetDefaults();
  596. };
  597. //! The material appearance of a primitive.
  598. struct Material : public Object
  599. {
  600. //PBR metallic roughness properties
  601. PbrMetallicRoughness pbrMetallicRoughness;
  602. //other basic material properties
  603. NormalTextureInfo normalTexture;
  604. OcclusionTextureInfo occlusionTexture;
  605. TextureInfo emissiveTexture;
  606. vec3 emissiveFactor;
  607. std::string alphaMode;
  608. float alphaCutoff;
  609. bool doubleSided;
  610. //extension: KHR_materials_pbrSpecularGlossiness
  611. Nullable<PbrSpecularGlossiness> pbrSpecularGlossiness;
  612. Material() { SetDefaults(); }
  613. void Read(Value& obj, Asset& r);
  614. void SetDefaults();
  615. };
  616. //! A set of primitives to be rendered. A node can contain one or more meshes. A node's transform places the mesh in the scene.
  617. struct Mesh : public Object
  618. {
  619. typedef std::vector< Ref<Accessor> > AccessorList;
  620. struct Primitive
  621. {
  622. PrimitiveMode mode;
  623. struct Attributes {
  624. AccessorList position, normal, tangent, texcoord, color, joint, jointmatrix, weight;
  625. } attributes;
  626. Ref<Accessor> indices;
  627. Ref<Material> material;
  628. };
  629. std::vector<Primitive> primitives;
  630. Mesh() {}
  631. /// \fn void Read(Value& pJSON_Object, Asset& pAsset_Root)
  632. /// Get mesh data from JSON-object and place them to root asset.
  633. /// \param [in] pJSON_Object - reference to pJSON-object from which data are read.
  634. /// \param [out] pAsset_Root - reference to root assed where data will be stored.
  635. void Read(Value& pJSON_Object, Asset& pAsset_Root);
  636. };
  637. struct Node : public Object
  638. {
  639. std::vector< Ref<Node> > children;
  640. std::vector< Ref<Mesh> > meshes;
  641. Nullable<mat4> matrix;
  642. Nullable<vec3> translation;
  643. Nullable<vec4> rotation;
  644. Nullable<vec3> scale;
  645. Ref<Camera> camera;
  646. std::vector< Ref<Node> > skeletons; //!< The ID of skeleton nodes. Each of which is the root of a node hierarchy.
  647. Ref<Skin> skin; //!< The ID of the skin referenced by this node.
  648. std::string jointName; //!< Name used when this node is a joint in a skin.
  649. Ref<Node> parent; //!< This is not part of the glTF specification. Used as a helper.
  650. Node() {}
  651. void Read(Value& obj, Asset& r);
  652. };
  653. struct Program : public Object
  654. {
  655. Program() {}
  656. void Read(Value& obj, Asset& r);
  657. };
  658. struct Sampler : public Object
  659. {
  660. SamplerMagFilter magFilter; //!< The texture magnification filter.
  661. SamplerMinFilter minFilter; //!< The texture minification filter.
  662. SamplerWrap wrapS; //!< The texture wrapping in the S direction.
  663. SamplerWrap wrapT; //!< The texture wrapping in the T direction.
  664. Sampler() { SetDefaults(); }
  665. void Read(Value& obj, Asset& r);
  666. void SetDefaults();
  667. };
  668. struct Scene : public Object
  669. {
  670. std::vector< Ref<Node> > nodes;
  671. Scene() {}
  672. void Read(Value& obj, Asset& r);
  673. };
  674. struct Shader : public Object
  675. {
  676. Shader() {}
  677. void Read(Value& obj, Asset& r);
  678. };
  679. struct Skin : public Object
  680. {
  681. Nullable<mat4> bindShapeMatrix; //!< Floating-point 4x4 transformation matrix stored in column-major order.
  682. Ref<Accessor> inverseBindMatrices; //!< The ID of the accessor containing the floating-point 4x4 inverse-bind matrices.
  683. std::vector<Ref<Node>> jointNames; //!< Joint names of the joints (nodes with a jointName property) in this skin.
  684. std::string name; //!< The user-defined name of this object.
  685. Skin() {}
  686. void Read(Value& obj, Asset& r);
  687. };
  688. //! A texture and its sampler.
  689. struct Texture : public Object
  690. {
  691. Ref<Sampler> sampler; //!< The ID of the sampler used by this texture. (required)
  692. Ref<Image> source; //!< The ID of the image used by this texture. (required)
  693. //TextureFormat format; //!< The texture's format. (default: TextureFormat_RGBA)
  694. //TextureFormat internalFormat; //!< The texture's internal format. (default: TextureFormat_RGBA)
  695. //TextureTarget target; //!< The target that the WebGL texture should be bound to. (default: TextureTarget_TEXTURE_2D)
  696. //TextureType type; //!< Texel datatype. (default: TextureType_UNSIGNED_BYTE)
  697. Texture() {}
  698. void Read(Value& obj, Asset& r);
  699. };
  700. struct Animation : public Object
  701. {
  702. struct AnimSampler {
  703. std::string id; //!< The ID of this sampler.
  704. std::string input; //!< The ID of a parameter in this animation to use as key-frame input.
  705. std::string interpolation; //!< Type of interpolation algorithm to use between key-frames.
  706. std::string output; //!< The ID of a parameter in this animation to use as key-frame output.
  707. };
  708. struct AnimChannel {
  709. int sampler; //!< The index of a sampler in the containing animation's samplers property.
  710. struct AnimTarget {
  711. Ref<Node> node; //!< The node to animate.
  712. std::string path; //!< The name of property of the node to animate ("translation", "rotation", or "scale").
  713. } target;
  714. };
  715. struct AnimParameters {
  716. Ref<Accessor> TIME; //!< Accessor reference to a buffer storing a array of floating point scalar values.
  717. Ref<Accessor> rotation; //!< Accessor reference to a buffer storing a array of four-component floating-point vectors.
  718. Ref<Accessor> scale; //!< Accessor reference to a buffer storing a array of three-component floating-point vectors.
  719. Ref<Accessor> translation; //!< Accessor reference to a buffer storing a array of three-component floating-point vectors.
  720. };
  721. // AnimChannel Channels[3]; //!< Connect the output values of the key-frame animation to a specific node in the hierarchy.
  722. // AnimParameters Parameters; //!< The samplers that interpolate between the key-frames.
  723. // AnimSampler Samplers[3]; //!< The parameterized inputs representing the key-frame data.
  724. std::vector<AnimChannel> Channels; //!< Connect the output values of the key-frame animation to a specific node in the hierarchy.
  725. AnimParameters Parameters; //!< The samplers that interpolate between the key-frames.
  726. std::vector<AnimSampler> Samplers; //!< The parameterized inputs representing the key-frame data.
  727. Animation() {}
  728. void Read(Value& obj, Asset& r);
  729. //! Get accessor given an animation parameter name.
  730. Ref<Accessor> GetAccessor(std::string name) {
  731. if (name == "TIME") {
  732. return Parameters.TIME;
  733. } else if (name == "rotation") {
  734. return Parameters.rotation;
  735. } else if (name == "scale") {
  736. return Parameters.scale;
  737. } else if (name == "translation") {
  738. return Parameters.translation;
  739. }
  740. return Ref<Accessor>();
  741. }
  742. };
  743. //! Base class for LazyDict that acts as an interface
  744. class LazyDictBase
  745. {
  746. public:
  747. virtual ~LazyDictBase() {}
  748. virtual void AttachToDocument(Document& doc) = 0;
  749. virtual void DetachFromDocument() = 0;
  750. virtual void WriteObjects(AssetWriter& writer) = 0;
  751. };
  752. template<class T>
  753. class LazyDict;
  754. //! (Implemented in glTFAssetWriter.h)
  755. template<class T>
  756. void WriteLazyDict(LazyDict<T>& d, AssetWriter& w);
  757. //! Manages lazy loading of the glTF top-level objects, and keeps a reference to them by ID
  758. //! It is the owner the loaded objects, so when it is destroyed it also deletes them
  759. template<class T>
  760. class LazyDict : public LazyDictBase
  761. {
  762. friend class Asset;
  763. friend class AssetWriter;
  764. typedef typename std::gltf_unordered_map< unsigned int, unsigned int > Dict;
  765. typedef typename std::gltf_unordered_map< std::string, unsigned int > IdDict;
  766. std::vector<T*> mObjs; //! The read objects
  767. Dict mObjsByOIndex; //! The read objects accessible by original index
  768. IdDict mObjsById; //! The read objects accessible by id
  769. const char* mDictId; //! ID of the dictionary object
  770. const char* mExtId; //! ID of the extension defining the dictionary
  771. Value* mDict; //! JSON dictionary object
  772. Asset& mAsset; //! The asset instance
  773. void AttachToDocument(Document& doc);
  774. void DetachFromDocument();
  775. void WriteObjects(AssetWriter& writer)
  776. { WriteLazyDict<T>(*this, writer); }
  777. Ref<T> Add(T* obj);
  778. public:
  779. LazyDict(Asset& asset, const char* dictId, const char* extId = 0);
  780. ~LazyDict();
  781. Ref<T> Retrieve(unsigned int i);
  782. Ref<T> Get(unsigned int i);
  783. Ref<T> Get(const char* id);
  784. Ref<T> Create(const char* id);
  785. Ref<T> Create(const std::string& id)
  786. { return Create(id.c_str()); }
  787. unsigned int Remove(const char* id);
  788. inline unsigned int Size() const
  789. { return unsigned(mObjs.size()); }
  790. inline T& operator[](size_t i)
  791. { return *mObjs[i]; }
  792. };
  793. struct AssetMetadata
  794. {
  795. std::string copyright; //!< A copyright message suitable for display to credit the content creator.
  796. std::string generator; //!< Tool that generated this glTF model.Useful for debugging.
  797. struct {
  798. std::string api; //!< Specifies the target rendering API (default: "WebGL")
  799. std::string version; //!< Specifies the target rendering API (default: "1.0.3")
  800. } profile; //!< Specifies the target rendering API and version, e.g., WebGL 1.0.3. (default: {})
  801. std::string version; //!< The glTF format version
  802. void Read(Document& doc);
  803. AssetMetadata() : version("") {}
  804. };
  805. //
  806. // glTF Asset class
  807. //
  808. //! Root object for a glTF asset
  809. class Asset
  810. {
  811. typedef std::gltf_unordered_map<std::string, int> IdMap;
  812. template<class T>
  813. friend class LazyDict;
  814. friend struct Buffer; // To access OpenFile
  815. friend class AssetWriter;
  816. private:
  817. IOSystem* mIOSystem;
  818. std::string mCurrentAssetDir;
  819. size_t mSceneLength;
  820. size_t mBodyOffset, mBodyLength;
  821. std::vector<LazyDictBase*> mDicts;
  822. IdMap mUsedIds;
  823. Ref<Buffer> mBodyBuffer;
  824. Asset(Asset&);
  825. Asset& operator=(const Asset&);
  826. public:
  827. //! Keeps info about the enabled extensions
  828. struct Extensions
  829. {
  830. bool KHR_materials_pbrSpecularGlossiness;
  831. } extensionsUsed;
  832. AssetMetadata asset;
  833. // Dictionaries for each type of object
  834. LazyDict<Accessor> accessors;
  835. LazyDict<Animation> animations;
  836. LazyDict<Buffer> buffers;
  837. LazyDict<BufferView> bufferViews;
  838. LazyDict<Camera> cameras;
  839. LazyDict<Image> images;
  840. LazyDict<Material> materials;
  841. LazyDict<Mesh> meshes;
  842. LazyDict<Node> nodes;
  843. LazyDict<Sampler> samplers;
  844. LazyDict<Scene> scenes;
  845. LazyDict<Skin> skins;
  846. LazyDict<Texture> textures;
  847. Ref<Scene> scene;
  848. public:
  849. Asset(IOSystem* io = 0)
  850. : mIOSystem(io)
  851. , asset()
  852. , accessors (*this, "accessors")
  853. , animations (*this, "animations")
  854. , buffers (*this, "buffers")
  855. , bufferViews (*this, "bufferViews")
  856. , cameras (*this, "cameras")
  857. , images (*this, "images")
  858. , materials (*this, "materials")
  859. , meshes (*this, "meshes")
  860. , nodes (*this, "nodes")
  861. , samplers (*this, "samplers")
  862. , scenes (*this, "scenes")
  863. , skins (*this, "skins")
  864. , textures (*this, "textures")
  865. {
  866. memset(&extensionsUsed, 0, sizeof(extensionsUsed));
  867. }
  868. //! Main function
  869. void Load(const std::string& file, bool isBinary = false);
  870. //! Enables binary encoding on the asset
  871. void SetAsBinary();
  872. //! Search for an available name, starting from the given strings
  873. std::string FindUniqueID(const std::string& str, const char* suffix);
  874. Ref<Buffer> GetBodyBuffer()
  875. { return mBodyBuffer; }
  876. private:
  877. void ReadBinaryHeader(IOStream& stream, std::vector<char>& sceneData);
  878. void ReadExtensionsUsed(Document& doc);
  879. IOStream* OpenFile(std::string path, const char* mode, bool absolute = false);
  880. };
  881. }
  882. // Include the implementation of the methods
  883. #include "glTF2Asset.inl"
  884. #endif // ASSIMP_BUILD_NO_GLTF_IMPORTER
  885. #endif // GLTF2ASSET_H_INC