glTFAsset.h 39 KB

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