glTFAsset.h 35 KB

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