glTFAsset.h 38 KB

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