glTFAsset.h 38 KB

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