glTFAsset.h 26 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945
  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 <vector>
  45. #include <algorithm>
  46. #include <stdexcept>
  47. #define RAPIDJSON_HAS_STDSTRING 1
  48. #include <rapidjson/rapidjson.h>
  49. #include <rapidjson/document.h>
  50. #include <rapidjson/error/en.h>
  51. #ifdef ASSIMP_API
  52. # include "boost/shared_ptr.hpp"
  53. # include "DefaultIOSystem.h"
  54. # include "ByteSwapper.h"
  55. #else
  56. # include <memory>
  57. # define AI_SWAP4(p)
  58. # define ai_assert
  59. #endif
  60. #if _MSC_VER > 1500 || (defined __GNUC___)
  61. # define ASSIMP_GLTF_USE_UNORDERED_MULTIMAP
  62. # else
  63. # define gltf_unordered_map map
  64. #endif
  65. #ifdef ASSIMP_GLTF_USE_UNORDERED_MULTIMAP
  66. # include <unordered_map>
  67. # if _MSC_VER > 1600
  68. # define gltf_unordered_map unordered_map
  69. # else
  70. # define gltf_unordered_map tr1::unordered_map
  71. # endif
  72. #endif
  73. namespace glTF
  74. {
  75. #ifdef ASSIMP_API
  76. using Assimp::IOStream;
  77. using Assimp::IOSystem;
  78. using boost::shared_ptr;
  79. #else
  80. using std::shared_ptr;
  81. typedef std::runtime_error DeadlyImportError;
  82. typedef std::runtime_error DeadlyExportError;
  83. enum aiOrigin { aiOrigin_SET = 0, aiOrigin_CUR = 1, aiOrigin_END = 2 };
  84. class IOSystem;
  85. class IOStream
  86. {
  87. FILE* f;
  88. public:
  89. IOStream(FILE* file) : f(file) {}
  90. ~IOStream() { fclose(f); f = 0; }
  91. size_t Read(void* b, size_t sz, size_t n) { return fread(b, sz, n, f); }
  92. size_t Write(const void* b, size_t sz, size_t n) { return fwrite(b, sz, n, f); }
  93. int Seek(size_t off, aiOrigin orig) { return fseek(f, off, int(orig)); }
  94. size_t Tell() const { return ftell(f); }
  95. size_t FileSize() {
  96. long p = Tell(), len = (Seek(0, aiOrigin_END), Tell());
  97. return size_t((Seek(p, aiOrigin_SET), len));
  98. }
  99. };
  100. #endif
  101. using rapidjson::Value;
  102. using rapidjson::Document;
  103. class Asset;
  104. class AssetWriter;
  105. struct BufferView; // here due to cross-reference
  106. struct Texture;
  107. struct Light;
  108. // Vec/matrix types, as raw float arrays
  109. typedef float (vec3)[3];
  110. typedef float (vec4)[4];
  111. typedef float (mat4)[16];
  112. namespace Util
  113. {
  114. void EncodeBase64(const uint8_t* in, size_t inLength, std::string& out);
  115. size_t DecodeBase64(const char* in, size_t inLength, uint8_t*& out);
  116. inline size_t DecodeBase64(const char* in, uint8_t*& out)
  117. {
  118. return DecodeBase64(in, strlen(in), out);
  119. }
  120. struct DataURI
  121. {
  122. const char* mediaType;
  123. const char* charset;
  124. bool base64;
  125. const char* data;
  126. size_t dataLength;
  127. };
  128. //! Check if a uri is a data URI
  129. inline bool ParseDataURI(const char* uri, size_t uriLen, DataURI& out);
  130. }
  131. //! Magic number for GLB files
  132. #define AI_GLB_MAGIC_NUMBER "glTF"
  133. #ifdef ASSIMP_API
  134. #include "./../include/assimp/Compiler/pushpack1.h"
  135. #endif
  136. //! For the KHR_binary_glTF extension (binary .glb file)
  137. //! 20-byte header (+ the JSON + a "body" data section)
  138. struct GLB_Header
  139. {
  140. uint8_t magic[4]; //!< Magic number: "glTF"
  141. uint32_t version; //!< Version number (always 1 as of the last update)
  142. uint32_t length; //!< Total length of the Binary glTF, including header, scene, and body, in bytes
  143. uint32_t sceneLength; //!< Length, in bytes, of the glTF scene
  144. uint32_t sceneFormat; //!< Specifies the format of the glTF scene (see the SceneFormat enum)
  145. } PACK_STRUCT;
  146. #ifdef ASSIMP_API
  147. #include "./../include/assimp/Compiler/poppack1.h"
  148. #endif
  149. //! Values for the GLB_Header::sceneFormat field
  150. enum SceneFormat
  151. {
  152. SceneFormat_JSON = 0
  153. };
  154. //! Values for the mesh primitive modes
  155. enum PrimitiveMode
  156. {
  157. PrimitiveMode_POINTS = 0,
  158. PrimitiveMode_LINES = 1,
  159. PrimitiveMode_LINE_LOOP = 2,
  160. PrimitiveMode_LINE_STRIP = 3,
  161. PrimitiveMode_TRIANGLES = 4,
  162. PrimitiveMode_TRIANGLE_STRIP = 5,
  163. PrimitiveMode_TRIANGLE_FAN = 6
  164. };
  165. //! Values for the Accessor::componentType field
  166. enum ComponentType
  167. {
  168. ComponentType_BYTE = 5120,
  169. ComponentType_UNSIGNED_BYTE = 5121,
  170. ComponentType_SHORT = 5122,
  171. ComponentType_UNSIGNED_SHORT = 5123,
  172. ComponentType_FLOAT = 5126
  173. };
  174. inline size_t ComponentTypeSize(ComponentType t)
  175. {
  176. switch (t) {
  177. case ComponentType_SHORT:
  178. case ComponentType_UNSIGNED_SHORT:
  179. return 2;
  180. case ComponentType_FLOAT:
  181. return 4;
  182. //case Accessor::ComponentType_BYTE:
  183. //case Accessor::ComponentType_UNSIGNED_BYTE:
  184. default:
  185. return 1;
  186. }
  187. }
  188. //! Values for the BufferView::target field
  189. enum BufferViewTarget
  190. {
  191. BufferViewTarget_ARRAY_BUFFER = 34962,
  192. BufferViewTarget_ELEMENT_ARRAY_BUFFER = 34963
  193. };
  194. //! Values for the Texture::format and Texture::internalFormat fields
  195. enum TextureFormat
  196. {
  197. TextureFormat_ALPHA = 6406,
  198. TextureFormat_RGB = 6407,
  199. TextureFormat_RGBA = 6408,
  200. TextureFormat_LUMINANCE = 6409,
  201. TextureFormat_LUMINANCE_ALPHA = 6410
  202. };
  203. //! Values for the Texture::target field
  204. enum TextureTarget
  205. {
  206. TextureTarget_TEXTURE_2D = 3553
  207. };
  208. //! Values for the Texture::type field
  209. enum TextureType
  210. {
  211. TextureType_UNSIGNED_BYTE = 5121,
  212. TextureType_UNSIGNED_SHORT_5_6_5 = 33635,
  213. TextureType_UNSIGNED_SHORT_4_4_4_4 = 32819,
  214. TextureType_UNSIGNED_SHORT_5_5_5_1 = 32820
  215. };
  216. //! Values for the Accessor::type field (helper class)
  217. class AttribType
  218. {
  219. public:
  220. enum Value
  221. { SCALAR, VEC2, VEC3, VEC4, MAT2, MAT3, MAT4 };
  222. private:
  223. static const size_t NUM_VALUES = static_cast<size_t>(MAT4)+1;
  224. struct Info
  225. { const char* name; unsigned int numComponents; };
  226. template<int N> struct data
  227. { static const Info infos[NUM_VALUES]; };
  228. public:
  229. inline static Value FromString(const char* str)
  230. {
  231. for (size_t i = 0; i < NUM_VALUES; ++i) {
  232. if (strcmp(data<0>::infos[i].name, str) == 0) {
  233. return static_cast<Value>(i);
  234. }
  235. }
  236. return SCALAR;
  237. }
  238. inline static const char* ToString(Value type)
  239. {
  240. return data<0>::infos[static_cast<size_t>(type)].name;
  241. }
  242. inline static unsigned int GetNumComponents(Value type)
  243. {
  244. return data<0>::infos[static_cast<size_t>(type)].numComponents;
  245. }
  246. };
  247. // must match the order of the AttribTypeTraits::Value enum!
  248. template<int N> const AttribType::Info
  249. AttribType::data<N>::infos[AttribType::NUM_VALUES] = {
  250. { "SCALAR", 1 }, { "VEC2", 2 }, { "VEC3", 3 }, { "VEC4", 4 }, { "MAT2", 4 }, { "MAT3", 9 }, { "MAT4", 16 }
  251. };
  252. //! A reference to one top-level object, which is valid
  253. //! until the Asset instance is destroyed
  254. template<class T>
  255. class Ref
  256. {
  257. std::vector<T*>* vector;
  258. int index;
  259. public:
  260. Ref() : vector(0), index(0) {}
  261. Ref(std::vector<T*>& vec, int idx) : vector(&vec), index(idx) {}
  262. inline size_t GetIndex() const
  263. { return index; }
  264. operator bool() const
  265. { return vector != 0; }
  266. T* operator->()
  267. { return (*vector)[index]; }
  268. T& operator*()
  269. { return *((*vector)[index]); }
  270. };
  271. //! Helper struct to represent values that might not be present
  272. template<class T>
  273. struct Nullable
  274. {
  275. T value;
  276. bool isPresent;
  277. Nullable() : isPresent(false) {}
  278. Nullable(T& val) : value(val), isPresent(true) {}
  279. };
  280. //! Base classe for all glTF top-level objects
  281. struct Object
  282. {
  283. std::string id; //!< The globally unique ID used to reference this object
  284. std::string name; //!< The user-defined name of this object
  285. //! Objects marked as special are not exported (used to emulate the binary body buffer)
  286. virtual bool IsSpecial() const
  287. { return false; }
  288. virtual ~Object() {}
  289. };
  290. //
  291. // Classes for each glTF top-level object type
  292. //
  293. //! A typed view into a BufferView. A BufferView contains raw binary data.
  294. //! An accessor provides a typed view into a BufferView or a subset of a BufferView
  295. // !similar to how WebGL's vertexAttribPointer() defines an attribute in a buffer.
  296. struct Accessor : public Object
  297. {
  298. Ref<BufferView> bufferView; //!< The ID of the bufferView. (required)
  299. unsigned int byteOffset; //!< The offset relative to the start of the bufferView in bytes. (required)
  300. unsigned int byteStride; //!< The stride, in bytes, between attributes referenced by this accessor. (default: 0)
  301. ComponentType componentType; //!< The datatype of components in the attribute. (required)
  302. unsigned int count; //!< The number of attributes referenced by this accessor. (required)
  303. AttribType::Value type; //!< Specifies if the attribute is a scalar, vector, or matrix. (required)
  304. //std::vector<float> max; //!< Maximum value of each component in this attribute.
  305. //std::vector<float> min; //!< Minimum value of each component in this attribute.
  306. unsigned int GetNumComponents();
  307. unsigned int GetBytesPerComponent();
  308. unsigned int GetElementSize();
  309. inline uint8_t* GetPointer();
  310. template<class T>
  311. void ExtractData(T*& outData);
  312. void WriteData(size_t count, const void* src_buffer, size_t src_stride);
  313. //! Helper class to iterate the data
  314. class Indexer
  315. {
  316. friend struct Accessor;
  317. Accessor& accessor;
  318. uint8_t* data;
  319. size_t elemSize, stride;
  320. Indexer(Accessor& acc);
  321. public:
  322. //! Accesses the i-th value as defined by the accessor
  323. template<class T>
  324. T GetValue(int i);
  325. //! Accesses the i-th value as defined by the accessor
  326. inline unsigned int GetUInt(int i)
  327. {
  328. return GetValue<unsigned int>(i);
  329. }
  330. };
  331. inline Indexer GetIndexer()
  332. {
  333. return Indexer(*this);
  334. }
  335. Accessor() {}
  336. void Read(Value& obj, Asset& r);
  337. };
  338. struct Animation : public Object
  339. {
  340. struct Channel
  341. {
  342. };
  343. struct Target
  344. {
  345. };
  346. struct Sampler
  347. {
  348. };
  349. };
  350. //! A buffer points to binary geometry, animation, or skins.
  351. struct Buffer : public Object
  352. {
  353. public:
  354. enum Type
  355. {
  356. Type_arraybuffer,
  357. Type_text
  358. };
  359. //std::string uri; //!< The uri of the buffer. Can be a filepath, a data uri, etc. (required)
  360. size_t byteLength; //!< The length of the buffer in bytes. (default: 0)
  361. //std::string type; //!< XMLHttpRequest responseType (default: "arraybuffer")
  362. Type type;
  363. private:
  364. shared_ptr<uint8_t> mData; //!< Pointer to the data
  365. bool mIsSpecial; //!< Set to true for special cases (e.g. the body buffer)
  366. public:
  367. Buffer();
  368. void Read(Value& obj, Asset& r);
  369. void LoadFromStream(IOStream& stream, size_t length = 0, size_t baseOffset = 0);
  370. size_t AppendData(uint8_t* data, size_t length);
  371. void Grow(size_t amount);
  372. uint8_t* GetPointer()
  373. { return mData.get(); }
  374. void MarkAsSpecial()
  375. { mIsSpecial = true; }
  376. bool IsSpecial() const
  377. { return mIsSpecial; }
  378. };
  379. //! A view into a buffer generally representing a subset of the buffer.
  380. struct BufferView : public Object
  381. {
  382. Ref<Buffer> buffer; //! The ID of the buffer. (required)
  383. size_t byteOffset; //! The offset into the buffer in bytes. (required)
  384. size_t byteLength; //! The length of the bufferView in bytes. (default: 0)
  385. BufferViewTarget target; //! The target that the WebGL buffer should be bound to.
  386. BufferView() {}
  387. void Read(Value& obj, Asset& r);
  388. };
  389. struct Camera : public Object
  390. {
  391. enum Type
  392. {
  393. Perspective,
  394. Orthographic
  395. };
  396. Type type;
  397. union
  398. {
  399. struct {
  400. float aspectRatio; //!<The floating - point aspect ratio of the field of view. (0 = undefined = use the canvas one)
  401. float yfov; //!<The floating - point vertical field of view in radians. (required)
  402. float zfar; //!<The floating - point distance to the far clipping plane. (required)
  403. float znear; //!< The floating - point distance to the near clipping plane. (required)
  404. } perspective;
  405. struct {
  406. float xmag; //! The floating-point horizontal magnification of the view. (required)
  407. float ymag; //! The floating-point vertical magnification of the view. (required)
  408. float zfar; //! The floating-point distance to the far clipping plane. (required)
  409. float znear; //! The floating-point distance to the near clipping plane. (required)
  410. } ortographic;
  411. };
  412. Camera() {}
  413. void Read(Value& obj, Asset& r);
  414. };
  415. //! Image data used to create a texture.
  416. struct Image : public Object
  417. {
  418. std::string uri; //! The uri of the image, that can be a file path, a data URI, etc.. (required)
  419. Ref<BufferView> bufferView;
  420. std::string mimeType;
  421. int width, height;
  422. private:
  423. uint8_t* mData;
  424. size_t mDataLength;
  425. public:
  426. Image();
  427. void Read(Value& obj, Asset& r);
  428. inline bool HasData() const
  429. { return mDataLength > 0; }
  430. inline size_t GetDataLength() const
  431. { return mDataLength; }
  432. inline const uint8_t* GetData() const
  433. { return mData; }
  434. inline uint8_t* StealData();
  435. inline void SetData(uint8_t* data, size_t length, Asset& r);
  436. };
  437. //! Holds a material property that can be a texture or a color
  438. struct TexProperty
  439. {
  440. Ref<Texture> texture;
  441. vec4 color;
  442. };
  443. //! The material appearance of a primitive.
  444. struct Material : public Object
  445. {
  446. //Ref<Sampler> source; //!< The ID of the technique.
  447. //std::gltf_unordered_map<std::string, std::string> values; //!< A dictionary object of parameter values.
  448. //! Techniques defined by KHR_materials_common
  449. enum Technique
  450. {
  451. Technique_undefined = 0,
  452. Technique_BLINN,
  453. Technique_PHONG,
  454. Technique_LAMBERT,
  455. Technique_CONSTANT
  456. };
  457. TexProperty ambient;
  458. TexProperty diffuse;
  459. TexProperty specular;
  460. TexProperty emission;
  461. bool doubleSided;
  462. bool transparent;
  463. float transparency;
  464. float shininess;
  465. Technique technique;
  466. Material() { SetDefaults(); }
  467. void Read(Value& obj, Asset& r);
  468. void SetDefaults();
  469. };
  470. //! 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.
  471. struct Mesh : public Object
  472. {
  473. typedef std::vector< Ref<Accessor> > AccessorList;
  474. struct Primitive
  475. {
  476. PrimitiveMode mode;
  477. struct Attributes {
  478. AccessorList position, normal, texcoord, color, joint, jointmatrix, weight;
  479. } attributes;
  480. Ref<Accessor> indices;
  481. Ref<Material> material;
  482. };
  483. std::vector<Primitive> primitives;
  484. Mesh() {}
  485. void Read(Value& obj, Asset& r);
  486. };
  487. struct Node : public Object
  488. {
  489. std::vector< Ref<Node> > children;
  490. std::vector< Ref<Mesh> > meshes;
  491. Nullable<mat4> matrix;
  492. Nullable<vec3> translation;
  493. Nullable<vec4> rotation;
  494. Nullable<vec3> scale;
  495. Ref<Camera> camera;
  496. Ref<Light> light;
  497. Node() {}
  498. void Read(Value& obj, Asset& r);
  499. };
  500. struct Program : public Object
  501. {
  502. Program() {}
  503. void Read(Value& obj, Asset& r);
  504. };
  505. struct Sampler : public Object
  506. {
  507. Sampler() {}
  508. void Read(Value& obj, Asset& r);
  509. };
  510. struct Scene : public Object
  511. {
  512. std::vector< Ref<Node> > nodes;
  513. Scene() {}
  514. void Read(Value& obj, Asset& r);
  515. };
  516. struct Shader : public Object
  517. {
  518. Shader() {}
  519. void Read(Value& obj, Asset& r);
  520. };
  521. struct Skin : public Object
  522. {
  523. Skin() {}
  524. void Read(Value& obj, Asset& r);
  525. };
  526. struct Technique : public Object
  527. {
  528. struct Parameters
  529. {
  530. };
  531. struct States
  532. {
  533. };
  534. struct Functions
  535. {
  536. };
  537. Technique() {}
  538. void Read(Value& obj, Asset& r);
  539. };
  540. //! A texture and its sampler.
  541. struct Texture : public Object
  542. {
  543. //Ref<Sampler> source; //!< The ID of the sampler used by this texture. (required)
  544. Ref<Image> source; //!< The ID of the image used by this texture. (required)
  545. //TextureFormat format; //!< The texture's format. (default: TextureFormat_RGBA)
  546. //TextureFormat internalFormat; //!< The texture's internal format. (default: TextureFormat_RGBA)
  547. //TextureTarget target; //!< The target that the WebGL texture should be bound to. (default: TextureTarget_TEXTURE_2D)
  548. //TextureType type; //!< Texel datatype. (default: TextureType_UNSIGNED_BYTE)
  549. Texture() {}
  550. void Read(Value& obj, Asset& r);
  551. };
  552. //! A light (from KHR_materials_common extension)
  553. struct Light : public Object
  554. {
  555. enum Type
  556. {
  557. Type_undefined,
  558. Type_ambient,
  559. Type_directional,
  560. Type_point,
  561. Type_spot
  562. };
  563. Type type;
  564. vec4 color;
  565. float distance;
  566. float constantAttenuation;
  567. float linearAttenuation;
  568. float quadraticAttenuation;
  569. float falloffAngle;
  570. float falloffExponent;
  571. Light() {}
  572. void Read(Value& obj, Asset& r);
  573. void SetDefaults();
  574. };
  575. //! Base class for LazyDict that acts as an interface
  576. class LazyDictBase
  577. {
  578. public:
  579. virtual ~LazyDictBase() {}
  580. virtual void AttachToDocument(Document& doc) = 0;
  581. virtual void DetachFromDocument() = 0;
  582. virtual void WriteObjects(AssetWriter& writer) = 0;
  583. };
  584. //! (Stub class that is specialized in glTFAssetWriter.h)
  585. template<class T>
  586. struct LazyDictWriter
  587. {
  588. static void Write(T& d, AssetWriter& w) {}
  589. };
  590. //! Manages lazy loading of the glTF top-level objects, and keeps a reference to them by ID
  591. //! It is the owner the loaded objects, so when it is destroyed it also deletes them
  592. template<class T>
  593. class LazyDict : public LazyDictBase
  594. {
  595. friend class Asset;
  596. friend class AssetWriter;
  597. typedef typename std::gltf_unordered_map< std::string, size_t > Dict;
  598. std::vector<T*> mObjs; //! The read objects
  599. Dict mObjsById; //! The read objects accesible by id
  600. const char* mDictId; //! ID of the dictionary object
  601. const char* mExtId; //! ID of the extension defining the dictionary
  602. Value* mDict; //! JSON dictionary object
  603. Asset& mAsset; //! The asset instance
  604. void AttachToDocument(Document& doc);
  605. void DetachFromDocument();
  606. void WriteObjects(AssetWriter& writer)
  607. { LazyDictWriter< LazyDict >::Write(*this, writer); }
  608. Ref<T> Add(T* obj);
  609. public:
  610. LazyDict(Asset& asset, const char* dictId, const char* extId = 0);
  611. ~LazyDict();
  612. Ref<T> Get(const char* id);
  613. Ref<T> Get(size_t i);
  614. Ref<T> Create(const char* id);
  615. Ref<T> Create(const std::string& id)
  616. { return Create(id.c_str()); }
  617. inline size_t Size() const
  618. { return mObjs.size(); }
  619. inline T& operator[](size_t i)
  620. { return *mObjs[i]; }
  621. };
  622. struct AssetMetadata
  623. {
  624. std::string copyright; //!< A copyright message suitable for display to credit the content creator.
  625. std::string generator; //!< Tool that generated this glTF model.Useful for debugging.
  626. bool premultipliedAlpha; //!< Specifies if the shaders were generated with premultiplied alpha. (default: false)
  627. struct {
  628. std::string api; //!< Specifies the target rendering API (default: "WebGL")
  629. std::string version; //!< Specifies the target rendering API (default: "1.0.3")
  630. } profile; //!< Specifies the target rendering API and version, e.g., WebGL 1.0.3. (default: {})
  631. int version; //!< The glTF format version (should be 1)
  632. void Read(Document& doc);
  633. };
  634. //
  635. // glTF Asset class
  636. //
  637. //! Root object for a glTF asset
  638. class Asset
  639. {
  640. typedef std::gltf_unordered_map<std::string, int> IdMap;
  641. template<class T>
  642. friend class LazyDict;
  643. friend struct Buffer; // To access OpenFile
  644. friend class AssetWriter;
  645. private:
  646. IOSystem* mIOSystem;
  647. std::string mCurrentAssetDir;
  648. size_t mSceneLength;
  649. size_t mBodyOffset, mBodyLength;
  650. std::vector<LazyDictBase*> mDicts;
  651. IdMap mUsedIds;
  652. Ref<Buffer> mBodyBuffer;
  653. Asset(Asset&);
  654. Asset& operator=(const Asset&);
  655. public:
  656. //! Keeps info about the enabled extensions
  657. struct Extensions
  658. {
  659. bool KHR_binary_glTF;
  660. bool KHR_materials_common;
  661. } extensionsUsed;
  662. AssetMetadata asset;
  663. // Dictionaries for each type of object
  664. LazyDict<Accessor> accessors;
  665. LazyDict<Animation> animations;
  666. LazyDict<Buffer> buffers;
  667. LazyDict<BufferView> bufferViews;
  668. LazyDict<Camera> cameras;
  669. LazyDict<Image> images;
  670. LazyDict<Material> materials;
  671. LazyDict<Mesh> meshes;
  672. LazyDict<Node> nodes;
  673. //LazyDict<Program> programs;
  674. //LazyDict<Sampler> samplers;
  675. LazyDict<Scene> scenes;
  676. //LazyDict<Shader> shaders;
  677. //LazyDict<Skin> skins;
  678. //LazyDict<Technique> techniques;
  679. LazyDict<Texture> textures;
  680. LazyDict<Light> lights; // KHR_materials_common ext
  681. Ref<Scene> scene;
  682. public:
  683. Asset(IOSystem* io = 0)
  684. : mIOSystem(io)
  685. , accessors (*this, "accessors")
  686. , animations (*this, "animations")
  687. , buffers (*this, "buffers")
  688. , bufferViews (*this, "bufferViews")
  689. , cameras (*this, "cameras")
  690. , images (*this, "images")
  691. , materials (*this, "materials")
  692. , meshes (*this, "meshes")
  693. , nodes (*this, "nodes")
  694. //, programs (*this, "programs")
  695. //, samplers (*this, "samplers")
  696. , scenes (*this, "scenes")
  697. //, shaders (*this, "shaders")
  698. //, skins (*this, "skins")
  699. //, techniques (*this, "techniques")
  700. , textures (*this, "textures")
  701. , lights (*this, "lights", "KHR_materials_common")
  702. {
  703. memset(&extensionsUsed, 0, sizeof(extensionsUsed));
  704. memset(&asset, 0, sizeof(asset));
  705. }
  706. //! Main function
  707. void Load(const std::string& file, bool isBinary = false);
  708. //! Enables the "KHR_binary_glTF" extension on the asset
  709. void SetAsBinary();
  710. //! Search for an available name, starting from the given strings
  711. std::string FindUniqueID(const std::string& str, const char* suffix);
  712. Ref<Buffer> GetBodyBuffer()
  713. { return mBodyBuffer; }
  714. private:
  715. void ReadBinaryHeader(IOStream& stream);
  716. void ReadExtensionsUsed(Document& doc);
  717. IOStream* OpenFile(std::string path, const char* mode, bool absolute = false);
  718. };
  719. }
  720. // Include the implementation of the methods
  721. #include "glTFAsset.inl"
  722. #endif