glTFAsset.inl 52 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635
  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. #include "StringUtils.h"
  34. // Header files, Assimp
  35. #include <assimp/DefaultLogger.hpp>
  36. #ifdef ASSIMP_IMPORTER_GLTF_USE_OPEN3DGC
  37. // Header files, Open3DGC.
  38. # include <Open3DGC/o3dgcSC3DMCDecoder.h>
  39. #endif
  40. using namespace Assimp;
  41. namespace glTF {
  42. namespace {
  43. //
  44. // JSON Value reading helpers
  45. //
  46. template<class T>
  47. struct ReadHelper { static bool Read(Value& val, T& out) {
  48. return val.IsInt() ? out = static_cast<T>(val.GetInt()), true : false;
  49. }};
  50. template<> struct ReadHelper<bool> { static bool Read(Value& val, bool& out) {
  51. return val.IsBool() ? out = val.GetBool(), true : false;
  52. }};
  53. template<> struct ReadHelper<float> { static bool Read(Value& val, float& out) {
  54. return val.IsNumber() ? out = static_cast<float>(val.GetDouble()), true : false;
  55. }};
  56. template<unsigned int N> struct ReadHelper<float[N]> { static bool Read(Value& val, float (&out)[N]) {
  57. if (!val.IsArray() || val.Size() != N) return false;
  58. for (unsigned int i = 0; i < N; ++i) {
  59. if (val[i].IsNumber())
  60. out[i] = static_cast<float>(val[i].GetDouble());
  61. }
  62. return true;
  63. }};
  64. template<> struct ReadHelper<const char*> { static bool Read(Value& val, const char*& out) {
  65. return val.IsString() ? (out = val.GetString(), true) : false;
  66. }};
  67. template<> struct ReadHelper<std::string> { static bool Read(Value& val, std::string& out) {
  68. return val.IsString() ? (out = std::string(val.GetString(), val.GetStringLength()), true) : false;
  69. }};
  70. template<class T> struct ReadHelper< Nullable<T> > { static bool Read(Value& val, Nullable<T>& out) {
  71. return out.isPresent = ReadHelper<T>::Read(val, out.value);
  72. }};
  73. template<class T>
  74. inline static bool ReadValue(Value& val, T& out)
  75. {
  76. return ReadHelper<T>::Read(val, out);
  77. }
  78. template<class T>
  79. inline static bool ReadMember(Value& obj, const char* id, T& out)
  80. {
  81. Value::MemberIterator it = obj.FindMember(id);
  82. if (it != obj.MemberEnd()) {
  83. return ReadHelper<T>::Read(it->value, out);
  84. }
  85. return false;
  86. }
  87. template<class T>
  88. inline static T MemberOrDefault(Value& obj, const char* id, T defaultValue)
  89. {
  90. T out;
  91. return ReadMember(obj, id, out) ? out : defaultValue;
  92. }
  93. inline Value* FindMember(Value& val, const char* id)
  94. {
  95. Value::MemberIterator it = val.FindMember(id);
  96. return (it != val.MemberEnd()) ? &it->value : 0;
  97. }
  98. inline Value* FindString(Value& val, const char* id)
  99. {
  100. Value::MemberIterator it = val.FindMember(id);
  101. return (it != val.MemberEnd() && it->value.IsString()) ? &it->value : 0;
  102. }
  103. inline Value* FindArray(Value& val, const char* id)
  104. {
  105. Value::MemberIterator it = val.FindMember(id);
  106. return (it != val.MemberEnd() && it->value.IsArray()) ? &it->value : 0;
  107. }
  108. inline Value* FindObject(Value& val, const char* id)
  109. {
  110. Value::MemberIterator it = val.FindMember(id);
  111. return (it != val.MemberEnd() && it->value.IsObject()) ? &it->value : 0;
  112. }
  113. }
  114. //
  115. // LazyDict methods
  116. //
  117. template<class T>
  118. inline LazyDict<T>::LazyDict(Asset& asset, const char* dictId, const char* extId)
  119. : mDictId(dictId), mExtId(extId), mDict(0), mAsset(asset)
  120. {
  121. asset.mDicts.push_back(this); // register to the list of dictionaries
  122. }
  123. template<class T>
  124. inline LazyDict<T>::~LazyDict()
  125. {
  126. for (size_t i = 0; i < mObjs.size(); ++i) {
  127. delete mObjs[i];
  128. }
  129. }
  130. template<class T>
  131. inline void LazyDict<T>::AttachToDocument(Document& doc)
  132. {
  133. Value* container = 0;
  134. if (mExtId) {
  135. if (Value* exts = FindObject(doc, "extensions")) {
  136. container = FindObject(*exts, mExtId);
  137. }
  138. }
  139. else {
  140. container = &doc;
  141. }
  142. if (container) {
  143. mDict = FindObject(*container, mDictId);
  144. }
  145. }
  146. template<class T>
  147. inline void LazyDict<T>::DetachFromDocument()
  148. {
  149. mDict = 0;
  150. }
  151. template<class T>
  152. Ref<T> LazyDict<T>::Get(unsigned int i)
  153. {
  154. return Ref<T>(mObjs, i);
  155. }
  156. template<class T>
  157. Ref<T> LazyDict<T>::Get(const char* id)
  158. {
  159. id = T::TranslateId(mAsset, id);
  160. typename Dict::iterator it = mObjsById.find(id);
  161. if (it != mObjsById.end()) { // already created?
  162. return Ref<T>(mObjs, it->second);
  163. }
  164. // read it from the JSON object
  165. if (!mDict) {
  166. throw DeadlyImportError("GLTF: Missing section \"" + std::string(mDictId) + "\"");
  167. }
  168. Value::MemberIterator obj = mDict->FindMember(id);
  169. if (obj == mDict->MemberEnd()) {
  170. throw DeadlyImportError("GLTF: Missing object with id \"" + std::string(id) + "\" in \"" + mDictId + "\"");
  171. }
  172. if (!obj->value.IsObject()) {
  173. throw DeadlyImportError("GLTF: Object with id \"" + std::string(id) + "\" is not a JSON object");
  174. }
  175. // create an instance of the given type
  176. T* inst = new T();
  177. inst->id = id;
  178. ReadMember(obj->value, "name", inst->name);
  179. inst->Read(obj->value, mAsset);
  180. return Add(inst);
  181. }
  182. template<class T>
  183. Ref<T> LazyDict<T>::Add(T* obj)
  184. {
  185. unsigned int idx = unsigned(mObjs.size());
  186. mObjs.push_back(obj);
  187. mObjsById[obj->id] = idx;
  188. mAsset.mUsedIds[obj->id] = true;
  189. return Ref<T>(mObjs, idx);
  190. }
  191. template<class T>
  192. Ref<T> LazyDict<T>::Create(const char* id)
  193. {
  194. Asset::IdMap::iterator it = mAsset.mUsedIds.find(id);
  195. if (it != mAsset.mUsedIds.end()) {
  196. throw DeadlyImportError("GLTF: two objects with the same ID exist");
  197. }
  198. T* inst = new T();
  199. inst->id = id;
  200. return Add(inst);
  201. }
  202. //
  203. // glTF dictionary objects methods
  204. //
  205. inline Buffer::Buffer()
  206. : byteLength(0), type(Type_arraybuffer), EncodedRegion_Current(nullptr), mIsSpecial(false)
  207. { }
  208. inline Buffer::~Buffer()
  209. {
  210. for(SEncodedRegion* reg : EncodedRegion_List) delete reg;
  211. }
  212. inline const char* Buffer::TranslateId(Asset& r, const char* id)
  213. {
  214. // Compatibility with old spec
  215. if (r.extensionsUsed.KHR_binary_glTF && strcmp(id, "KHR_binary_glTF") == 0) {
  216. return "binary_glTF";
  217. }
  218. return id;
  219. }
  220. inline void Buffer::Read(Value& obj, Asset& r)
  221. {
  222. size_t statedLength = MemberOrDefault<size_t>(obj, "byteLength", 0);
  223. byteLength = statedLength;
  224. Value* it = FindString(obj, "uri");
  225. if (!it) {
  226. if (statedLength > 0) {
  227. throw DeadlyImportError("GLTF: buffer with non-zero length missing the \"uri\" attribute");
  228. }
  229. return;
  230. }
  231. const char* uri = it->GetString();
  232. Util::DataURI dataURI;
  233. if (ParseDataURI(uri, it->GetStringLength(), dataURI)) {
  234. if (dataURI.base64) {
  235. uint8_t* data = 0;
  236. this->byteLength = Util::DecodeBase64(dataURI.data, dataURI.dataLength, data);
  237. this->mData.reset(data);
  238. if (statedLength > 0 && this->byteLength != statedLength) {
  239. throw DeadlyImportError("GLTF: buffer \"" + id + "\", expected " + to_string(statedLength) +
  240. " bytes, but found " + to_string(dataURI.dataLength));
  241. }
  242. }
  243. else { // assume raw data
  244. if (statedLength != dataURI.dataLength) {
  245. throw DeadlyImportError("GLTF: buffer \"" + id + "\", expected " + to_string(statedLength) +
  246. " bytes, but found " + to_string(dataURI.dataLength));
  247. }
  248. this->mData.reset(new uint8_t[dataURI.dataLength]);
  249. memcpy( this->mData.get(), dataURI.data, dataURI.dataLength );
  250. }
  251. }
  252. else { // Local file
  253. if (byteLength > 0) {
  254. IOStream* file = r.OpenFile(uri, "rb");
  255. if (file) {
  256. bool ok = LoadFromStream(*file, byteLength);
  257. delete file;
  258. if (!ok)
  259. throw DeadlyImportError("GLTF: error while reading referenced file \"" + std::string(uri) + "\"" );
  260. }
  261. else {
  262. throw DeadlyImportError("GLTF: could not open referenced file \"" + std::string(uri) + "\"");
  263. }
  264. }
  265. }
  266. }
  267. inline bool Buffer::LoadFromStream(IOStream& stream, size_t length, size_t baseOffset)
  268. {
  269. byteLength = length ? length : stream.FileSize();
  270. if (baseOffset) {
  271. stream.Seek(baseOffset, aiOrigin_SET);
  272. }
  273. mData.reset(new uint8_t[byteLength]);
  274. if (stream.Read(mData.get(), byteLength, 1) != 1) {
  275. return false;
  276. }
  277. return true;
  278. }
  279. inline void Buffer::EncodedRegion_Mark(const size_t pOffset, const size_t pEncodedData_Length, uint8_t* pDecodedData, const size_t pDecodedData_Length, const std::string& pID)
  280. {
  281. // Check pointer to data
  282. if(pDecodedData == nullptr) throw DeadlyImportError("GLTF: for marking encoded region pointer to decoded data must be provided.");
  283. // Check offset
  284. if(pOffset > byteLength)
  285. {
  286. const uint8_t val_size = 32;
  287. char val[val_size];
  288. ai_snprintf(val, val_size, "%llu", (long long)pOffset);
  289. throw DeadlyImportError(std::string("GLTF: incorrect offset value (") + val + ") for marking encoded region.");
  290. }
  291. // Check length
  292. if((pOffset + pEncodedData_Length) > byteLength)
  293. {
  294. const uint8_t val_size = 64;
  295. char val[val_size];
  296. ai_snprintf(val, val_size, "%llu, %llu", (long long)pOffset, (long long)pEncodedData_Length);
  297. throw DeadlyImportError(std::string("GLTF: encoded region with offset/length (") + val + ") is out of range.");
  298. }
  299. // Add new region
  300. EncodedRegion_List.push_back(new SEncodedRegion(pOffset, pEncodedData_Length, pDecodedData, pDecodedData_Length, pID));
  301. // And set new value for "byteLength"
  302. byteLength += (pDecodedData_Length - pEncodedData_Length);
  303. }
  304. inline void Buffer::EncodedRegion_SetCurrent(const std::string& pID)
  305. {
  306. if((EncodedRegion_Current != nullptr) && (EncodedRegion_Current->ID == pID)) return;
  307. for(SEncodedRegion* reg : EncodedRegion_List)
  308. {
  309. if(reg->ID == pID)
  310. {
  311. EncodedRegion_Current = reg;
  312. return;
  313. }
  314. }
  315. throw DeadlyImportError("GLTF: EncodedRegion with ID: \"" + pID + "\" not found.");
  316. }
  317. inline bool Buffer::ReplaceData(const size_t pBufferData_Offset, const size_t pBufferData_Count, const uint8_t* pReplace_Data, const size_t pReplace_Count)
  318. {
  319. const size_t new_data_size = byteLength + pReplace_Count - pBufferData_Count;
  320. uint8_t* new_data;
  321. if((pBufferData_Count == 0) || (pReplace_Count == 0) || (pReplace_Data == nullptr)) return false;
  322. new_data = new uint8_t[new_data_size];
  323. // Copy data which place before replacing part.
  324. memcpy(new_data, mData.get(), pBufferData_Offset);
  325. // Copy new data.
  326. memcpy(&new_data[pBufferData_Offset], pReplace_Data, pReplace_Count);
  327. // Copy data which place after replacing part.
  328. memcpy(&new_data[pBufferData_Offset + pReplace_Count], &mData.get()[pBufferData_Offset + pBufferData_Count], pBufferData_Offset);
  329. // Apply new data
  330. mData.reset(new_data);
  331. byteLength = new_data_size;
  332. return true;
  333. }
  334. inline size_t Buffer::AppendData(uint8_t* data, size_t length)
  335. {
  336. size_t offset = this->byteLength;
  337. Grow(length);
  338. memcpy(mData.get() + offset, data, length);
  339. return offset;
  340. }
  341. inline void Buffer::Grow(size_t amount)
  342. {
  343. if (amount <= 0) return;
  344. uint8_t* b = new uint8_t[byteLength + amount];
  345. if (mData) memcpy(b, mData.get(), byteLength);
  346. mData.reset(b);
  347. byteLength += amount;
  348. }
  349. //
  350. // struct BufferView
  351. //
  352. inline void BufferView::Read(Value& obj, Asset& r)
  353. {
  354. const char* bufferId = MemberOrDefault<const char*>(obj, "buffer", 0);
  355. if (bufferId) {
  356. buffer = r.buffers.Get(bufferId);
  357. }
  358. byteOffset = MemberOrDefault(obj, "byteOffset", 0u);
  359. byteLength = MemberOrDefault(obj, "byteLength", 0u);
  360. }
  361. //
  362. // struct Accessor
  363. //
  364. inline void Accessor::Read(Value& obj, Asset& r)
  365. {
  366. const char* bufferViewId = MemberOrDefault<const char*>(obj, "bufferView", 0);
  367. if (bufferViewId) {
  368. bufferView = r.bufferViews.Get(bufferViewId);
  369. }
  370. byteOffset = MemberOrDefault(obj, "byteOffset", 0u);
  371. byteStride = MemberOrDefault(obj, "byteStride", 0u);
  372. componentType = MemberOrDefault(obj, "componentType", ComponentType_BYTE);
  373. count = MemberOrDefault(obj, "count", 0u);
  374. const char* typestr;
  375. type = ReadMember(obj, "type", typestr) ? AttribType::FromString(typestr) : AttribType::SCALAR;
  376. }
  377. inline unsigned int Accessor::GetNumComponents()
  378. {
  379. return AttribType::GetNumComponents(type);
  380. }
  381. inline unsigned int Accessor::GetBytesPerComponent()
  382. {
  383. return int(ComponentTypeSize(componentType));
  384. }
  385. inline unsigned int Accessor::GetElementSize()
  386. {
  387. return GetNumComponents() * GetBytesPerComponent();
  388. }
  389. inline uint8_t* Accessor::GetPointer()
  390. {
  391. if (!bufferView || !bufferView->buffer) return 0;
  392. uint8_t* basePtr = bufferView->buffer->GetPointer();
  393. if (!basePtr) return 0;
  394. size_t offset = byteOffset + bufferView->byteOffset;
  395. // Check if region is encoded.
  396. if(bufferView->buffer->EncodedRegion_Current != nullptr)
  397. {
  398. const size_t begin = bufferView->buffer->EncodedRegion_Current->Offset;
  399. const size_t end = begin + bufferView->buffer->EncodedRegion_Current->DecodedData_Length;
  400. if((offset >= begin) && (offset < end))
  401. return &bufferView->buffer->EncodedRegion_Current->DecodedData[offset - begin];
  402. }
  403. return basePtr + offset;
  404. }
  405. namespace {
  406. inline void CopyData(size_t count,
  407. const uint8_t* src, size_t src_stride,
  408. uint8_t* dst, size_t dst_stride)
  409. {
  410. if (src_stride == dst_stride) {
  411. memcpy(dst, src, count * src_stride);
  412. }
  413. else {
  414. size_t sz = std::min(src_stride, dst_stride);
  415. for (size_t i = 0; i < count; ++i) {
  416. memcpy(dst, src, sz);
  417. if (sz < dst_stride) {
  418. memset(dst + sz, 0, dst_stride - sz);
  419. }
  420. src += src_stride;
  421. dst += dst_stride;
  422. }
  423. }
  424. }
  425. }
  426. template<class T>
  427. bool Accessor::ExtractData(T*& outData)
  428. {
  429. uint8_t* data = GetPointer();
  430. if (!data) return false;
  431. const size_t elemSize = GetElementSize();
  432. const size_t totalSize = elemSize * count;
  433. const size_t stride = byteStride ? byteStride : elemSize;
  434. const size_t targetElemSize = sizeof(T);
  435. ai_assert(elemSize <= targetElemSize);
  436. ai_assert(count*stride <= bufferView->byteLength);
  437. outData = new T[count];
  438. if (stride == elemSize && targetElemSize == elemSize) {
  439. memcpy(outData, data, totalSize);
  440. }
  441. else {
  442. for (size_t i = 0; i < count; ++i) {
  443. memcpy(outData + i, data + i*stride, elemSize);
  444. }
  445. }
  446. return true;
  447. }
  448. inline void Accessor::WriteData(size_t count, const void* src_buffer, size_t src_stride)
  449. {
  450. uint8_t* buffer_ptr = bufferView->buffer->GetPointer();
  451. size_t offset = byteOffset + bufferView->byteOffset;
  452. size_t dst_stride = GetNumComponents() * GetBytesPerComponent();
  453. const uint8_t* src = reinterpret_cast<const uint8_t*>(src_buffer);
  454. uint8_t* dst = reinterpret_cast< uint8_t*>(buffer_ptr + offset);
  455. ai_assert(dst + count*dst_stride <= buffer_ptr + bufferView->buffer->byteLength);
  456. CopyData(count, src, src_stride, dst, dst_stride);
  457. }
  458. inline Accessor::Indexer::Indexer(Accessor& acc)
  459. : accessor(acc)
  460. , data(acc.GetPointer())
  461. , elemSize(acc.GetElementSize())
  462. , stride(acc.byteStride ? acc.byteStride : elemSize)
  463. {
  464. }
  465. //! Accesses the i-th value as defined by the accessor
  466. template<class T>
  467. T Accessor::Indexer::GetValue(int i)
  468. {
  469. ai_assert(data);
  470. ai_assert(i*stride < accessor.bufferView->byteLength);
  471. T value = T();
  472. memcpy(&value, data + i*stride, elemSize);
  473. //value >>= 8 * (sizeof(T) - elemSize);
  474. return value;
  475. }
  476. inline Image::Image()
  477. : width(0)
  478. , height(0)
  479. , mData(0)
  480. , mDataLength(0)
  481. {
  482. }
  483. inline void Image::Read(Value& obj, Asset& r)
  484. {
  485. // Check for extensions first (to detect binary embedded data)
  486. if (Value* extensions = FindObject(obj, "extensions")) {
  487. if (r.extensionsUsed.KHR_binary_glTF) {
  488. if (Value* ext = FindObject(*extensions, "KHR_binary_glTF")) {
  489. width = MemberOrDefault(*ext, "width", 0);
  490. height = MemberOrDefault(*ext, "height", 0);
  491. ReadMember(*ext, "mimeType", mimeType);
  492. const char* bufferViewId;
  493. if (ReadMember(*ext, "bufferView", bufferViewId)) {
  494. Ref<BufferView> bv = r.bufferViews.Get(bufferViewId);
  495. if (bv) {
  496. mDataLength = bv->byteLength;
  497. mData = new uint8_t[mDataLength];
  498. memcpy(mData, bv->buffer->GetPointer() + bv->byteOffset, mDataLength);
  499. }
  500. }
  501. }
  502. }
  503. }
  504. if (!mDataLength) {
  505. if (Value* uri = FindString(obj, "uri")) {
  506. const char* uristr = uri->GetString();
  507. Util::DataURI dataURI;
  508. if (ParseDataURI(uristr, uri->GetStringLength(), dataURI)) {
  509. mimeType = dataURI.mediaType;
  510. if (dataURI.base64) {
  511. mDataLength = Util::DecodeBase64(dataURI.data, dataURI.dataLength, mData);
  512. }
  513. }
  514. else {
  515. this->uri = uristr;
  516. }
  517. }
  518. }
  519. }
  520. inline uint8_t* Image::StealData()
  521. {
  522. uint8_t* data = mData;
  523. mDataLength = 0;
  524. mData = 0;
  525. return data;
  526. }
  527. inline void Image::SetData(uint8_t* data, size_t length, Asset& r)
  528. {
  529. Ref<Buffer> b = r.GetBodyBuffer();
  530. if (b) { // binary file: append to body
  531. std::string bvId = r.FindUniqueID(this->id, "imgdata");
  532. bufferView = r.bufferViews.Create(bvId);
  533. bufferView->buffer = b;
  534. bufferView->byteLength = length;
  535. bufferView->byteOffset = b->AppendData(data, length);
  536. }
  537. else { // text file: will be stored as a data uri
  538. this->mData = data;
  539. this->mDataLength = length;
  540. }
  541. }
  542. inline void Sampler::Read(Value& obj, Asset& r)
  543. {
  544. SetDefaults();
  545. ReadMember(obj, "magFilter", magFilter);
  546. ReadMember(obj, "minFilter", minFilter);
  547. ReadMember(obj, "wrapS", wrapS);
  548. ReadMember(obj, "wrapT", wrapT);
  549. }
  550. inline void Sampler::SetDefaults()
  551. {
  552. magFilter = SamplerMagFilter_Linear;
  553. minFilter = SamplerMinFilter_Linear;
  554. wrapS = SamplerWrap_Repeat;
  555. wrapT = SamplerWrap_Repeat;
  556. }
  557. inline void Texture::Read(Value& obj, Asset& r)
  558. {
  559. const char* sourcestr;
  560. if (ReadMember(obj, "source", sourcestr)) {
  561. source = r.images.Get(sourcestr);
  562. }
  563. const char* samplerstr;
  564. if (ReadMember(obj, "sampler", samplerstr)) {
  565. sampler = r.samplers.Get(samplerstr);
  566. }
  567. }
  568. namespace {
  569. inline void ReadMaterialProperty(Asset& r, Value& vals, const char* propName, TexProperty& out)
  570. {
  571. if (Value* prop = FindMember(vals, propName)) {
  572. if (prop->IsString()) {
  573. out.texture = r.textures.Get(prop->GetString());
  574. }
  575. else {
  576. ReadValue(*prop, out.color);
  577. }
  578. }
  579. }
  580. }
  581. inline void Material::Read(Value& material, Asset& r)
  582. {
  583. SetDefaults();
  584. if (Value* values = FindObject(material, "values")) {
  585. ReadMaterialProperty(r, *values, "ambient", this->ambient);
  586. ReadMaterialProperty(r, *values, "diffuse", this->diffuse);
  587. ReadMaterialProperty(r, *values, "specular", this->specular);
  588. ReadMember(*values, "transparency", transparency);
  589. ReadMember(*values, "shininess", shininess);
  590. }
  591. if (Value* extensions = FindObject(material, "extensions")) {
  592. if (r.extensionsUsed.KHR_materials_common) {
  593. if (Value* ext = FindObject(*extensions, "KHR_materials_common")) {
  594. if (Value* tnq = FindString(*ext, "technique")) {
  595. const char* t = tnq->GetString();
  596. if (strcmp(t, "BLINN") == 0) technique = Technique_BLINN;
  597. else if (strcmp(t, "PHONG") == 0) technique = Technique_PHONG;
  598. else if (strcmp(t, "LAMBERT") == 0) technique = Technique_LAMBERT;
  599. else if (strcmp(t, "CONSTANT") == 0) technique = Technique_CONSTANT;
  600. }
  601. if (Value* values = FindObject(*ext, "values")) {
  602. ReadMaterialProperty(r, *values, "ambient", this->ambient);
  603. ReadMaterialProperty(r, *values, "diffuse", this->diffuse);
  604. ReadMaterialProperty(r, *values, "specular", this->specular);
  605. ReadMember(*values, "doubleSided", doubleSided);
  606. ReadMember(*values, "transparent", transparent);
  607. ReadMember(*values, "transparency", transparency);
  608. ReadMember(*values, "shininess", shininess);
  609. }
  610. }
  611. }
  612. }
  613. }
  614. namespace {
  615. void SetVector(vec4& v, float x, float y, float z, float w)
  616. { v[0] = x; v[1] = y; v[2] = z; v[3] = w; }
  617. }
  618. inline void Material::SetDefaults()
  619. {
  620. SetVector(ambient.color, 0, 0, 0, 1);
  621. SetVector(diffuse.color, 0, 0, 0, 1);
  622. SetVector(specular.color, 0, 0, 0, 1);
  623. SetVector(emission.color, 0, 0, 0, 1);
  624. doubleSided = false;
  625. transparent = false;
  626. transparency = 1.0;
  627. shininess = 0.0;
  628. technique = Technique_undefined;
  629. }
  630. namespace {
  631. template<int N>
  632. inline int Compare(const char* attr, const char (&str)[N]) {
  633. return (strncmp(attr, str, N - 1) == 0) ? N - 1 : 0;
  634. }
  635. inline bool GetAttribVector(Mesh::Primitive& p, const char* attr, Mesh::AccessorList*& v, int& pos)
  636. {
  637. if ((pos = Compare(attr, "POSITION"))) {
  638. v = &(p.attributes.position);
  639. }
  640. else if ((pos = Compare(attr, "NORMAL"))) {
  641. v = &(p.attributes.normal);
  642. }
  643. else if ((pos = Compare(attr, "TEXCOORD"))) {
  644. v = &(p.attributes.texcoord);
  645. }
  646. else if ((pos = Compare(attr, "COLOR"))) {
  647. v = &(p.attributes.color);
  648. }
  649. else if ((pos = Compare(attr, "JOINT"))) {
  650. v = &(p.attributes.joint);
  651. }
  652. else if ((pos = Compare(attr, "JOINTMATRIX"))) {
  653. v = &(p.attributes.jointmatrix);
  654. }
  655. else if ((pos = Compare(attr, "WEIGHT"))) {
  656. v = &(p.attributes.weight);
  657. }
  658. else return false;
  659. return true;
  660. }
  661. }
  662. inline void Mesh::Read(Value& pJSON_Object, Asset& pAsset_Root)
  663. {
  664. /****************** Mesh primitives ******************/
  665. if (Value* primitives = FindArray(pJSON_Object, "primitives")) {
  666. this->primitives.resize(primitives->Size());
  667. for (unsigned int i = 0; i < primitives->Size(); ++i) {
  668. Value& primitive = (*primitives)[i];
  669. Primitive& prim = this->primitives[i];
  670. prim.mode = MemberOrDefault(primitive, "mode", PrimitiveMode_TRIANGLES);
  671. if (Value* attrs = FindObject(primitive, "attributes")) {
  672. for (Value::MemberIterator it = attrs->MemberBegin(); it != attrs->MemberEnd(); ++it) {
  673. if (!it->value.IsString()) continue;
  674. const char* attr = it->name.GetString();
  675. // Valid attribute semantics include POSITION, NORMAL, TEXCOORD, COLOR, JOINT, JOINTMATRIX,
  676. // and WEIGHT.Attribute semantics can be of the form[semantic]_[set_index], e.g., TEXCOORD_0, TEXCOORD_1, etc.
  677. int undPos = 0;
  678. Mesh::AccessorList* vec = 0;
  679. if (GetAttribVector(prim, attr, vec, undPos)) {
  680. size_t idx = (attr[undPos] == '_') ? atoi(attr + undPos + 1) : 0;
  681. if ((*vec).size() <= idx) (*vec).resize(idx + 1);
  682. (*vec)[idx] = pAsset_Root.accessors.Get(it->value.GetString());
  683. }
  684. }
  685. }
  686. if (Value* indices = FindString(primitive, "indices")) {
  687. prim.indices = pAsset_Root.accessors.Get(indices->GetString());
  688. }
  689. if (Value* material = FindString(primitive, "material")) {
  690. prim.material = pAsset_Root.materials.Get(material->GetString());
  691. }
  692. }
  693. }
  694. /****************** Mesh extensions ******************/
  695. Value* json_extensions = FindObject(pJSON_Object, "extensions");
  696. if(json_extensions == nullptr) goto mr_skip_extensions;
  697. for(Value::MemberIterator it_memb = json_extensions->MemberBegin(); it_memb != json_extensions->MemberEnd(); it_memb++)
  698. {
  699. #ifdef ASSIMP_IMPORTER_GLTF_USE_OPEN3DGC
  700. if(it_memb->name.GetString() == std::string("Open3DGC-compression"))
  701. {
  702. // Search for compressed data.
  703. // Compressed data contain description of part of "buffer" which is encoded. This part must be decoded and
  704. // new data will replace old encoded part by request. In fact \"compressedData\" is kind of "accessor" structure.
  705. Value* comp_data = FindObject(it_memb->value, "compressedData");
  706. if(comp_data == nullptr) throw DeadlyImportError("GLTF: \"Open3DGC-compression\" must has \"compressedData\".");
  707. DefaultLogger::get()->info("GLTF: Decompressing Open3DGC data.");
  708. /************** Read data from JSON-document **************/
  709. #define MESH_READ_COMPRESSEDDATA_MEMBER(pFieldName, pOut) \
  710. if(!ReadMember(*comp_data, pFieldName, pOut)) \
  711. { \
  712. throw DeadlyImportError(std::string("GLTF: \"compressedData\" must has \"") + pFieldName + "\"."); \
  713. }
  714. const char* mode_str;
  715. const char* type_str;
  716. ComponentType component_type;
  717. SCompression_Open3DGC* ext_o3dgc = new SCompression_Open3DGC;
  718. MESH_READ_COMPRESSEDDATA_MEMBER("buffer", ext_o3dgc->Buffer);
  719. MESH_READ_COMPRESSEDDATA_MEMBER("byteOffset", ext_o3dgc->Offset);
  720. MESH_READ_COMPRESSEDDATA_MEMBER("componentType", component_type);
  721. MESH_READ_COMPRESSEDDATA_MEMBER("type", type_str);
  722. MESH_READ_COMPRESSEDDATA_MEMBER("count", ext_o3dgc->Count);
  723. MESH_READ_COMPRESSEDDATA_MEMBER("mode", mode_str);
  724. MESH_READ_COMPRESSEDDATA_MEMBER("indicesCount", ext_o3dgc->IndicesCount);
  725. MESH_READ_COMPRESSEDDATA_MEMBER("verticesCount", ext_o3dgc->VerticesCount);
  726. #undef MESH_READ_COMPRESSEDDATA_MEMBER
  727. // Check some values
  728. if(strcmp(type_str, "SCALAR")) throw DeadlyImportError("GLTF: only \"SCALAR\" type is supported for compressed data.");
  729. if(component_type != ComponentType_UNSIGNED_BYTE) throw DeadlyImportError("GLTF: only \"UNSIGNED_BYTE\" component type is supported for compressed data.");
  730. // Set read/write data mode.
  731. if(strcmp(mode_str, "binary") == 0)
  732. ext_o3dgc->Binary = true;
  733. else if(strcmp(mode_str, "ascii") == 0)
  734. ext_o3dgc->Binary = false;
  735. else
  736. throw DeadlyImportError(std::string("GLTF: for compressed data supported modes is: \"ascii\", \"binary\". Not the: \"") + mode_str + "\".");
  737. /************************ Decoding ************************/
  738. Decode_O3DGC(*ext_o3dgc, pAsset_Root);
  739. Extension.push_back(ext_o3dgc);// store info in mesh extensions list.
  740. }// if(it_memb->name.GetString() == "Open3DGC-compression")
  741. else
  742. #endif
  743. {
  744. throw DeadlyImportError(std::string("GLTF: Unknown mesh extension: \"") + it_memb->name.GetString() + "\".");
  745. }
  746. }// for(Value::MemberIterator it_memb = json_extensions->MemberBegin(); it_memb != json_extensions->MemberEnd(); json_extensions++)
  747. mr_skip_extensions:
  748. return;// After label some operators must be present.
  749. }
  750. #ifdef ASSIMP_IMPORTER_GLTF_USE_OPEN3DGC
  751. inline void Mesh::Decode_O3DGC(const SCompression_Open3DGC& pCompression_Open3DGC, Asset& pAsset_Root)
  752. {
  753. typedef unsigned short IndicesType;///< \sa glTFExporter::ExportMeshes.
  754. o3dgc::SC3DMCDecoder<IndicesType> decoder;
  755. o3dgc::IndexedFaceSet<IndicesType> ifs;
  756. o3dgc::BinaryStream bstream;
  757. uint8_t* decoded_data;
  758. size_t decoded_data_size = 0;
  759. Ref<Buffer> buf = pAsset_Root.buffers.Get(pCompression_Open3DGC.Buffer);
  760. // Read data from buffer and place it in BinaryStream for decoder.
  761. // Just "Count" because always is used type equivalent to uint8_t.
  762. bstream.LoadFromBuffer(&buf->GetPointer()[pCompression_Open3DGC.Offset], static_cast<unsigned long>(pCompression_Open3DGC.Count));
  763. // After decoding header we can get size of primitives.
  764. if(decoder.DecodeHeader(ifs, bstream) != o3dgc::O3DGC_OK) throw DeadlyImportError("GLTF: can not decode Open3DGC header.");
  765. /****************** Get sizes of arrays and check sizes ******************/
  766. // Note. See "Limitations for meshes when using Open3DGC-compression".
  767. // Indices
  768. size_t size_coordindex = ifs.GetNCoordIndex() * 3;// See float attributes note.
  769. if(primitives[0].indices->count != size_coordindex)
  770. throw DeadlyImportError("GLTF: Open3DGC. Compressed indices count (" + std::to_string(size_coordindex) +
  771. ") not equal to uncompressed (" + std::to_string(primitives[0].indices->count) + ").");
  772. size_coordindex *= sizeof(IndicesType);
  773. // Coordinates
  774. size_t size_coord = ifs.GetNCoord();// See float attributes note.
  775. if(primitives[0].attributes.position[0]->count != size_coord)
  776. throw DeadlyImportError("GLTF: Open3DGC. Compressed positions count (" + std::to_string(size_coord) +
  777. ") not equal to uncompressed (" + std::to_string(primitives[0].attributes.position[0]->count) + ").");
  778. size_coord *= 3 * sizeof(float);
  779. // Normals
  780. size_t size_normal = ifs.GetNNormal();// See float attributes note.
  781. if(primitives[0].attributes.normal[0]->count != size_normal)
  782. throw DeadlyImportError("GLTF: Open3DGC. Compressed normals count (" + std::to_string(size_normal) +
  783. ") not equal to uncompressed (" + std::to_string(primitives[0].attributes.normal[0]->count) + ").");
  784. size_normal *= 3 * sizeof(float);
  785. // Additional attributes.
  786. std::vector<size_t> size_floatattr;
  787. std::vector<size_t> size_intattr;
  788. size_floatattr.resize(ifs.GetNumFloatAttributes());
  789. size_intattr.resize(ifs.GetNumIntAttributes());
  790. decoded_data_size = size_coordindex + size_coord + size_normal;
  791. for(size_t idx = 0, idx_end = size_floatattr.size(), idx_texcoord = 0; idx < idx_end; idx++)
  792. {
  793. // size = number_of_elements * components_per_element * size_of_component.
  794. // Note. But as you can see above, at first we are use this variable in meaning "count". After checking count of objects...
  795. size_t tval = ifs.GetNFloatAttribute(static_cast<unsigned long>(idx));
  796. switch(ifs.GetFloatAttributeType(static_cast<unsigned long>(idx)))
  797. {
  798. case o3dgc::O3DGC_IFS_FLOAT_ATTRIBUTE_TYPE_TEXCOORD:
  799. // Check situation when encoded data contain texture coordinates but primitive not.
  800. if(idx_texcoord < primitives[0].attributes.texcoord.size())
  801. {
  802. if(primitives[0].attributes.texcoord[idx]->count != tval)
  803. throw DeadlyImportError("GLTF: Open3DGC. Compressed texture coordinates count (" + std::to_string(tval) +
  804. ") not equal to uncompressed (" + std::to_string(primitives[0].attributes.texcoord[idx]->count) + ").");
  805. idx_texcoord++;
  806. }
  807. else
  808. {
  809. ifs.SetNFloatAttribute(static_cast<unsigned long>(idx), 0ul);// Disable decoding this attribute.
  810. }
  811. break;
  812. default:
  813. throw DeadlyImportError("GLTF: Open3DGC. Unsupported type of float attribute: " + to_string(ifs.GetFloatAttributeType(static_cast<unsigned long>(idx))));
  814. }
  815. tval *= ifs.GetFloatAttributeDim(static_cast<unsigned long>(idx)) * sizeof(o3dgc::Real);// After checking count of objects we can get size of array.
  816. size_floatattr[idx] = tval;
  817. decoded_data_size += tval;
  818. }
  819. for(size_t idx = 0, idx_end = size_intattr.size(); idx < idx_end; idx++)
  820. {
  821. // size = number_of_elements * components_per_element * size_of_component. See float attributes note.
  822. size_t tval = ifs.GetNIntAttribute(static_cast<unsigned long>(idx));
  823. switch( ifs.GetIntAttributeType(static_cast<unsigned long>(idx) ) )
  824. {
  825. case o3dgc::O3DGC_IFS_INT_ATTRIBUTE_TYPE_UNKOWN:
  826. case o3dgc::O3DGC_IFS_INT_ATTRIBUTE_TYPE_INDEX:
  827. case o3dgc::O3DGC_IFS_INT_ATTRIBUTE_TYPE_JOINT_ID:
  828. case o3dgc::O3DGC_IFS_INT_ATTRIBUTE_TYPE_INDEX_BUFFER_ID:
  829. break;
  830. default:
  831. throw DeadlyImportError("GLTF: Open3DGC. Unsupported type of int attribute: " + to_string(ifs.GetIntAttributeType(static_cast<unsigned long>(idx))));
  832. }
  833. tval *= ifs.GetIntAttributeDim(static_cast<unsigned long>(idx)) * sizeof(long);// See float attributes note.
  834. size_intattr[idx] = tval;
  835. decoded_data_size += tval;
  836. }
  837. // Create array for decoded data.
  838. decoded_data = new uint8_t[decoded_data_size];
  839. /****************** Set right array regions for decoder ******************/
  840. auto get_buf_offset = [](Ref<Accessor>& pAccessor) -> size_t { return pAccessor->byteOffset + pAccessor->bufferView->byteOffset; };
  841. // Indices
  842. ifs.SetCoordIndex((IndicesType* const)(decoded_data + get_buf_offset(primitives[0].indices)));
  843. // Coordinates
  844. ifs.SetCoord((o3dgc::Real* const)(decoded_data + get_buf_offset(primitives[0].attributes.position[0])));
  845. // Normals
  846. if(size_normal)
  847. {
  848. ifs.SetNormal((o3dgc::Real* const)(decoded_data + get_buf_offset(primitives[0].attributes.normal[0])));
  849. }
  850. for(size_t idx = 0, idx_end = size_floatattr.size(), idx_texcoord = 0; idx < idx_end; idx++)
  851. {
  852. switch(ifs.GetFloatAttributeType(static_cast<unsigned long>(idx)))
  853. {
  854. case o3dgc::O3DGC_IFS_FLOAT_ATTRIBUTE_TYPE_TEXCOORD:
  855. if(idx_texcoord < primitives[0].attributes.texcoord.size())
  856. {
  857. // See above about absent attributes.
  858. ifs.SetFloatAttribute(static_cast<unsigned long>(idx), (o3dgc::Real* const)(decoded_data + get_buf_offset(primitives[0].attributes.texcoord[idx])));
  859. idx_texcoord++;
  860. }
  861. break;
  862. default:
  863. throw DeadlyImportError("GLTF: Open3DGC. Unsupported type of float attribute: " + to_string(ifs.GetFloatAttributeType(static_cast<unsigned long>(idx))));
  864. }
  865. }
  866. for(size_t idx = 0, idx_end = size_intattr.size(); idx < idx_end; idx++) {
  867. switch(ifs.GetIntAttributeType(static_cast<unsigned int>(idx))) {
  868. case o3dgc::O3DGC_IFS_INT_ATTRIBUTE_TYPE_UNKOWN:
  869. case o3dgc::O3DGC_IFS_INT_ATTRIBUTE_TYPE_INDEX:
  870. case o3dgc::O3DGC_IFS_INT_ATTRIBUTE_TYPE_JOINT_ID:
  871. case o3dgc::O3DGC_IFS_INT_ATTRIBUTE_TYPE_INDEX_BUFFER_ID:
  872. break;
  873. // ifs.SetIntAttribute(idx, (long* const)(decoded_data + get_buf_offset(primitives[0].attributes.joint)));
  874. default:
  875. throw DeadlyImportError("GLTF: Open3DGC. Unsupported type of int attribute: " + to_string(ifs.GetIntAttributeType(static_cast<unsigned long>(idx))));
  876. }
  877. }
  878. //
  879. // Decode data
  880. //
  881. if ( decoder.DecodePayload( ifs, bstream ) != o3dgc::O3DGC_OK ) {
  882. throw DeadlyImportError( "GLTF: can not decode Open3DGC data." );
  883. }
  884. // Set encoded region for "buffer".
  885. buf->EncodedRegion_Mark(pCompression_Open3DGC.Offset, pCompression_Open3DGC.Count, decoded_data, decoded_data_size, id);
  886. // No. Do not delete "output_data". After calling "EncodedRegion_Mark" bufferView is owner of "output_data".
  887. // "delete [] output_data;"
  888. }
  889. #endif
  890. inline void Camera::Read(Value& obj, Asset& r)
  891. {
  892. type = MemberOrDefault(obj, "type", Camera::Perspective);
  893. const char* subobjId = (type == Camera::Orthographic) ? "ortographic" : "perspective";
  894. Value* it = FindObject(obj, subobjId);
  895. if (!it) throw DeadlyImportError("GLTF: Camera missing its parameters");
  896. if (type == Camera::Perspective) {
  897. perspective.aspectRatio = MemberOrDefault(*it, "aspectRatio", 0.f);
  898. perspective.yfov = MemberOrDefault(*it, "yfov", 3.1415f/2.f);
  899. perspective.zfar = MemberOrDefault(*it, "zfar", 100.f);
  900. perspective.znear = MemberOrDefault(*it, "znear", 0.01f);
  901. }
  902. else {
  903. ortographic.xmag = MemberOrDefault(obj, "xmag", 1.f);
  904. ortographic.ymag = MemberOrDefault(obj, "ymag", 1.f);
  905. ortographic.zfar = MemberOrDefault(obj, "zfar", 100.f);
  906. ortographic.znear = MemberOrDefault(obj, "znear", 0.01f);
  907. }
  908. }
  909. inline void Light::Read(Value& obj, Asset& r)
  910. {
  911. SetDefaults();
  912. if (Value* type = FindString(obj, "type")) {
  913. const char* t = type->GetString();
  914. if (strcmp(t, "ambient") == 0) this->type = Type_ambient;
  915. else if (strcmp(t, "directional") == 0) this->type = Type_directional;
  916. else if (strcmp(t, "point") == 0) this->type = Type_point;
  917. else if (strcmp(t, "spot") == 0) this->type = Type_spot;
  918. if (this->type != Type_undefined) {
  919. if (Value* vals = FindString(obj, t)) {
  920. ReadMember(*vals, "color", color);
  921. ReadMember(*vals, "constantAttenuation", constantAttenuation);
  922. ReadMember(*vals, "linearAttenuation", linearAttenuation);
  923. ReadMember(*vals, "quadraticAttenuation", quadraticAttenuation);
  924. ReadMember(*vals, "distance", distance);
  925. ReadMember(*vals, "falloffAngle", falloffAngle);
  926. ReadMember(*vals, "falloffExponent", falloffExponent);
  927. }
  928. }
  929. }
  930. }
  931. inline void Light::SetDefaults()
  932. {
  933. #ifndef M_PI
  934. const float M_PI = 3.14159265358979323846f;
  935. #endif
  936. type = Type_undefined;
  937. SetVector(color, 0.f, 0.f, 0.f, 1.f);
  938. constantAttenuation = 0.f;
  939. linearAttenuation = 1.f;
  940. quadraticAttenuation = 1.f;
  941. distance = 0.f;
  942. falloffAngle = static_cast<float>(M_PI / 2.f);
  943. falloffExponent = 0.f;
  944. }
  945. inline void Node::Read(Value& obj, Asset& r)
  946. {
  947. if (Value* children = FindArray(obj, "children")) {
  948. this->children.reserve(children->Size());
  949. for (unsigned int i = 0; i < children->Size(); ++i) {
  950. Value& child = (*children)[i];
  951. if (child.IsString()) {
  952. // get/create the child node
  953. Ref<Node> chn = r.nodes.Get(child.GetString());
  954. if (chn) this->children.push_back(chn);
  955. }
  956. }
  957. }
  958. if (Value* matrix = FindArray(obj, "matrix")) {
  959. ReadValue(*matrix, this->matrix);
  960. }
  961. else {
  962. ReadMember(obj, "translation", translation);
  963. ReadMember(obj, "scale", scale);
  964. ReadMember(obj, "rotation", rotation);
  965. }
  966. if (Value* meshes = FindArray(obj, "meshes")) {
  967. unsigned numMeshes = (unsigned)meshes->Size();
  968. std::vector<unsigned int> meshList;
  969. this->meshes.reserve(numMeshes);
  970. for (unsigned i = 0; i < numMeshes; ++i) {
  971. if ((*meshes)[i].IsString()) {
  972. Ref<Mesh> mesh = r.meshes.Get((*meshes)[i].GetString());
  973. if (mesh) this->meshes.push_back(mesh);
  974. }
  975. }
  976. }
  977. if (Value* camera = FindString(obj, "camera")) {
  978. this->camera = r.cameras.Get(camera->GetString());
  979. if (this->camera)
  980. this->camera->id = this->id;
  981. }
  982. // TODO load "skeletons", "skin", "jointName"
  983. if (Value* extensions = FindObject(obj, "extensions")) {
  984. if (r.extensionsUsed.KHR_materials_common) {
  985. if (Value* ext = FindObject(*extensions, "KHR_materials_common")) {
  986. if (Value* light = FindString(*ext, "light")) {
  987. this->light = r.lights.Get(light->GetString());
  988. }
  989. }
  990. }
  991. }
  992. }
  993. inline void Scene::Read(Value& obj, Asset& r)
  994. {
  995. if (Value* array = FindArray(obj, "nodes")) {
  996. for (unsigned int i = 0; i < array->Size(); ++i) {
  997. if (!(*array)[i].IsString()) continue;
  998. Ref<Node> node = r.nodes.Get((*array)[i].GetString());
  999. if (node)
  1000. this->nodes.push_back(node);
  1001. }
  1002. }
  1003. }
  1004. inline void AssetMetadata::Read(Document& doc)
  1005. {
  1006. // read the version, etc.
  1007. int statedVersion = 0;
  1008. if (Value* obj = FindObject(doc, "asset")) {
  1009. ReadMember(*obj, "copyright", copyright);
  1010. ReadMember(*obj, "generator", generator);
  1011. premultipliedAlpha = MemberOrDefault(*obj, "premultipliedAlpha", false);
  1012. statedVersion = MemberOrDefault(*obj, "version", 0);
  1013. if (Value* profile = FindObject(*obj, "profile")) {
  1014. ReadMember(*profile, "api", this->profile.api);
  1015. ReadMember(*profile, "version", this->profile.version);
  1016. }
  1017. }
  1018. version = std::max(statedVersion, version);
  1019. if (version == 0) {
  1020. // if missing version, we'll assume version 1...
  1021. version = 1;
  1022. }
  1023. if (version != 1) {
  1024. char msg[128];
  1025. ai_snprintf(msg, 128, "GLTF: Unsupported glTF version: %d", version);
  1026. throw DeadlyImportError(msg);
  1027. }
  1028. }
  1029. //
  1030. // Asset methods implementation
  1031. //
  1032. inline void Asset::ReadBinaryHeader(IOStream& stream)
  1033. {
  1034. GLB_Header header;
  1035. if (stream.Read(&header, sizeof(header), 1) != 1) {
  1036. throw DeadlyImportError("GLTF: Unable to read the file header");
  1037. }
  1038. if (strncmp((char*)header.magic, AI_GLB_MAGIC_NUMBER, sizeof(header.magic)) != 0) {
  1039. throw DeadlyImportError("GLTF: Invalid binary glTF file");
  1040. }
  1041. AI_SWAP4(header.version);
  1042. asset.version = header.version;
  1043. if (header.version != 1) {
  1044. throw DeadlyImportError("GLTF: Unsupported binary glTF version");
  1045. }
  1046. AI_SWAP4(header.sceneFormat);
  1047. if (header.sceneFormat != SceneFormat_JSON) {
  1048. throw DeadlyImportError("GLTF: Unsupported binary glTF scene format");
  1049. }
  1050. AI_SWAP4(header.length);
  1051. AI_SWAP4(header.sceneLength);
  1052. mSceneLength = static_cast<size_t>(header.sceneLength);
  1053. mBodyOffset = sizeof(header)+mSceneLength;
  1054. mBodyOffset = (mBodyOffset + 3) & ~3; // Round up to next multiple of 4
  1055. mBodyLength = header.length - mBodyOffset;
  1056. }
  1057. inline void Asset::Load(const std::string& pFile, bool isBinary)
  1058. {
  1059. mCurrentAssetDir.clear();
  1060. int pos = std::max(int(pFile.rfind('/')), int(pFile.rfind('\\')));
  1061. if (pos != int(std::string::npos)) mCurrentAssetDir = pFile.substr(0, pos + 1);
  1062. shared_ptr<IOStream> stream(OpenFile(pFile.c_str(), "rb", true));
  1063. if (!stream) {
  1064. throw DeadlyImportError("GLTF: Could not open file for reading");
  1065. }
  1066. // is binary? then read the header
  1067. if (isBinary) {
  1068. SetAsBinary(); // also creates the body buffer
  1069. ReadBinaryHeader(*stream);
  1070. }
  1071. else {
  1072. mSceneLength = stream->FileSize();
  1073. mBodyLength = 0;
  1074. }
  1075. // read the scene data
  1076. std::vector<char> sceneData(mSceneLength + 1);
  1077. sceneData[mSceneLength] = '\0';
  1078. if (stream->Read(&sceneData[0], 1, mSceneLength) != mSceneLength) {
  1079. throw DeadlyImportError("GLTF: Could not read the file contents");
  1080. }
  1081. // parse the JSON document
  1082. Document doc;
  1083. doc.ParseInsitu(&sceneData[0]);
  1084. if (doc.HasParseError()) {
  1085. char buffer[32];
  1086. ai_snprintf(buffer, 32, "%d", static_cast<int>(doc.GetErrorOffset()));
  1087. throw DeadlyImportError(std::string("GLTF: JSON parse error, offset ") + buffer + ": "
  1088. + GetParseError_En(doc.GetParseError()));
  1089. }
  1090. if (!doc.IsObject()) {
  1091. throw DeadlyImportError("GLTF: JSON document root must be a JSON object");
  1092. }
  1093. // Fill the buffer instance for the current file embedded contents
  1094. if (mBodyLength > 0) {
  1095. if (!mBodyBuffer->LoadFromStream(*stream, mBodyLength, mBodyOffset)) {
  1096. throw DeadlyImportError("GLTF: Unable to read gltf file");
  1097. }
  1098. }
  1099. // Load the metadata
  1100. asset.Read(doc);
  1101. ReadExtensionsUsed(doc);
  1102. // Prepare the dictionaries
  1103. for (size_t i = 0; i < mDicts.size(); ++i) {
  1104. mDicts[i]->AttachToDocument(doc);
  1105. }
  1106. // Read the "scene" property, which specifies which scene to load
  1107. // and recursively load everything referenced by it
  1108. if (Value* scene = FindString(doc, "scene")) {
  1109. this->scene = scenes.Get(scene->GetString());
  1110. }
  1111. // Clean up
  1112. for (size_t i = 0; i < mDicts.size(); ++i) {
  1113. mDicts[i]->DetachFromDocument();
  1114. }
  1115. }
  1116. inline void Asset::SetAsBinary()
  1117. {
  1118. if (!extensionsUsed.KHR_binary_glTF) {
  1119. extensionsUsed.KHR_binary_glTF = true;
  1120. mBodyBuffer = buffers.Create("binary_glTF");
  1121. mBodyBuffer->MarkAsSpecial();
  1122. }
  1123. }
  1124. inline void Asset::ReadExtensionsUsed(Document& doc)
  1125. {
  1126. Value* extsUsed = FindArray(doc, "extensionsUsed");
  1127. if (!extsUsed) return;
  1128. std::gltf_unordered_map<std::string, bool> exts;
  1129. for (unsigned int i = 0; i < extsUsed->Size(); ++i) {
  1130. if ((*extsUsed)[i].IsString()) {
  1131. exts[(*extsUsed)[i].GetString()] = true;
  1132. }
  1133. }
  1134. #define CHECK_EXT(EXT) \
  1135. if (exts.find(#EXT) != exts.end()) extensionsUsed.EXT = true;
  1136. CHECK_EXT(KHR_binary_glTF);
  1137. CHECK_EXT(KHR_materials_common);
  1138. #undef CHECK_EXT
  1139. }
  1140. inline IOStream* Asset::OpenFile(std::string path, const char* mode, bool absolute)
  1141. {
  1142. #ifdef ASSIMP_API
  1143. return mIOSystem->Open(path, mode);
  1144. #else
  1145. if (path.size() < 2) return 0;
  1146. if (!absolute && path[1] != ':' && path[0] != '/') { // relative?
  1147. path = mCurrentAssetDir + path;
  1148. }
  1149. FILE* f = fopen(path.c_str(), mode);
  1150. return f ? new IOStream(f) : 0;
  1151. #endif
  1152. }
  1153. inline std::string Asset::FindUniqueID(const std::string& str, const char* suffix)
  1154. {
  1155. std::string id = str;
  1156. if (!id.empty()) {
  1157. if (mUsedIds.find(id) == mUsedIds.end())
  1158. return id;
  1159. id += "_";
  1160. }
  1161. id += suffix;
  1162. Asset::IdMap::iterator it = mUsedIds.find(id);
  1163. if (it == mUsedIds.end())
  1164. return id;
  1165. char buffer[256];
  1166. int offset = ai_snprintf(buffer, sizeof(buffer), "%s_", id.c_str());
  1167. for (int i = 0; it != mUsedIds.end(); ++i) {
  1168. ai_snprintf(buffer + offset, sizeof(buffer) - offset, "%d", i);
  1169. id = buffer;
  1170. it = mUsedIds.find(id);
  1171. }
  1172. return id;
  1173. }
  1174. namespace Util {
  1175. inline
  1176. bool ParseDataURI(const char* const_uri, size_t uriLen, DataURI& out) {
  1177. if ( NULL == const_uri ) {
  1178. return false;
  1179. }
  1180. if (const_uri[0] != 0x10) { // we already parsed this uri?
  1181. if (strncmp(const_uri, "data:", 5) != 0) // not a data uri?
  1182. return false;
  1183. }
  1184. // set defaults
  1185. out.mediaType = "text/plain";
  1186. out.charset = "US-ASCII";
  1187. out.base64 = false;
  1188. char* uri = const_cast<char*>(const_uri);
  1189. if (uri[0] != 0x10) {
  1190. uri[0] = 0x10;
  1191. uri[1] = uri[2] = uri[3] = uri[4] = 0;
  1192. size_t i = 5, j;
  1193. if (uri[i] != ';' && uri[i] != ',') { // has media type?
  1194. uri[1] = char(i);
  1195. for (; uri[i] != ';' && uri[i] != ',' && i < uriLen; ++i) {
  1196. // nothing to do!
  1197. }
  1198. }
  1199. while (uri[i] == ';' && i < uriLen) {
  1200. uri[i++] = '\0';
  1201. for (j = i; uri[i] != ';' && uri[i] != ',' && i < uriLen; ++i) {
  1202. // nothing to do!
  1203. }
  1204. if ( strncmp( uri + j, "charset=", 8 ) == 0 ) {
  1205. uri[2] = char(j + 8);
  1206. } else if ( strncmp( uri + j, "base64", 6 ) == 0 ) {
  1207. uri[3] = char(j);
  1208. }
  1209. }
  1210. if (i < uriLen) {
  1211. uri[i++] = '\0';
  1212. uri[4] = char(i);
  1213. } else {
  1214. uri[1] = uri[2] = uri[3] = 0;
  1215. uri[4] = 5;
  1216. }
  1217. }
  1218. if ( uri[ 1 ] != 0 ) {
  1219. out.mediaType = uri + uri[ 1 ];
  1220. }
  1221. if ( uri[ 2 ] != 0 ) {
  1222. out.charset = uri + uri[ 2 ];
  1223. }
  1224. if ( uri[ 3 ] != 0 ) {
  1225. out.base64 = true;
  1226. }
  1227. out.data = uri + uri[4];
  1228. out.dataLength = (uri + uriLen) - out.data;
  1229. return true;
  1230. }
  1231. template<bool B>
  1232. struct DATA
  1233. {
  1234. static const uint8_t tableDecodeBase64[128];
  1235. };
  1236. template<bool B>
  1237. const uint8_t DATA<B>::tableDecodeBase64[128] = {
  1238. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  1239. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  1240. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 62, 0, 0, 0, 63,
  1241. 52, 53, 54, 55, 56, 57, 58, 59, 60, 61, 0, 0, 0, 64, 0, 0,
  1242. 0, 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14,
  1243. 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 0, 0, 0, 0, 0,
  1244. 0, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 36, 37, 38, 39, 40,
  1245. 41, 42, 43, 44, 45, 46, 47, 48, 49, 50, 51, 0, 0, 0, 0, 0
  1246. };
  1247. inline char EncodeCharBase64(uint8_t b)
  1248. {
  1249. return "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/="[size_t(b)];
  1250. }
  1251. inline uint8_t DecodeCharBase64(char c)
  1252. {
  1253. return DATA<true>::tableDecodeBase64[size_t(c)]; // TODO faster with lookup table or ifs?
  1254. /*if (c >= 'A' && c <= 'Z') return c - 'A';
  1255. if (c >= 'a' && c <= 'z') return c - 'a' + 26;
  1256. if (c >= '0' && c <= '9') return c - '0' + 52;
  1257. if (c == '+') return 62;
  1258. if (c == '/') return 63;
  1259. return 64; // '-' */
  1260. }
  1261. inline size_t DecodeBase64(const char* in, size_t inLength, uint8_t*& out)
  1262. {
  1263. ai_assert(inLength % 4 == 0);
  1264. if (inLength < 4) {
  1265. out = 0;
  1266. return 0;
  1267. }
  1268. int nEquals = int(in[inLength - 1] == '=') +
  1269. int(in[inLength - 2] == '=');
  1270. size_t outLength = (inLength * 3) / 4 - nEquals;
  1271. out = new uint8_t[outLength];
  1272. memset(out, 0, outLength);
  1273. size_t i, j = 0;
  1274. for (i = 0; i + 4 < inLength; i += 4) {
  1275. uint8_t b0 = DecodeCharBase64(in[i]);
  1276. uint8_t b1 = DecodeCharBase64(in[i + 1]);
  1277. uint8_t b2 = DecodeCharBase64(in[i + 2]);
  1278. uint8_t b3 = DecodeCharBase64(in[i + 3]);
  1279. out[j++] = (uint8_t)((b0 << 2) | (b1 >> 4));
  1280. out[j++] = (uint8_t)((b1 << 4) | (b2 >> 2));
  1281. out[j++] = (uint8_t)((b2 << 6) | b3);
  1282. }
  1283. {
  1284. uint8_t b0 = DecodeCharBase64(in[i]);
  1285. uint8_t b1 = DecodeCharBase64(in[i + 1]);
  1286. uint8_t b2 = DecodeCharBase64(in[i + 2]);
  1287. uint8_t b3 = DecodeCharBase64(in[i + 3]);
  1288. out[j++] = (uint8_t)((b0 << 2) | (b1 >> 4));
  1289. if (b2 < 64) out[j++] = (uint8_t)((b1 << 4) | (b2 >> 2));
  1290. if (b3 < 64) out[j++] = (uint8_t)((b2 << 6) | b3);
  1291. }
  1292. return outLength;
  1293. }
  1294. inline void EncodeBase64(
  1295. const uint8_t* in, size_t inLength,
  1296. std::string& out)
  1297. {
  1298. size_t outLength = ((inLength + 2) / 3) * 4;
  1299. size_t j = out.size();
  1300. out.resize(j + outLength);
  1301. for (size_t i = 0; i < inLength; i += 3) {
  1302. uint8_t b = (in[i] & 0xFC) >> 2;
  1303. out[j++] = EncodeCharBase64(b);
  1304. b = (in[i] & 0x03) << 4;
  1305. if (i + 1 < inLength) {
  1306. b |= (in[i + 1] & 0xF0) >> 4;
  1307. out[j++] = EncodeCharBase64(b);
  1308. b = (in[i + 1] & 0x0F) << 2;
  1309. if (i + 2 < inLength) {
  1310. b |= (in[i + 2] & 0xC0) >> 6;
  1311. out[j++] = EncodeCharBase64(b);
  1312. b = in[i + 2] & 0x3F;
  1313. out[j++] = EncodeCharBase64(b);
  1314. }
  1315. else {
  1316. out[j++] = EncodeCharBase64(b);
  1317. out[j++] = '=';
  1318. }
  1319. }
  1320. else {
  1321. out[j++] = EncodeCharBase64(b);
  1322. out[j++] = '=';
  1323. out[j++] = '=';
  1324. }
  1325. }
  1326. }
  1327. }
  1328. } // ns glTF