glTFAsset.h 38 KB

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