glTF2Asset.h 36 KB

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