glTF2Asset.h 35 KB

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