glTF2Asset.inl 58 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730
  1. /*
  2. Open Asset Import Library (assimp)
  3. ----------------------------------------------------------------------
  4. Copyright (c) 2006-2020, assimp team
  5. All rights reserved.
  6. Redistribution and use of this software in source and binary forms,
  7. with or without modification, are permitted provided that the
  8. following conditions are met:
  9. * Redistributions of source code must retain the above
  10. copyright notice, this list of conditions and the
  11. following disclaimer.
  12. * Redistributions in binary form must reproduce the above
  13. copyright notice, this list of conditions and the
  14. following disclaimer in the documentation and/or other
  15. materials provided with the distribution.
  16. * Neither the name of the assimp team, nor the names of its
  17. contributors may be used to endorse or promote products
  18. derived from this software without specific prior
  19. written permission of the assimp team.
  20. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
  21. "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
  22. LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
  23. A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
  24. OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
  25. SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
  26. LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
  27. DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
  28. THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
  29. (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
  30. OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
  31. ----------------------------------------------------------------------
  32. */
  33. #include "AssetLib/glTF/glTFCommon.h"
  34. #include <assimp/StringUtils.h>
  35. #include <assimp/DefaultLogger.hpp>
  36. using namespace Assimp;
  37. namespace glTF2 {
  38. namespace {
  39. //
  40. // JSON Value reading helpers
  41. //
  42. template <class T>
  43. struct ReadHelper {
  44. static bool Read(Value &val, T &out) {
  45. return val.IsInt() ? out = static_cast<T>(val.GetInt()), true : false;
  46. }
  47. };
  48. template <>
  49. struct ReadHelper<bool> {
  50. static bool Read(Value &val, bool &out) {
  51. return val.IsBool() ? out = val.GetBool(), true : false;
  52. }
  53. };
  54. template <>
  55. struct ReadHelper<float> {
  56. static bool Read(Value &val, float &out) {
  57. return val.IsNumber() ? out = static_cast<float>(val.GetDouble()), true : false;
  58. }
  59. };
  60. template <unsigned int N>
  61. struct ReadHelper<float[N]> {
  62. static bool Read(Value &val, float (&out)[N]) {
  63. if (!val.IsArray() || val.Size() != N) return false;
  64. for (unsigned int i = 0; i < N; ++i) {
  65. if (val[i].IsNumber())
  66. out[i] = static_cast<float>(val[i].GetDouble());
  67. }
  68. return true;
  69. }
  70. };
  71. template <>
  72. struct ReadHelper<const char *> {
  73. static bool Read(Value &val, const char *&out) {
  74. return val.IsString() ? (out = val.GetString(), true) : false;
  75. }
  76. };
  77. template <>
  78. struct ReadHelper<std::string> {
  79. static bool Read(Value &val, std::string &out) {
  80. return val.IsString() ? (out = std::string(val.GetString(), val.GetStringLength()), true) : false;
  81. }
  82. };
  83. template <>
  84. struct ReadHelper<uint64_t> {
  85. static bool Read(Value &val, uint64_t &out) {
  86. return val.IsUint64() ? out = val.GetUint64(), true : false;
  87. }
  88. };
  89. template <>
  90. struct ReadHelper<int64_t> {
  91. static bool Read(Value &val, int64_t &out) {
  92. return val.IsInt64() ? out = val.GetInt64(), true : false;
  93. }
  94. };
  95. template <class T>
  96. struct ReadHelper<Nullable<T>> {
  97. static bool Read(Value &val, Nullable<T> &out) {
  98. return out.isPresent = ReadHelper<T>::Read(val, out.value);
  99. }
  100. };
  101. template <class T>
  102. inline static bool ReadValue(Value &val, T &out) {
  103. return ReadHelper<T>::Read(val, out);
  104. }
  105. template <class T>
  106. inline static bool ReadMember(Value &obj, const char *id, T &out) {
  107. Value::MemberIterator it = obj.FindMember(id);
  108. if (it != obj.MemberEnd()) {
  109. return ReadHelper<T>::Read(it->value, out);
  110. }
  111. return false;
  112. }
  113. template <class T>
  114. inline static T MemberOrDefault(Value &obj, const char *id, T defaultValue) {
  115. T out;
  116. return ReadMember(obj, id, out) ? out : defaultValue;
  117. }
  118. inline Value *FindMember(Value &val, const char *id) {
  119. Value::MemberIterator it = val.FindMember(id);
  120. return (it != val.MemberEnd()) ? &it->value : 0;
  121. }
  122. inline Value *FindString(Value &val, const char *id) {
  123. Value::MemberIterator it = val.FindMember(id);
  124. return (it != val.MemberEnd() && it->value.IsString()) ? &it->value : 0;
  125. }
  126. inline Value *FindNumber(Value &val, const char *id) {
  127. Value::MemberIterator it = val.FindMember(id);
  128. return (it != val.MemberEnd() && it->value.IsNumber()) ? &it->value : 0;
  129. }
  130. inline Value *FindUInt(Value &val, const char *id) {
  131. Value::MemberIterator it = val.FindMember(id);
  132. return (it != val.MemberEnd() && it->value.IsUint()) ? &it->value : 0;
  133. }
  134. inline Value *FindArray(Value &val, const char *id) {
  135. Value::MemberIterator it = val.FindMember(id);
  136. return (it != val.MemberEnd() && it->value.IsArray()) ? &it->value : 0;
  137. }
  138. inline Value *FindObject(Value &val, const char *id) {
  139. Value::MemberIterator it = val.FindMember(id);
  140. return (it != val.MemberEnd() && it->value.IsObject()) ? &it->value : 0;
  141. }
  142. } // namespace
  143. //
  144. // LazyDict methods
  145. //
  146. template <class T>
  147. inline LazyDict<T>::LazyDict(Asset &asset, const char *dictId, const char *extId) :
  148. mDictId(dictId),
  149. mExtId(extId),
  150. mDict(0),
  151. mAsset(asset) {
  152. asset.mDicts.push_back(this); // register to the list of dictionaries
  153. }
  154. template <class T>
  155. inline LazyDict<T>::~LazyDict() {
  156. for (size_t i = 0; i < mObjs.size(); ++i) {
  157. delete mObjs[i];
  158. }
  159. }
  160. template <class T>
  161. inline void LazyDict<T>::AttachToDocument(Document &doc) {
  162. Value *container = 0;
  163. if (mExtId) {
  164. if (Value *exts = FindObject(doc, "extensions")) {
  165. container = FindObject(*exts, mExtId);
  166. }
  167. } else {
  168. container = &doc;
  169. }
  170. if (container) {
  171. mDict = FindArray(*container, mDictId);
  172. }
  173. }
  174. template <class T>
  175. inline void LazyDict<T>::DetachFromDocument() {
  176. mDict = 0;
  177. }
  178. template <class T>
  179. unsigned int LazyDict<T>::Remove(const char *id) {
  180. id = T::TranslateId(mAsset, id);
  181. typename IdDict::iterator objIt = mObjsById.find(id);
  182. if (objIt == mObjsById.end()) {
  183. throw DeadlyExportError("GLTF: Object with id \"" + std::string(id) + "\" is not found");
  184. }
  185. const unsigned int index = objIt->second;
  186. mAsset.mUsedIds[id] = false;
  187. mObjsById.erase(id);
  188. mObjsByOIndex.erase(index);
  189. mObjs.erase(mObjs.begin() + index);
  190. //update index of object in mObjs;
  191. for (unsigned int i = index; i < mObjs.size(); ++i) {
  192. T *obj = mObjs[i];
  193. obj->index = i;
  194. }
  195. for (IdDict::iterator it = mObjsById.begin(); it != mObjsById.end(); ++it) {
  196. if (it->second <= index) {
  197. continue;
  198. }
  199. mObjsById[it->first] = it->second - 1;
  200. }
  201. for (Dict::iterator it = mObjsByOIndex.begin(); it != mObjsByOIndex.end(); ++it) {
  202. if (it->second <= index) {
  203. continue;
  204. }
  205. mObjsByOIndex[it->first] = it->second - 1;
  206. }
  207. return index;
  208. }
  209. template <class T>
  210. Ref<T> LazyDict<T>::Retrieve(unsigned int i) {
  211. typename Dict::iterator it = mObjsByOIndex.find(i);
  212. if (it != mObjsByOIndex.end()) { // already created?
  213. return Ref<T>(mObjs, it->second);
  214. }
  215. // read it from the JSON object
  216. if (!mDict) {
  217. throw DeadlyImportError("GLTF: Missing section \"" + std::string(mDictId) + "\"");
  218. }
  219. if (!mDict->IsArray()) {
  220. throw DeadlyImportError("GLTF: Field is not an array \"" + std::string(mDictId) + "\"");
  221. }
  222. Value &obj = (*mDict)[i];
  223. if (!obj.IsObject()) {
  224. throw DeadlyImportError("GLTF: Object at index \"" + to_string(i) + "\" is not a JSON object");
  225. }
  226. if (mRecursiveReferenceCheck.find(i) != mRecursiveReferenceCheck.end()) {
  227. throw DeadlyImportError("GLTF: Object at index \"" + to_string(i) + "\" has recursive reference to itself");
  228. }
  229. mRecursiveReferenceCheck.insert(i);
  230. // Unique ptr prevents memory leak in case of Read throws an exception
  231. auto inst = std::unique_ptr<T>(new T());
  232. inst->id = std::string(mDictId) + "_" + to_string(i);
  233. inst->oIndex = i;
  234. ReadMember(obj, "name", inst->name);
  235. inst->Read(obj, mAsset);
  236. Ref<T> result = Add(inst.release());
  237. mRecursiveReferenceCheck.erase(i);
  238. return result;
  239. }
  240. template <class T>
  241. Ref<T> LazyDict<T>::Get(unsigned int i) {
  242. return Ref<T>(mObjs, i);
  243. }
  244. template <class T>
  245. Ref<T> LazyDict<T>::Get(const char *id) {
  246. id = T::TranslateId(mAsset, id);
  247. typename IdDict::iterator it = mObjsById.find(id);
  248. if (it != mObjsById.end()) { // already created?
  249. return Ref<T>(mObjs, it->second);
  250. }
  251. return Ref<T>();
  252. }
  253. template <class T>
  254. Ref<T> LazyDict<T>::Add(T *obj) {
  255. unsigned int idx = unsigned(mObjs.size());
  256. mObjs.push_back(obj);
  257. mObjsByOIndex[obj->oIndex] = idx;
  258. mObjsById[obj->id] = idx;
  259. mAsset.mUsedIds[obj->id] = true;
  260. return Ref<T>(mObjs, idx);
  261. }
  262. template <class T>
  263. Ref<T> LazyDict<T>::Create(const char *id) {
  264. Asset::IdMap::iterator it = mAsset.mUsedIds.find(id);
  265. if (it != mAsset.mUsedIds.end()) {
  266. throw DeadlyImportError("GLTF: two objects with the same ID exist");
  267. }
  268. T *inst = new T();
  269. unsigned int idx = unsigned(mObjs.size());
  270. inst->id = id;
  271. inst->index = idx;
  272. inst->oIndex = idx;
  273. return Add(inst);
  274. }
  275. //
  276. // glTF dictionary objects methods
  277. //
  278. inline Buffer::Buffer() :
  279. byteLength(0),
  280. type(Type_arraybuffer),
  281. EncodedRegion_Current(nullptr),
  282. mIsSpecial(false) {}
  283. inline Buffer::~Buffer() {
  284. for (SEncodedRegion *reg : EncodedRegion_List)
  285. delete reg;
  286. }
  287. inline const char *Buffer::TranslateId(Asset & /*r*/, const char *id) {
  288. return id;
  289. }
  290. inline void Buffer::Read(Value &obj, Asset &r) {
  291. size_t statedLength = MemberOrDefault<size_t>(obj, "byteLength", 0);
  292. byteLength = statedLength;
  293. Value *it = FindString(obj, "uri");
  294. if (!it) {
  295. if (statedLength > 0) {
  296. throw DeadlyImportError("GLTF: buffer with non-zero length missing the \"uri\" attribute");
  297. }
  298. return;
  299. }
  300. const char *uri = it->GetString();
  301. glTFCommon::Util::DataURI dataURI;
  302. if (ParseDataURI(uri, it->GetStringLength(), dataURI)) {
  303. if (dataURI.base64) {
  304. uint8_t *data = 0;
  305. this->byteLength = glTFCommon::Util::DecodeBase64(dataURI.data, dataURI.dataLength, data);
  306. this->mData.reset(data, std::default_delete<uint8_t[]>());
  307. if (statedLength > 0 && this->byteLength != statedLength) {
  308. throw DeadlyImportError("GLTF: buffer \"" + id + "\", expected " + to_string(statedLength) +
  309. " bytes, but found " + to_string(dataURI.dataLength));
  310. }
  311. } else { // assume raw data
  312. if (statedLength != dataURI.dataLength) {
  313. throw DeadlyImportError("GLTF: buffer \"" + id + "\", expected " + to_string(statedLength) +
  314. " bytes, but found " + to_string(dataURI.dataLength));
  315. }
  316. this->mData.reset(new uint8_t[dataURI.dataLength], std::default_delete<uint8_t[]>());
  317. memcpy(this->mData.get(), dataURI.data, dataURI.dataLength);
  318. }
  319. } else { // Local file
  320. if (byteLength > 0) {
  321. std::string dir = !r.mCurrentAssetDir.empty() ? (r.mCurrentAssetDir) : "";
  322. IOStream *file = r.OpenFile(dir + uri, "rb");
  323. if (file) {
  324. bool ok = LoadFromStream(*file, byteLength);
  325. delete file;
  326. if (!ok)
  327. throw DeadlyImportError("GLTF: error while reading referenced file \"" + std::string(uri) + "\"");
  328. } else {
  329. throw DeadlyImportError("GLTF: could not open referenced file \"" + std::string(uri) + "\"");
  330. }
  331. }
  332. }
  333. }
  334. inline bool Buffer::LoadFromStream(IOStream &stream, size_t length, size_t baseOffset) {
  335. byteLength = length ? length : stream.FileSize();
  336. if (baseOffset) {
  337. stream.Seek(baseOffset, aiOrigin_SET);
  338. }
  339. mData.reset(new uint8_t[byteLength], std::default_delete<uint8_t[]>());
  340. if (stream.Read(mData.get(), byteLength, 1) != 1) {
  341. return false;
  342. }
  343. return true;
  344. }
  345. 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) {
  346. // Check pointer to data
  347. if (pDecodedData == nullptr) throw DeadlyImportError("GLTF: for marking encoded region pointer to decoded data must be provided.");
  348. // Check offset
  349. if (pOffset > byteLength) {
  350. const uint8_t val_size = 32;
  351. char val[val_size];
  352. ai_snprintf(val, val_size, "%llu", (long long)pOffset);
  353. throw DeadlyImportError(std::string("GLTF: incorrect offset value (") + val + ") for marking encoded region.");
  354. }
  355. // Check length
  356. if ((pOffset + pEncodedData_Length) > byteLength) {
  357. const uint8_t val_size = 64;
  358. char val[val_size];
  359. ai_snprintf(val, val_size, "%llu, %llu", (long long)pOffset, (long long)pEncodedData_Length);
  360. throw DeadlyImportError(std::string("GLTF: encoded region with offset/length (") + val + ") is out of range.");
  361. }
  362. // Add new region
  363. EncodedRegion_List.push_back(new SEncodedRegion(pOffset, pEncodedData_Length, pDecodedData, pDecodedData_Length, pID));
  364. // And set new value for "byteLength"
  365. byteLength += (pDecodedData_Length - pEncodedData_Length);
  366. }
  367. inline void Buffer::EncodedRegion_SetCurrent(const std::string &pID) {
  368. if ((EncodedRegion_Current != nullptr) && (EncodedRegion_Current->ID == pID)) return;
  369. for (SEncodedRegion *reg : EncodedRegion_List) {
  370. if (reg->ID == pID) {
  371. EncodedRegion_Current = reg;
  372. return;
  373. }
  374. }
  375. throw DeadlyImportError("GLTF: EncodedRegion with ID: \"" + pID + "\" not found.");
  376. }
  377. inline bool Buffer::ReplaceData(const size_t pBufferData_Offset, const size_t pBufferData_Count, const uint8_t *pReplace_Data, const size_t pReplace_Count) {
  378. if ((pBufferData_Count == 0) || (pReplace_Count == 0) || (pReplace_Data == nullptr)) {
  379. return false;
  380. }
  381. const size_t new_data_size = byteLength + pReplace_Count - pBufferData_Count;
  382. uint8_t *new_data = new uint8_t[new_data_size];
  383. // Copy data which place before replacing part.
  384. ::memcpy(new_data, mData.get(), pBufferData_Offset);
  385. // Copy new data.
  386. ::memcpy(&new_data[pBufferData_Offset], pReplace_Data, pReplace_Count);
  387. // Copy data which place after replacing part.
  388. ::memcpy(&new_data[pBufferData_Offset + pReplace_Count], &mData.get()[pBufferData_Offset + pBufferData_Count], pBufferData_Offset);
  389. // Apply new data
  390. mData.reset(new_data, std::default_delete<uint8_t[]>());
  391. byteLength = new_data_size;
  392. return true;
  393. }
  394. inline bool Buffer::ReplaceData_joint(const size_t pBufferData_Offset, const size_t pBufferData_Count, const uint8_t *pReplace_Data, const size_t pReplace_Count) {
  395. if ((pBufferData_Count == 0) || (pReplace_Count == 0) || (pReplace_Data == nullptr)) {
  396. return false;
  397. }
  398. const size_t new_data_size = byteLength + pReplace_Count - pBufferData_Count;
  399. uint8_t *new_data = new uint8_t[new_data_size];
  400. // Copy data which place before replacing part.
  401. memcpy(new_data, mData.get(), pBufferData_Offset);
  402. // Copy new data.
  403. memcpy(&new_data[pBufferData_Offset], pReplace_Data, pReplace_Count);
  404. // Copy data which place after replacing part.
  405. memcpy(&new_data[pBufferData_Offset + pReplace_Count], &mData.get()[pBufferData_Offset + pBufferData_Count], new_data_size - (pBufferData_Offset + pReplace_Count));
  406. // Apply new data
  407. mData.reset(new_data, std::default_delete<uint8_t[]>());
  408. byteLength = new_data_size;
  409. return true;
  410. }
  411. inline size_t Buffer::AppendData(uint8_t *data, size_t length) {
  412. size_t offset = this->byteLength;
  413. // Force alignment to 4 bits
  414. Grow((length + 3) & ~3);
  415. memcpy(mData.get() + offset, data, length);
  416. return offset;
  417. }
  418. inline void Buffer::Grow(size_t amount) {
  419. if (amount <= 0) {
  420. return;
  421. }
  422. // Capacity is big enough
  423. if (capacity >= byteLength + amount) {
  424. byteLength += amount;
  425. return;
  426. }
  427. // Just allocate data which we need
  428. capacity = byteLength + amount;
  429. uint8_t *b = new uint8_t[capacity];
  430. if (nullptr != mData) {
  431. memcpy(b, mData.get(), byteLength);
  432. }
  433. mData.reset(b, std::default_delete<uint8_t[]>());
  434. byteLength += amount;
  435. }
  436. //
  437. // struct BufferView
  438. //
  439. inline void BufferView::Read(Value &obj, Asset &r) {
  440. if (Value *bufferVal = FindUInt(obj, "buffer")) {
  441. buffer = r.buffers.Retrieve(bufferVal->GetUint());
  442. }
  443. byteOffset = MemberOrDefault(obj, "byteOffset", size_t(0));
  444. byteLength = MemberOrDefault(obj, "byteLength", size_t(0));
  445. byteStride = MemberOrDefault(obj, "byteStride", 0u);
  446. }
  447. inline uint8_t *BufferView::GetPointer(size_t accOffset) {
  448. if (!buffer) return 0;
  449. uint8_t *basePtr = buffer->GetPointer();
  450. if (!basePtr) return 0;
  451. size_t offset = accOffset + byteOffset;
  452. if (buffer->EncodedRegion_Current != nullptr) {
  453. const size_t begin = buffer->EncodedRegion_Current->Offset;
  454. const size_t end = begin + buffer->EncodedRegion_Current->DecodedData_Length;
  455. if ((offset >= begin) && (offset < end))
  456. return &buffer->EncodedRegion_Current->DecodedData[offset - begin];
  457. }
  458. return basePtr + offset;
  459. }
  460. //
  461. // struct Accessor
  462. //
  463. inline void Accessor::Sparse::PopulateData(size_t numBytes, uint8_t *bytes) {
  464. if (bytes) {
  465. data.assign(bytes, bytes + numBytes);
  466. } else {
  467. data.resize(numBytes, 0x00);
  468. }
  469. }
  470. inline void Accessor::Sparse::PatchData(unsigned int elementSize) {
  471. uint8_t *pIndices = indices->GetPointer(indicesByteOffset);
  472. const unsigned int indexSize = int(ComponentTypeSize(indicesType));
  473. uint8_t *indicesEnd = pIndices + count * indexSize;
  474. uint8_t *pValues = values->GetPointer(valuesByteOffset);
  475. while (pIndices != indicesEnd) {
  476. size_t offset;
  477. switch (indicesType) {
  478. case ComponentType_UNSIGNED_BYTE:
  479. offset = *pIndices;
  480. break;
  481. case ComponentType_UNSIGNED_SHORT:
  482. offset = *reinterpret_cast<uint16_t *>(pIndices);
  483. break;
  484. case ComponentType_UNSIGNED_INT:
  485. offset = *reinterpret_cast<uint32_t *>(pIndices);
  486. break;
  487. default:
  488. // have fun with float and negative values from signed types as indices.
  489. throw DeadlyImportError("Unsupported component type in index.");
  490. }
  491. offset *= elementSize;
  492. std::memcpy(data.data() + offset, pValues, elementSize);
  493. pValues += elementSize;
  494. pIndices += indexSize;
  495. }
  496. }
  497. inline void Accessor::Read(Value &obj, Asset &r) {
  498. if (Value *bufferViewVal = FindUInt(obj, "bufferView")) {
  499. bufferView = r.bufferViews.Retrieve(bufferViewVal->GetUint());
  500. }
  501. byteOffset = MemberOrDefault(obj, "byteOffset", size_t(0));
  502. componentType = MemberOrDefault(obj, "componentType", ComponentType_BYTE);
  503. count = MemberOrDefault(obj, "count", size_t(0));
  504. const char *typestr;
  505. type = ReadMember(obj, "type", typestr) ? AttribType::FromString(typestr) : AttribType::SCALAR;
  506. if (Value *sparseValue = FindObject(obj, "sparse")) {
  507. sparse.reset(new Sparse);
  508. // count
  509. ReadMember(*sparseValue, "count", sparse->count);
  510. // indices
  511. if (Value *indicesValue = FindObject(*sparseValue, "indices")) {
  512. //indices bufferView
  513. Value *indiceViewID = FindUInt(*indicesValue, "bufferView");
  514. sparse->indices = r.bufferViews.Retrieve(indiceViewID->GetUint());
  515. //indices byteOffset
  516. sparse->indicesByteOffset = MemberOrDefault(*indicesValue, "byteOffset", size_t(0));
  517. //indices componentType
  518. sparse->indicesType = MemberOrDefault(*indicesValue, "componentType", ComponentType_BYTE);
  519. //sparse->indices->Read(*indicesValue, r);
  520. }
  521. // value
  522. if (Value *valuesValue = FindObject(*sparseValue, "values")) {
  523. //value bufferView
  524. Value *valueViewID = FindUInt(*valuesValue, "bufferView");
  525. sparse->values = r.bufferViews.Retrieve(valueViewID->GetUint());
  526. //value byteOffset
  527. sparse->valuesByteOffset = MemberOrDefault(*valuesValue, "byteOffset", size_t(0));
  528. //sparse->values->Read(*valuesValue, r);
  529. }
  530. // indicesType
  531. sparse->indicesType = MemberOrDefault(*sparseValue, "componentType", ComponentType_UNSIGNED_SHORT);
  532. const unsigned int elementSize = GetElementSize();
  533. const size_t dataSize = count * elementSize;
  534. sparse->PopulateData(dataSize, bufferView ? bufferView->GetPointer(byteOffset) : 0);
  535. sparse->PatchData(elementSize);
  536. }
  537. }
  538. inline unsigned int Accessor::GetNumComponents() {
  539. return AttribType::GetNumComponents(type);
  540. }
  541. inline unsigned int Accessor::GetBytesPerComponent() {
  542. return int(ComponentTypeSize(componentType));
  543. }
  544. inline unsigned int Accessor::GetElementSize() {
  545. return GetNumComponents() * GetBytesPerComponent();
  546. }
  547. inline uint8_t *Accessor::GetPointer() {
  548. if (sparse)
  549. return sparse->data.data();
  550. if (!bufferView || !bufferView->buffer) return 0;
  551. uint8_t *basePtr = bufferView->buffer->GetPointer();
  552. if (!basePtr) return 0;
  553. size_t offset = byteOffset + bufferView->byteOffset;
  554. // Check if region is encoded.
  555. if (bufferView->buffer->EncodedRegion_Current != nullptr) {
  556. const size_t begin = bufferView->buffer->EncodedRegion_Current->Offset;
  557. const size_t end = begin + bufferView->buffer->EncodedRegion_Current->DecodedData_Length;
  558. if ((offset >= begin) && (offset < end))
  559. return &bufferView->buffer->EncodedRegion_Current->DecodedData[offset - begin];
  560. }
  561. return basePtr + offset;
  562. }
  563. namespace {
  564. inline void CopyData(size_t count,
  565. const uint8_t *src, size_t src_stride,
  566. uint8_t *dst, size_t dst_stride) {
  567. if (src_stride == dst_stride) {
  568. memcpy(dst, src, count * src_stride);
  569. } else {
  570. size_t sz = std::min(src_stride, dst_stride);
  571. for (size_t i = 0; i < count; ++i) {
  572. memcpy(dst, src, sz);
  573. if (sz < dst_stride) {
  574. memset(dst + sz, 0, dst_stride - sz);
  575. }
  576. src += src_stride;
  577. dst += dst_stride;
  578. }
  579. }
  580. }
  581. } // namespace
  582. template <class T>
  583. void Accessor::ExtractData(T *&outData) {
  584. uint8_t *data = GetPointer();
  585. if (!data) {
  586. throw DeadlyImportError("GLTF2: data is nullptr.");
  587. }
  588. const size_t elemSize = GetElementSize();
  589. const size_t totalSize = elemSize * count;
  590. const size_t stride = bufferView && bufferView->byteStride ? bufferView->byteStride : elemSize;
  591. const size_t targetElemSize = sizeof(T);
  592. ai_assert(elemSize <= targetElemSize);
  593. ai_assert(count * stride <= (bufferView ? bufferView->byteLength : sparse->data.size()));
  594. outData = new T[count];
  595. if (stride == elemSize && targetElemSize == elemSize) {
  596. memcpy(outData, data, totalSize);
  597. } else {
  598. for (size_t i = 0; i < count; ++i) {
  599. memcpy(outData + i, data + i * stride, elemSize);
  600. }
  601. }
  602. }
  603. inline void Accessor::WriteData(size_t _count, const void *src_buffer, size_t src_stride) {
  604. uint8_t *buffer_ptr = bufferView->buffer->GetPointer();
  605. size_t offset = byteOffset + bufferView->byteOffset;
  606. size_t dst_stride = GetNumComponents() * GetBytesPerComponent();
  607. const uint8_t *src = reinterpret_cast<const uint8_t *>(src_buffer);
  608. uint8_t *dst = reinterpret_cast<uint8_t *>(buffer_ptr + offset);
  609. ai_assert(dst + _count * dst_stride <= buffer_ptr + bufferView->buffer->byteLength);
  610. CopyData(_count, src, src_stride, dst, dst_stride);
  611. }
  612. inline void Accessor::WriteSparseValues(size_t _count, const void *src_data, size_t src_dataStride) {
  613. if (!sparse)
  614. return;
  615. // values
  616. uint8_t *value_buffer_ptr = sparse->values->buffer->GetPointer();
  617. size_t value_offset = sparse->valuesByteOffset + sparse->values->byteOffset;
  618. size_t value_dst_stride = GetNumComponents() * GetBytesPerComponent();
  619. const uint8_t *value_src = reinterpret_cast<const uint8_t *>(src_data);
  620. uint8_t *value_dst = reinterpret_cast<uint8_t *>(value_buffer_ptr + value_offset);
  621. ai_assert(value_dst + _count * value_dst_stride <= value_buffer_ptr + sparse->values->buffer->byteLength);
  622. CopyData(_count, value_src, src_dataStride, value_dst, value_dst_stride);
  623. }
  624. inline void Accessor::WriteSparseIndices(size_t _count, const void *src_idx, size_t src_idxStride) {
  625. if (!sparse)
  626. return;
  627. // indices
  628. uint8_t *indices_buffer_ptr = sparse->indices->buffer->GetPointer();
  629. size_t indices_offset = sparse->indicesByteOffset + sparse->indices->byteOffset;
  630. size_t indices_dst_stride = 1 * sizeof(unsigned short);
  631. const uint8_t *indices_src = reinterpret_cast<const uint8_t *>(src_idx);
  632. uint8_t *indices_dst = reinterpret_cast<uint8_t *>(indices_buffer_ptr + indices_offset);
  633. ai_assert(indices_dst + _count * indices_dst_stride <= indices_buffer_ptr + sparse->indices->buffer->byteLength);
  634. CopyData(_count, indices_src, src_idxStride, indices_dst, indices_dst_stride);
  635. }
  636. inline Accessor::Indexer::Indexer(Accessor &acc) :
  637. accessor(acc),
  638. data(acc.GetPointer()),
  639. elemSize(acc.GetElementSize()),
  640. stride(acc.bufferView && acc.bufferView->byteStride ? acc.bufferView->byteStride : elemSize) {
  641. }
  642. //! Accesses the i-th value as defined by the accessor
  643. template <class T>
  644. T Accessor::Indexer::GetValue(int i) {
  645. ai_assert(data);
  646. ai_assert(i * stride < accessor.bufferView->byteLength);
  647. T value = T();
  648. memcpy(&value, data + i * stride, elemSize);
  649. //value >>= 8 * (sizeof(T) - elemSize);
  650. return value;
  651. }
  652. inline Image::Image() :
  653. width(0),
  654. height(0),
  655. mDataLength(0) {
  656. }
  657. inline void Image::Read(Value &obj, Asset &r) {
  658. if (!mDataLength) {
  659. Value *curUri = FindString(obj, "uri");
  660. if (nullptr != curUri) {
  661. const char *uristr = curUri->GetString();
  662. glTFCommon::Util::DataURI dataURI;
  663. if (ParseDataURI(uristr, curUri->GetStringLength(), dataURI)) {
  664. mimeType = dataURI.mediaType;
  665. if (dataURI.base64) {
  666. uint8_t *ptr = nullptr;
  667. mDataLength = glTFCommon::Util::DecodeBase64(dataURI.data, dataURI.dataLength, ptr);
  668. mData.reset(ptr);
  669. }
  670. } else {
  671. this->uri = uristr;
  672. }
  673. } else if (Value *bufferViewVal = FindUInt(obj, "bufferView")) {
  674. this->bufferView = r.bufferViews.Retrieve(bufferViewVal->GetUint());
  675. Ref<Buffer> buffer = this->bufferView->buffer;
  676. this->mDataLength = this->bufferView->byteLength;
  677. // maybe this memcpy could be avoided if aiTexture does not delete[] pcData at destruction.
  678. this->mData.reset(new uint8_t[this->mDataLength]);
  679. memcpy(this->mData.get(), buffer->GetPointer() + this->bufferView->byteOffset, this->mDataLength);
  680. if (Value *mtype = FindString(obj, "mimeType")) {
  681. this->mimeType = mtype->GetString();
  682. }
  683. }
  684. }
  685. }
  686. inline uint8_t *Image::StealData() {
  687. mDataLength = 0;
  688. return mData.release();
  689. }
  690. // Never take over the ownership of data whenever binary or not
  691. inline void Image::SetData(uint8_t *data, size_t length, Asset &r) {
  692. Ref<Buffer> b = r.GetBodyBuffer();
  693. if (b) { // binary file: append to body
  694. std::string bvId = r.FindUniqueID(this->id, "imgdata");
  695. bufferView = r.bufferViews.Create(bvId);
  696. bufferView->buffer = b;
  697. bufferView->byteLength = length;
  698. bufferView->byteOffset = b->AppendData(data, length);
  699. } else { // text file: will be stored as a data uri
  700. uint8_t *temp = new uint8_t[length];
  701. memcpy(temp, data, length);
  702. this->mData.reset(temp);
  703. this->mDataLength = length;
  704. }
  705. }
  706. inline void Sampler::Read(Value &obj, Asset & /*r*/) {
  707. SetDefaults();
  708. ReadMember(obj, "name", name);
  709. ReadMember(obj, "magFilter", magFilter);
  710. ReadMember(obj, "minFilter", minFilter);
  711. ReadMember(obj, "wrapS", wrapS);
  712. ReadMember(obj, "wrapT", wrapT);
  713. }
  714. inline void Sampler::SetDefaults() {
  715. //only wrapping modes have defaults
  716. wrapS = SamplerWrap::Repeat;
  717. wrapT = SamplerWrap::Repeat;
  718. magFilter = SamplerMagFilter::UNSET;
  719. minFilter = SamplerMinFilter::UNSET;
  720. }
  721. inline void Texture::Read(Value &obj, Asset &r) {
  722. if (Value *sourceVal = FindUInt(obj, "source")) {
  723. source = r.images.Retrieve(sourceVal->GetUint());
  724. }
  725. if (Value *samplerVal = FindUInt(obj, "sampler")) {
  726. sampler = r.samplers.Retrieve(samplerVal->GetUint());
  727. }
  728. }
  729. namespace {
  730. inline void SetTextureProperties(Asset &r, Value *prop, TextureInfo &out) {
  731. if (r.extensionsUsed.KHR_texture_transform) {
  732. if (Value *extensions = FindObject(*prop, "extensions")) {
  733. out.textureTransformSupported = true;
  734. if (Value *pKHR_texture_transform = FindObject(*extensions, "KHR_texture_transform")) {
  735. if (Value *array = FindArray(*pKHR_texture_transform, "offset")) {
  736. out.TextureTransformExt_t.offset[0] = (*array)[0].GetFloat();
  737. out.TextureTransformExt_t.offset[1] = (*array)[1].GetFloat();
  738. } else {
  739. out.TextureTransformExt_t.offset[0] = 0;
  740. out.TextureTransformExt_t.offset[1] = 0;
  741. }
  742. if (!ReadMember(*pKHR_texture_transform, "rotation", out.TextureTransformExt_t.rotation)) {
  743. out.TextureTransformExt_t.rotation = 0;
  744. }
  745. if (Value *array = FindArray(*pKHR_texture_transform, "scale")) {
  746. out.TextureTransformExt_t.scale[0] = (*array)[0].GetFloat();
  747. out.TextureTransformExt_t.scale[1] = (*array)[1].GetFloat();
  748. } else {
  749. out.TextureTransformExt_t.scale[0] = 1;
  750. out.TextureTransformExt_t.scale[1] = 1;
  751. }
  752. }
  753. }
  754. }
  755. if (Value *index = FindUInt(*prop, "index")) {
  756. out.texture = r.textures.Retrieve(index->GetUint());
  757. }
  758. if (Value *texcoord = FindUInt(*prop, "texCoord")) {
  759. out.texCoord = texcoord->GetUint();
  760. }
  761. }
  762. inline void ReadTextureProperty(Asset &r, Value &vals, const char *propName, TextureInfo &out) {
  763. if (Value *prop = FindMember(vals, propName)) {
  764. SetTextureProperties(r, prop, out);
  765. }
  766. }
  767. inline void ReadTextureProperty(Asset &r, Value &vals, const char *propName, NormalTextureInfo &out) {
  768. if (Value *prop = FindMember(vals, propName)) {
  769. SetTextureProperties(r, prop, out);
  770. if (Value *scale = FindNumber(*prop, "scale")) {
  771. out.scale = static_cast<float>(scale->GetDouble());
  772. }
  773. }
  774. }
  775. inline void ReadTextureProperty(Asset &r, Value &vals, const char *propName, OcclusionTextureInfo &out) {
  776. if (Value *prop = FindMember(vals, propName)) {
  777. SetTextureProperties(r, prop, out);
  778. if (Value *strength = FindNumber(*prop, "strength")) {
  779. out.strength = static_cast<float>(strength->GetDouble());
  780. }
  781. }
  782. }
  783. } // namespace
  784. inline void Material::Read(Value &material, Asset &r) {
  785. SetDefaults();
  786. if (Value *curPbrMetallicRoughness = FindObject(material, "pbrMetallicRoughness")) {
  787. ReadMember(*curPbrMetallicRoughness, "baseColorFactor", this->pbrMetallicRoughness.baseColorFactor);
  788. ReadTextureProperty(r, *curPbrMetallicRoughness, "baseColorTexture", this->pbrMetallicRoughness.baseColorTexture);
  789. ReadTextureProperty(r, *curPbrMetallicRoughness, "metallicRoughnessTexture", this->pbrMetallicRoughness.metallicRoughnessTexture);
  790. ReadMember(*curPbrMetallicRoughness, "metallicFactor", this->pbrMetallicRoughness.metallicFactor);
  791. ReadMember(*curPbrMetallicRoughness, "roughnessFactor", this->pbrMetallicRoughness.roughnessFactor);
  792. }
  793. ReadTextureProperty(r, material, "normalTexture", this->normalTexture);
  794. ReadTextureProperty(r, material, "occlusionTexture", this->occlusionTexture);
  795. ReadTextureProperty(r, material, "emissiveTexture", this->emissiveTexture);
  796. ReadMember(material, "emissiveFactor", this->emissiveFactor);
  797. ReadMember(material, "doubleSided", this->doubleSided);
  798. ReadMember(material, "alphaMode", this->alphaMode);
  799. ReadMember(material, "alphaCutoff", this->alphaCutoff);
  800. if (Value *extensions = FindObject(material, "extensions")) {
  801. if (r.extensionsUsed.KHR_materials_pbrSpecularGlossiness) {
  802. if (Value *curPbrSpecularGlossiness = FindObject(*extensions, "KHR_materials_pbrSpecularGlossiness")) {
  803. PbrSpecularGlossiness pbrSG;
  804. ReadMember(*curPbrSpecularGlossiness, "diffuseFactor", pbrSG.diffuseFactor);
  805. ReadTextureProperty(r, *curPbrSpecularGlossiness, "diffuseTexture", pbrSG.diffuseTexture);
  806. ReadTextureProperty(r, *curPbrSpecularGlossiness, "specularGlossinessTexture", pbrSG.specularGlossinessTexture);
  807. ReadMember(*curPbrSpecularGlossiness, "specularFactor", pbrSG.specularFactor);
  808. ReadMember(*curPbrSpecularGlossiness, "glossinessFactor", pbrSG.glossinessFactor);
  809. this->pbrSpecularGlossiness = Nullable<PbrSpecularGlossiness>(pbrSG);
  810. }
  811. }
  812. if (r.extensionsUsed.KHR_texture_transform) {
  813. }
  814. unlit = nullptr != FindObject(*extensions, "KHR_materials_unlit");
  815. }
  816. }
  817. namespace {
  818. void SetVector(vec4 &v, const float (&in)[4]) {
  819. v[0] = in[0];
  820. v[1] = in[1];
  821. v[2] = in[2];
  822. v[3] = in[3];
  823. }
  824. void SetVector(vec3 &v, const float (&in)[3]) {
  825. v[0] = in[0];
  826. v[1] = in[1];
  827. v[2] = in[2];
  828. }
  829. } // namespace
  830. inline void Material::SetDefaults() {
  831. //pbr materials
  832. SetVector(pbrMetallicRoughness.baseColorFactor, defaultBaseColor);
  833. pbrMetallicRoughness.metallicFactor = 1.0;
  834. pbrMetallicRoughness.roughnessFactor = 1.0;
  835. SetVector(emissiveFactor, defaultEmissiveFactor);
  836. alphaMode = "OPAQUE";
  837. alphaCutoff = 0.5;
  838. doubleSided = false;
  839. unlit = false;
  840. }
  841. inline void PbrSpecularGlossiness::SetDefaults() {
  842. //pbrSpecularGlossiness properties
  843. SetVector(diffuseFactor, defaultDiffuseFactor);
  844. SetVector(specularFactor, defaultSpecularFactor);
  845. glossinessFactor = 1.0;
  846. }
  847. namespace {
  848. template <int N>
  849. inline int Compare(const char *attr, const char (&str)[N]) {
  850. return (strncmp(attr, str, N - 1) == 0) ? N - 1 : 0;
  851. }
  852. #ifdef _WIN32
  853. #pragma warning(push)
  854. #pragma warning(disable : 4706)
  855. #endif // _WIN32
  856. inline bool GetAttribVector(Mesh::Primitive &p, const char *attr, Mesh::AccessorList *&v, int &pos) {
  857. if ((pos = Compare(attr, "POSITION"))) {
  858. v = &(p.attributes.position);
  859. } else if ((pos = Compare(attr, "NORMAL"))) {
  860. v = &(p.attributes.normal);
  861. } else if ((pos = Compare(attr, "TANGENT"))) {
  862. v = &(p.attributes.tangent);
  863. } else if ((pos = Compare(attr, "TEXCOORD"))) {
  864. v = &(p.attributes.texcoord);
  865. } else if ((pos = Compare(attr, "COLOR"))) {
  866. v = &(p.attributes.color);
  867. } else if ((pos = Compare(attr, "JOINT"))) {
  868. v = &(p.attributes.joint);
  869. } else if ((pos = Compare(attr, "JOINTMATRIX"))) {
  870. v = &(p.attributes.jointmatrix);
  871. } else if ((pos = Compare(attr, "WEIGHT"))) {
  872. v = &(p.attributes.weight);
  873. } else
  874. return false;
  875. return true;
  876. }
  877. inline bool GetAttribTargetVector(Mesh::Primitive &p, const int targetIndex, const char *attr, Mesh::AccessorList *&v, int &pos) {
  878. if ((pos = Compare(attr, "POSITION"))) {
  879. v = &(p.targets[targetIndex].position);
  880. } else if ((pos = Compare(attr, "NORMAL"))) {
  881. v = &(p.targets[targetIndex].normal);
  882. } else if ((pos = Compare(attr, "TANGENT"))) {
  883. v = &(p.targets[targetIndex].tangent);
  884. } else
  885. return false;
  886. return true;
  887. }
  888. } // namespace
  889. inline void Mesh::Read(Value &pJSON_Object, Asset &pAsset_Root) {
  890. Value *curName = FindMember(pJSON_Object, "name");
  891. if (nullptr != curName) {
  892. name = curName->GetString();
  893. }
  894. /****************** Mesh primitives ******************/
  895. Value *curPrimitives = FindArray(pJSON_Object, "primitives");
  896. if (nullptr != curPrimitives) {
  897. this->primitives.resize(curPrimitives->Size());
  898. for (unsigned int i = 0; i < curPrimitives->Size(); ++i) {
  899. Value &primitive = (*curPrimitives)[i];
  900. Primitive &prim = this->primitives[i];
  901. prim.mode = MemberOrDefault(primitive, "mode", PrimitiveMode_TRIANGLES);
  902. if (Value *attrs = FindObject(primitive, "attributes")) {
  903. for (Value::MemberIterator it = attrs->MemberBegin(); it != attrs->MemberEnd(); ++it) {
  904. if (!it->value.IsUint()) continue;
  905. const char *attr = it->name.GetString();
  906. // Valid attribute semantics include POSITION, NORMAL, TANGENT, TEXCOORD, COLOR, JOINT, JOINTMATRIX,
  907. // and WEIGHT.Attribute semantics can be of the form[semantic]_[set_index], e.g., TEXCOORD_0, TEXCOORD_1, etc.
  908. int undPos = 0;
  909. Mesh::AccessorList *vec = 0;
  910. if (GetAttribVector(prim, attr, vec, undPos)) {
  911. size_t idx = (attr[undPos] == '_') ? atoi(attr + undPos + 1) : 0;
  912. if ((*vec).size() <= idx) (*vec).resize(idx + 1);
  913. (*vec)[idx] = pAsset_Root.accessors.Retrieve(it->value.GetUint());
  914. }
  915. }
  916. }
  917. Value *targetsArray = FindArray(primitive, "targets");
  918. if (nullptr != targetsArray) {
  919. prim.targets.resize(targetsArray->Size());
  920. for (unsigned int j = 0; j < targetsArray->Size(); ++j) {
  921. Value &target = (*targetsArray)[j];
  922. if (!target.IsObject()) {
  923. continue;
  924. }
  925. for (Value::MemberIterator it = target.MemberBegin(); it != target.MemberEnd(); ++it) {
  926. if (!it->value.IsUint()) {
  927. continue;
  928. }
  929. const char *attr = it->name.GetString();
  930. // Valid attribute semantics include POSITION, NORMAL, TANGENT
  931. int undPos = 0;
  932. Mesh::AccessorList *vec = 0;
  933. if (GetAttribTargetVector(prim, j, attr, vec, undPos)) {
  934. size_t idx = (attr[undPos] == '_') ? atoi(attr + undPos + 1) : 0;
  935. if ((*vec).size() <= idx) {
  936. (*vec).resize(idx + 1);
  937. }
  938. (*vec)[idx] = pAsset_Root.accessors.Retrieve(it->value.GetUint());
  939. }
  940. }
  941. }
  942. }
  943. if (Value *indices = FindUInt(primitive, "indices")) {
  944. prim.indices = pAsset_Root.accessors.Retrieve(indices->GetUint());
  945. }
  946. if (Value *material = FindUInt(primitive, "material")) {
  947. prim.material = pAsset_Root.materials.Retrieve(material->GetUint());
  948. }
  949. }
  950. }
  951. Value *curWeights = FindArray(pJSON_Object, "weights");
  952. if (nullptr != curWeights) {
  953. this->weights.resize(curWeights->Size());
  954. for (unsigned int i = 0; i < curWeights->Size(); ++i) {
  955. Value &weightValue = (*curWeights)[i];
  956. if (weightValue.IsNumber()) {
  957. this->weights[i] = weightValue.GetFloat();
  958. }
  959. }
  960. }
  961. Value *extras = FindObject(pJSON_Object, "extras");
  962. if (nullptr != extras) {
  963. if (Value *curTargetNames = FindArray(*extras, "targetNames")) {
  964. this->targetNames.resize(curTargetNames->Size());
  965. for (unsigned int i = 0; i < curTargetNames->Size(); ++i) {
  966. Value &targetNameValue = (*curTargetNames)[i];
  967. if (targetNameValue.IsString()) {
  968. this->targetNames[i] = targetNameValue.GetString();
  969. }
  970. }
  971. }
  972. }
  973. }
  974. inline void Camera::Read(Value &obj, Asset & /*r*/) {
  975. std::string type_string = std::string(MemberOrDefault(obj, "type", "perspective"));
  976. if (type_string == "orthographic") {
  977. type = Camera::Orthographic;
  978. } else {
  979. type = Camera::Perspective;
  980. }
  981. const char *subobjId = (type == Camera::Orthographic) ? "orthographic" : "perspective";
  982. Value *it = FindObject(obj, subobjId);
  983. if (!it) throw DeadlyImportError("GLTF: Camera missing its parameters");
  984. if (type == Camera::Perspective) {
  985. cameraProperties.perspective.aspectRatio = MemberOrDefault(*it, "aspectRatio", 0.f);
  986. cameraProperties.perspective.yfov = MemberOrDefault(*it, "yfov", 3.1415f / 2.f);
  987. cameraProperties.perspective.zfar = MemberOrDefault(*it, "zfar", 100.f);
  988. cameraProperties.perspective.znear = MemberOrDefault(*it, "znear", 0.01f);
  989. } else {
  990. cameraProperties.ortographic.xmag = MemberOrDefault(*it, "xmag", 1.f);
  991. cameraProperties.ortographic.ymag = MemberOrDefault(*it, "ymag", 1.f);
  992. cameraProperties.ortographic.zfar = MemberOrDefault(*it, "zfar", 100.f);
  993. cameraProperties.ortographic.znear = MemberOrDefault(*it, "znear", 0.01f);
  994. }
  995. }
  996. inline void Light::Read(Value &obj, Asset & /*r*/) {
  997. #ifndef M_PI
  998. const float M_PI = 3.14159265358979323846f;
  999. #endif
  1000. std::string type_string;
  1001. ReadMember(obj, "type", type_string);
  1002. if (type_string == "directional")
  1003. type = Light::Directional;
  1004. else if (type_string == "point")
  1005. type = Light::Point;
  1006. else
  1007. type = Light::Spot;
  1008. name = MemberOrDefault(obj, "name", "");
  1009. SetVector(color, vec3{ 1.0f, 1.0f, 1.0f });
  1010. ReadMember(obj, "color", color);
  1011. intensity = MemberOrDefault(obj, "intensity", 1.0f);
  1012. ReadMember(obj, "range", range);
  1013. if (type == Light::Spot) {
  1014. Value *spot = FindObject(obj, "spot");
  1015. if (!spot) throw DeadlyImportError("GLTF: Light missing its spot parameters");
  1016. innerConeAngle = MemberOrDefault(*spot, "innerConeAngle", 0.0f);
  1017. outerConeAngle = MemberOrDefault(*spot, "outerConeAngle", M_PI / 4.0f);
  1018. }
  1019. }
  1020. inline CustomExtension ReadExtensions(const char *name, Value& obj) {
  1021. CustomExtension ret;
  1022. ret.name = name;
  1023. if (obj.IsObject()) {
  1024. ret.mValues.isPresent = true;
  1025. for (auto it = obj.MemberBegin(); it != obj.MemberEnd(); ++it) {
  1026. auto& val = it->value;
  1027. ret.mValues.value.push_back(ReadExtensions(it->name.GetString(), val));
  1028. }
  1029. }
  1030. else if (obj.IsArray()) {
  1031. ret.mValues.value.reserve(obj.Size());
  1032. ret.mValues.isPresent = true;
  1033. for (unsigned int i = 0; i < obj.Size(); ++i)
  1034. {
  1035. ret.mValues.value.push_back(ReadExtensions(name, obj[i]));
  1036. }
  1037. }
  1038. else if (obj.IsNumber()) {
  1039. if (obj.IsUint64()) {
  1040. ret.mUint64Value.value = obj.GetUint64();
  1041. ret.mUint64Value.isPresent = true;
  1042. } else if (obj.IsInt64()) {
  1043. ret.mInt64Value.value = obj.GetInt64();
  1044. ret.mInt64Value.isPresent = true;
  1045. } else if (obj.IsDouble()) {
  1046. ret.mDoubleValue.value = obj.GetDouble();
  1047. ret.mDoubleValue.isPresent = true;
  1048. }
  1049. }
  1050. else if (obj.IsString()) {
  1051. ReadValue(obj, ret.mStringValue);
  1052. ret.mStringValue.isPresent = true;
  1053. }
  1054. else if (obj.IsBool()) {
  1055. ret.mBoolValue.value = obj.GetBool();
  1056. ret.mBoolValue.isPresent = true;
  1057. }
  1058. return ret;
  1059. }
  1060. inline void Node::Read(Value &obj, Asset &r) {
  1061. if (name.empty()) {
  1062. name = id;
  1063. }
  1064. Value *curChildren = FindArray(obj, "children");
  1065. if (nullptr != curChildren) {
  1066. this->children.reserve(curChildren->Size());
  1067. for (unsigned int i = 0; i < curChildren->Size(); ++i) {
  1068. Value &child = (*curChildren)[i];
  1069. if (child.IsUint()) {
  1070. // get/create the child node
  1071. Ref<Node> chn = r.nodes.Retrieve(child.GetUint());
  1072. if (chn) {
  1073. this->children.push_back(chn);
  1074. }
  1075. }
  1076. }
  1077. }
  1078. Value *curMatrix = FindArray(obj, "matrix");
  1079. if (nullptr != curMatrix) {
  1080. ReadValue(*curMatrix, this->matrix);
  1081. } else {
  1082. ReadMember(obj, "translation", translation);
  1083. ReadMember(obj, "scale", scale);
  1084. ReadMember(obj, "rotation", rotation);
  1085. }
  1086. Value *curMesh = FindUInt(obj, "mesh");
  1087. if (nullptr != curMesh) {
  1088. unsigned int numMeshes = 1;
  1089. this->meshes.reserve(numMeshes);
  1090. Ref<Mesh> meshRef = r.meshes.Retrieve((*curMesh).GetUint());
  1091. if (meshRef) {
  1092. this->meshes.push_back(meshRef);
  1093. }
  1094. }
  1095. // Do not retrieve a skin here, just take a reference, to avoid infinite recursion
  1096. // Skins will be properly loaded later
  1097. Value *curSkin = FindUInt(obj, "skin");
  1098. if (nullptr != curSkin) {
  1099. this->skin = r.skins.Get(curSkin->GetUint());
  1100. }
  1101. Value *curCamera = FindUInt(obj, "camera");
  1102. if (nullptr != curCamera) {
  1103. this->camera = r.cameras.Retrieve(curCamera->GetUint());
  1104. if (this->camera) {
  1105. this->camera->id = this->id;
  1106. }
  1107. }
  1108. Value *curExtensions = FindObject(obj, "extensions");
  1109. if (nullptr != curExtensions) {
  1110. this->extensions = ReadExtensions("extensions", *curExtensions);
  1111. if (r.extensionsUsed.KHR_lights_punctual) {
  1112. if (Value *ext = FindObject(*curExtensions, "KHR_lights_punctual")) {
  1113. Value *curLight = FindUInt(*ext, "light");
  1114. if (nullptr != curLight) {
  1115. this->light = r.lights.Retrieve(curLight->GetUint());
  1116. if (this->light) {
  1117. this->light->id = this->id;
  1118. }
  1119. }
  1120. }
  1121. }
  1122. }
  1123. }
  1124. inline void Scene::Read(Value &obj, Asset &r) {
  1125. if (Value *array = FindArray(obj, "nodes")) {
  1126. for (unsigned int i = 0; i < array->Size(); ++i) {
  1127. if (!(*array)[i].IsUint()) continue;
  1128. Ref<Node> node = r.nodes.Retrieve((*array)[i].GetUint());
  1129. if (node)
  1130. this->nodes.push_back(node);
  1131. }
  1132. }
  1133. }
  1134. inline void Skin::Read(Value &obj, Asset &r) {
  1135. if (Value *matrices = FindUInt(obj, "inverseBindMatrices")) {
  1136. inverseBindMatrices = r.accessors.Retrieve(matrices->GetUint());
  1137. }
  1138. if (Value *joints = FindArray(obj, "joints")) {
  1139. for (unsigned i = 0; i < joints->Size(); ++i) {
  1140. if (!(*joints)[i].IsUint()) continue;
  1141. Ref<Node> node = r.nodes.Retrieve((*joints)[i].GetUint());
  1142. if (node) {
  1143. this->jointNames.push_back(node);
  1144. }
  1145. }
  1146. }
  1147. }
  1148. inline void Animation::Read(Value &obj, Asset &r) {
  1149. Value *curSamplers = FindArray(obj, "samplers");
  1150. if (nullptr != curSamplers) {
  1151. for (unsigned i = 0; i < curSamplers->Size(); ++i) {
  1152. Value &sampler = (*curSamplers)[i];
  1153. Sampler s;
  1154. if (Value *input = FindUInt(sampler, "input")) {
  1155. s.input = r.accessors.Retrieve(input->GetUint());
  1156. }
  1157. if (Value *output = FindUInt(sampler, "output")) {
  1158. s.output = r.accessors.Retrieve(output->GetUint());
  1159. }
  1160. s.interpolation = Interpolation_LINEAR;
  1161. if (Value *interpolation = FindString(sampler, "interpolation")) {
  1162. const std::string interp = interpolation->GetString();
  1163. if (interp == "LINEAR") {
  1164. s.interpolation = Interpolation_LINEAR;
  1165. } else if (interp == "STEP") {
  1166. s.interpolation = Interpolation_STEP;
  1167. } else if (interp == "CUBICSPLINE") {
  1168. s.interpolation = Interpolation_CUBICSPLINE;
  1169. }
  1170. }
  1171. this->samplers.push_back(s);
  1172. }
  1173. }
  1174. Value *curChannels = FindArray(obj, "channels");
  1175. if (nullptr != curChannels) {
  1176. for (unsigned i = 0; i < curChannels->Size(); ++i) {
  1177. Value &channel = (*curChannels)[i];
  1178. Channel c;
  1179. Value *curSampler = FindUInt(channel, "sampler");
  1180. if (nullptr != curSampler) {
  1181. c.sampler = curSampler->GetUint();
  1182. }
  1183. if (Value *target = FindObject(channel, "target")) {
  1184. if (Value *node = FindUInt(*target, "node")) {
  1185. c.target.node = r.nodes.Retrieve(node->GetUint());
  1186. }
  1187. if (Value *path = FindString(*target, "path")) {
  1188. const std::string p = path->GetString();
  1189. if (p == "translation") {
  1190. c.target.path = AnimationPath_TRANSLATION;
  1191. } else if (p == "rotation") {
  1192. c.target.path = AnimationPath_ROTATION;
  1193. } else if (p == "scale") {
  1194. c.target.path = AnimationPath_SCALE;
  1195. } else if (p == "weights") {
  1196. c.target.path = AnimationPath_WEIGHTS;
  1197. }
  1198. }
  1199. }
  1200. this->channels.push_back(c);
  1201. }
  1202. }
  1203. }
  1204. inline void AssetMetadata::Read(Document &doc) {
  1205. if (Value *obj = FindObject(doc, "asset")) {
  1206. ReadMember(*obj, "copyright", copyright);
  1207. ReadMember(*obj, "generator", generator);
  1208. if (Value *versionString = FindString(*obj, "version")) {
  1209. version = versionString->GetString();
  1210. } else if (Value *versionNumber = FindNumber(*obj, "version")) {
  1211. char buf[4];
  1212. ai_snprintf(buf, 4, "%.1f", versionNumber->GetDouble());
  1213. version = buf;
  1214. }
  1215. Value *curProfile = FindObject(*obj, "profile");
  1216. if (nullptr != curProfile) {
  1217. ReadMember(*curProfile, "api", this->profile.api);
  1218. ReadMember(*curProfile, "version", this->profile.version);
  1219. }
  1220. }
  1221. if (version.empty() || version[0] != '2') {
  1222. throw DeadlyImportError("GLTF: Unsupported glTF version: " + version);
  1223. }
  1224. }
  1225. //
  1226. // Asset methods implementation
  1227. //
  1228. inline void Asset::ReadBinaryHeader(IOStream &stream, std::vector<char> &sceneData) {
  1229. ASSIMP_LOG_DEBUG("Reading GLTF2 binary");
  1230. GLB_Header header;
  1231. if (stream.Read(&header, sizeof(header), 1) != 1) {
  1232. throw DeadlyImportError("GLTF: Unable to read the file header");
  1233. }
  1234. if (strncmp((char *)header.magic, AI_GLB_MAGIC_NUMBER, sizeof(header.magic)) != 0) {
  1235. throw DeadlyImportError("GLTF: Invalid binary glTF file");
  1236. }
  1237. AI_SWAP4(header.version);
  1238. asset.version = to_string(header.version);
  1239. if (header.version != 2) {
  1240. throw DeadlyImportError("GLTF: Unsupported binary glTF version");
  1241. }
  1242. GLB_Chunk chunk;
  1243. if (stream.Read(&chunk, sizeof(chunk), 1) != 1) {
  1244. throw DeadlyImportError("GLTF: Unable to read JSON chunk");
  1245. }
  1246. AI_SWAP4(chunk.chunkLength);
  1247. AI_SWAP4(chunk.chunkType);
  1248. if (chunk.chunkType != ChunkType_JSON) {
  1249. throw DeadlyImportError("GLTF: JSON chunk missing");
  1250. }
  1251. // read the scene data
  1252. mSceneLength = chunk.chunkLength;
  1253. sceneData.resize(mSceneLength + 1);
  1254. sceneData[mSceneLength] = '\0';
  1255. if (stream.Read(&sceneData[0], 1, mSceneLength) != mSceneLength) {
  1256. throw DeadlyImportError("GLTF: Could not read the file contents");
  1257. }
  1258. uint32_t padding = ((chunk.chunkLength + 3) & ~3) - chunk.chunkLength;
  1259. if (padding > 0) {
  1260. stream.Seek(padding, aiOrigin_CUR);
  1261. }
  1262. AI_SWAP4(header.length);
  1263. mBodyOffset = 12 + 8 + chunk.chunkLength + padding + 8;
  1264. if (header.length >= mBodyOffset) {
  1265. if (stream.Read(&chunk, sizeof(chunk), 1) != 1) {
  1266. throw DeadlyImportError("GLTF: Unable to read BIN chunk");
  1267. }
  1268. AI_SWAP4(chunk.chunkLength);
  1269. AI_SWAP4(chunk.chunkType);
  1270. if (chunk.chunkType != ChunkType_BIN) {
  1271. throw DeadlyImportError("GLTF: BIN chunk missing");
  1272. }
  1273. mBodyLength = chunk.chunkLength;
  1274. } else {
  1275. mBodyOffset = mBodyLength = 0;
  1276. }
  1277. }
  1278. inline void Asset::Load(const std::string &pFile, bool isBinary) {
  1279. ASSIMP_LOG_DEBUG("Loading GLTF2 asset");
  1280. mCurrentAssetDir.clear();
  1281. /*int pos = std::max(int(pFile.rfind('/')), int(pFile.rfind('\\')));
  1282. if (pos != int(std::string::npos)) */
  1283. mCurrentAssetDir = glTFCommon::getCurrentAssetDir(pFile);
  1284. shared_ptr<IOStream> stream(OpenFile(pFile.c_str(), "rb", true));
  1285. if (!stream) {
  1286. throw DeadlyImportError("GLTF: Could not open file for reading");
  1287. }
  1288. // is binary? then read the header
  1289. std::vector<char> sceneData;
  1290. if (isBinary) {
  1291. SetAsBinary(); // also creates the body buffer
  1292. ReadBinaryHeader(*stream, sceneData);
  1293. } else {
  1294. mSceneLength = stream->FileSize();
  1295. mBodyLength = 0;
  1296. // read the scene data
  1297. sceneData.resize(mSceneLength + 1);
  1298. sceneData[mSceneLength] = '\0';
  1299. if (stream->Read(&sceneData[0], 1, mSceneLength) != mSceneLength) {
  1300. throw DeadlyImportError("GLTF: Could not read the file contents");
  1301. }
  1302. }
  1303. // parse the JSON document
  1304. ASSIMP_LOG_DEBUG("Parsing GLTF2 JSON");
  1305. Document doc;
  1306. doc.ParseInsitu(&sceneData[0]);
  1307. if (doc.HasParseError()) {
  1308. char buffer[32];
  1309. ai_snprintf(buffer, 32, "%d", static_cast<int>(doc.GetErrorOffset()));
  1310. throw DeadlyImportError(std::string("GLTF: JSON parse error, offset ") + buffer + ": " + GetParseError_En(doc.GetParseError()));
  1311. }
  1312. if (!doc.IsObject()) {
  1313. throw DeadlyImportError("GLTF: JSON document root must be a JSON object");
  1314. }
  1315. // Fill the buffer instance for the current file embedded contents
  1316. if (mBodyLength > 0) {
  1317. if (!mBodyBuffer->LoadFromStream(*stream, mBodyLength, mBodyOffset)) {
  1318. throw DeadlyImportError("GLTF: Unable to read gltf file");
  1319. }
  1320. }
  1321. // Load the metadata
  1322. asset.Read(doc);
  1323. ReadExtensionsUsed(doc);
  1324. ReadExtensionsRequired(doc);
  1325. // Currently Draco is not supported
  1326. if (extensionsRequired.KHR_draco_mesh_compression) {
  1327. throw DeadlyImportError("GLTF: Draco mesh compression not currently supported.");
  1328. }
  1329. // Prepare the dictionaries
  1330. for (size_t i = 0; i < mDicts.size(); ++i) {
  1331. mDicts[i]->AttachToDocument(doc);
  1332. }
  1333. // Read the "scene" property, which specifies which scene to load
  1334. // and recursively load everything referenced by it
  1335. unsigned int sceneIndex = 0;
  1336. Value *curScene = FindUInt(doc, "scene");
  1337. if (nullptr != curScene) {
  1338. sceneIndex = curScene->GetUint();
  1339. }
  1340. if (Value *scenesArray = FindArray(doc, "scenes")) {
  1341. if (sceneIndex < scenesArray->Size()) {
  1342. this->scene = scenes.Retrieve(sceneIndex);
  1343. }
  1344. }
  1345. if (Value *skinsArray = FindArray(doc, "skins")) {
  1346. for (unsigned int i = 0; i < skinsArray->Size(); ++i) {
  1347. skins.Retrieve(i);
  1348. }
  1349. }
  1350. if (Value *animsArray = FindArray(doc, "animations")) {
  1351. for (unsigned int i = 0; i < animsArray->Size(); ++i) {
  1352. animations.Retrieve(i);
  1353. }
  1354. }
  1355. // Clean up
  1356. for (size_t i = 0; i < mDicts.size(); ++i) {
  1357. mDicts[i]->DetachFromDocument();
  1358. }
  1359. }
  1360. inline void Asset::SetAsBinary() {
  1361. if (!mBodyBuffer) {
  1362. mBodyBuffer = buffers.Create("binary_glTF");
  1363. mBodyBuffer->MarkAsSpecial();
  1364. }
  1365. }
  1366. // As required extensions are only a concept in glTF 2.0, this is here
  1367. // instead of glTFCommon.h
  1368. #define CHECK_REQUIRED_EXT(EXT) \
  1369. if (exts.find(#EXT) != exts.end()) extensionsRequired.EXT = true;
  1370. inline void Asset::ReadExtensionsRequired(Document &doc) {
  1371. Value *extsRequired = FindArray(doc, "extensionsRequired");
  1372. if (nullptr == extsRequired) {
  1373. return;
  1374. }
  1375. std::gltf_unordered_map<std::string, bool> exts;
  1376. for (unsigned int i = 0; i < extsRequired->Size(); ++i) {
  1377. if ((*extsRequired)[i].IsString()) {
  1378. exts[(*extsRequired)[i].GetString()] = true;
  1379. }
  1380. }
  1381. CHECK_REQUIRED_EXT(KHR_draco_mesh_compression);
  1382. #undef CHECK_REQUIRED_EXT
  1383. }
  1384. inline void Asset::ReadExtensionsUsed(Document &doc) {
  1385. Value *extsUsed = FindArray(doc, "extensionsUsed");
  1386. if (!extsUsed) return;
  1387. std::gltf_unordered_map<std::string, bool> exts;
  1388. for (unsigned int i = 0; i < extsUsed->Size(); ++i) {
  1389. if ((*extsUsed)[i].IsString()) {
  1390. exts[(*extsUsed)[i].GetString()] = true;
  1391. }
  1392. }
  1393. CHECK_EXT(KHR_materials_pbrSpecularGlossiness);
  1394. CHECK_EXT(KHR_materials_unlit);
  1395. CHECK_EXT(KHR_lights_punctual);
  1396. CHECK_EXT(KHR_texture_transform);
  1397. #undef CHECK_EXT
  1398. }
  1399. inline IOStream *Asset::OpenFile(std::string path, const char *mode, bool /*absolute*/) {
  1400. #ifdef ASSIMP_API
  1401. return mIOSystem->Open(path, mode);
  1402. #else
  1403. if (path.size() < 2) return 0;
  1404. if (!absolute && path[1] != ':' && path[0] != '/') { // relative?
  1405. path = mCurrentAssetDir + path;
  1406. }
  1407. FILE *f = fopen(path.c_str(), mode);
  1408. return f ? new IOStream(f) : 0;
  1409. #endif
  1410. }
  1411. inline std::string Asset::FindUniqueID(const std::string &str, const char *suffix) {
  1412. std::string id = str;
  1413. if (!id.empty()) {
  1414. if (mUsedIds.find(id) == mUsedIds.end())
  1415. return id;
  1416. id += "_";
  1417. }
  1418. id += suffix;
  1419. Asset::IdMap::iterator it = mUsedIds.find(id);
  1420. if (it == mUsedIds.end()) {
  1421. return id;
  1422. }
  1423. std::vector<char> buffer;
  1424. buffer.resize(id.size() + 16);
  1425. int offset = ai_snprintf(buffer.data(), buffer.size(), "%s_", id.c_str());
  1426. for (int i = 0; it != mUsedIds.end(); ++i) {
  1427. ai_snprintf(buffer.data() + offset, buffer.size() - offset, "%d", i);
  1428. id = buffer.data();
  1429. it = mUsedIds.find(id);
  1430. }
  1431. return id;
  1432. }
  1433. #ifdef _WIN32
  1434. #pragma warning(pop)
  1435. #endif // _WIN32
  1436. } // namespace glTF2