BlenderDNA.inl 28 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856
  1. /*
  2. Open Asset Import Library (assimp)
  3. ----------------------------------------------------------------------
  4. Copyright (c) 2006-2019, assimp team
  5. All rights reserved.
  6. Redistribution and use of this software in source and binary forms,
  7. with or without modification, are permitted provided that the
  8. following conditions are met:
  9. * Redistributions of source code must retain the above
  10. copyright notice, this list of conditions and the
  11. following disclaimer.
  12. * Redistributions in binary form must reproduce the above
  13. copyright notice, this list of conditions and the
  14. following disclaimer in the documentation and/or other
  15. materials provided with the distribution.
  16. * Neither the name of the assimp team, nor the names of its
  17. contributors may be used to endorse or promote products
  18. derived from this software without specific prior
  19. written permission of the assimp team.
  20. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
  21. "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
  22. LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
  23. A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
  24. OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
  25. SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
  26. LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
  27. DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
  28. THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
  29. (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
  30. OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
  31. ----------------------------------------------------------------------
  32. */
  33. /** @file BlenderDNA.inl
  34. * @brief Blender `DNA` (file format specification embedded in
  35. * blend file itself) loader.
  36. */
  37. #ifndef INCLUDED_AI_BLEND_DNA_INL
  38. #define INCLUDED_AI_BLEND_DNA_INL
  39. #include <memory>
  40. #include <assimp/TinyFormatter.h>
  41. namespace Assimp {
  42. namespace Blender {
  43. //--------------------------------------------------------------------------------
  44. const Field& Structure :: operator [] (const std::string& ss) const
  45. {
  46. std::map<std::string, size_t>::const_iterator it = indices.find(ss);
  47. if (it == indices.end()) {
  48. throw Error((Formatter::format(),
  49. "BlendDNA: Did not find a field named `",ss,"` in structure `",name,"`"
  50. ));
  51. }
  52. return fields[(*it).second];
  53. }
  54. //--------------------------------------------------------------------------------
  55. const Field* Structure :: Get (const std::string& ss) const
  56. {
  57. std::map<std::string, size_t>::const_iterator it = indices.find(ss);
  58. return it == indices.end() ? NULL : &fields[(*it).second];
  59. }
  60. //--------------------------------------------------------------------------------
  61. const Field& Structure :: operator [] (const size_t i) const
  62. {
  63. if (i >= fields.size()) {
  64. throw Error((Formatter::format(),
  65. "BlendDNA: There is no field with index `",i,"` in structure `",name,"`"
  66. ));
  67. }
  68. return fields[i];
  69. }
  70. //--------------------------------------------------------------------------------
  71. template <typename T> std::shared_ptr<ElemBase> Structure :: Allocate() const
  72. {
  73. return std::shared_ptr<T>(new T());
  74. }
  75. //--------------------------------------------------------------------------------
  76. template <typename T> void Structure :: Convert(
  77. std::shared_ptr<ElemBase> in,
  78. const FileDatabase& db) const
  79. {
  80. Convert<T> (*static_cast<T*> ( in.get() ),db);
  81. }
  82. //--------------------------------------------------------------------------------
  83. template <int error_policy, typename T, size_t M>
  84. void Structure :: ReadFieldArray(T (& out)[M], const char* name, const FileDatabase& db) const
  85. {
  86. const StreamReaderAny::pos old = db.reader->GetCurrentPos();
  87. try {
  88. const Field& f = (*this)[name];
  89. const Structure& s = db.dna[f.type];
  90. // is the input actually an array?
  91. if (!(f.flags & FieldFlag_Array)) {
  92. throw Error((Formatter::format(),"Field `",name,"` of structure `",
  93. this->name,"` ought to be an array of size ",M
  94. ));
  95. }
  96. db.reader->IncPtr(f.offset);
  97. // size conversions are always allowed, regardless of error_policy
  98. unsigned int i = 0;
  99. for(; i < std::min(f.array_sizes[0],M); ++i) {
  100. s.Convert(out[i],db);
  101. }
  102. for(; i < M; ++i) {
  103. _defaultInitializer<ErrorPolicy_Igno>()(out[i]);
  104. }
  105. }
  106. catch (const Error& e) {
  107. _defaultInitializer<error_policy>()(out,e.what());
  108. }
  109. // and recover the previous stream position
  110. db.reader->SetCurrentPos(old);
  111. #ifndef ASSIMP_BUILD_BLENDER_NO_STATS
  112. ++db.stats().fields_read;
  113. #endif
  114. }
  115. //--------------------------------------------------------------------------------
  116. template <int error_policy, typename T, size_t M, size_t N>
  117. void Structure :: ReadFieldArray2(T (& out)[M][N], const char* name, const FileDatabase& db) const
  118. {
  119. const StreamReaderAny::pos old = db.reader->GetCurrentPos();
  120. try {
  121. const Field& f = (*this)[name];
  122. const Structure& s = db.dna[f.type];
  123. // is the input actually an array?
  124. if (!(f.flags & FieldFlag_Array)) {
  125. throw Error((Formatter::format(),"Field `",name,"` of structure `",
  126. this->name,"` ought to be an array of size ",M,"*",N
  127. ));
  128. }
  129. db.reader->IncPtr(f.offset);
  130. // size conversions are always allowed, regardless of error_policy
  131. unsigned int i = 0;
  132. for(; i < std::min(f.array_sizes[0],M); ++i) {
  133. unsigned int j = 0;
  134. for(; j < std::min(f.array_sizes[1],N); ++j) {
  135. s.Convert(out[i][j],db);
  136. }
  137. for(; j < N; ++j) {
  138. _defaultInitializer<ErrorPolicy_Igno>()(out[i][j]);
  139. }
  140. }
  141. for(; i < M; ++i) {
  142. _defaultInitializer<ErrorPolicy_Igno>()(out[i]);
  143. }
  144. }
  145. catch (const Error& e) {
  146. _defaultInitializer<error_policy>()(out,e.what());
  147. }
  148. // and recover the previous stream position
  149. db.reader->SetCurrentPos(old);
  150. #ifndef ASSIMP_BUILD_BLENDER_NO_STATS
  151. ++db.stats().fields_read;
  152. #endif
  153. }
  154. //--------------------------------------------------------------------------------
  155. template <int error_policy, template <typename> class TOUT, typename T>
  156. bool Structure :: ReadFieldPtr(TOUT<T>& out, const char* name, const FileDatabase& db,
  157. bool non_recursive /*= false*/) const
  158. {
  159. const StreamReaderAny::pos old = db.reader->GetCurrentPos();
  160. Pointer ptrval;
  161. const Field* f;
  162. try {
  163. f = &(*this)[name];
  164. // sanity check, should never happen if the genblenddna script is right
  165. if (!(f->flags & FieldFlag_Pointer)) {
  166. throw Error((Formatter::format(),"Field `",name,"` of structure `",
  167. this->name,"` ought to be a pointer"));
  168. }
  169. db.reader->IncPtr(f->offset);
  170. Convert(ptrval,db);
  171. // actually it is meaningless on which Structure the Convert is called
  172. // because the `Pointer` argument triggers a special implementation.
  173. }
  174. catch (const Error& e) {
  175. _defaultInitializer<error_policy>()(out,e.what());
  176. out.reset();
  177. return false;
  178. }
  179. // resolve the pointer and load the corresponding structure
  180. const bool res = ResolvePointer(out,ptrval,db,*f, non_recursive);
  181. if(!non_recursive) {
  182. // and recover the previous stream position
  183. db.reader->SetCurrentPos(old);
  184. }
  185. #ifndef ASSIMP_BUILD_BLENDER_NO_STATS
  186. ++db.stats().fields_read;
  187. #endif
  188. return res;
  189. }
  190. //--------------------------------------------------------------------------------
  191. template <int error_policy, template <typename> class TOUT, typename T, size_t N>
  192. bool Structure :: ReadFieldPtr(TOUT<T> (&out)[N], const char* name,
  193. const FileDatabase& db) const
  194. {
  195. // XXX see if we can reduce this to call to the 'normal' ReadFieldPtr
  196. const StreamReaderAny::pos old = db.reader->GetCurrentPos();
  197. Pointer ptrval[N];
  198. const Field* f;
  199. try {
  200. f = &(*this)[name];
  201. // sanity check, should never happen if the genblenddna script is right
  202. if ((FieldFlag_Pointer|FieldFlag_Pointer) != (f->flags & (FieldFlag_Pointer|FieldFlag_Pointer))) {
  203. throw Error((Formatter::format(),"Field `",name,"` of structure `",
  204. this->name,"` ought to be a pointer AND an array"));
  205. }
  206. db.reader->IncPtr(f->offset);
  207. size_t i = 0;
  208. for(; i < std::min(f->array_sizes[0],N); ++i) {
  209. Convert(ptrval[i],db);
  210. }
  211. for(; i < N; ++i) {
  212. _defaultInitializer<ErrorPolicy_Igno>()(ptrval[i]);
  213. }
  214. // actually it is meaningless on which Structure the Convert is called
  215. // because the `Pointer` argument triggers a special implementation.
  216. }
  217. catch (const Error& e) {
  218. _defaultInitializer<error_policy>()(out,e.what());
  219. for(size_t i = 0; i < N; ++i) {
  220. out[i].reset();
  221. }
  222. return false;
  223. }
  224. bool res = true;
  225. for(size_t i = 0; i < N; ++i) {
  226. // resolve the pointer and load the corresponding structure
  227. res = ResolvePointer(out[i],ptrval[i],db,*f) && res;
  228. }
  229. // and recover the previous stream position
  230. db.reader->SetCurrentPos(old);
  231. #ifndef ASSIMP_BUILD_BLENDER_NO_STATS
  232. ++db.stats().fields_read;
  233. #endif
  234. return res;
  235. }
  236. //--------------------------------------------------------------------------------
  237. template <int error_policy, typename T>
  238. void Structure :: ReadField(T& out, const char* name, const FileDatabase& db) const
  239. {
  240. const StreamReaderAny::pos old = db.reader->GetCurrentPos();
  241. try {
  242. const Field& f = (*this)[name];
  243. // find the structure definition pertaining to this field
  244. const Structure& s = db.dna[f.type];
  245. db.reader->IncPtr(f.offset);
  246. s.Convert(out,db);
  247. }
  248. catch (const Error& e) {
  249. _defaultInitializer<error_policy>()(out,e.what());
  250. }
  251. // and recover the previous stream position
  252. db.reader->SetCurrentPos(old);
  253. #ifndef ASSIMP_BUILD_BLENDER_NO_STATS
  254. ++db.stats().fields_read;
  255. #endif
  256. }
  257. //--------------------------------------------------------------------------------
  258. // field parsing for raw untyped data (like CustomDataLayer.data)
  259. template <int error_policy>
  260. bool Structure::ReadCustomDataPtr(std::shared_ptr<ElemBase>&out, int cdtype, const char* name, const FileDatabase& db) const {
  261. const StreamReaderAny::pos old = db.reader->GetCurrentPos();
  262. Pointer ptrval;
  263. const Field* f;
  264. try {
  265. f = &(*this)[name];
  266. // sanity check, should never happen if the genblenddna script is right
  267. if (!(f->flags & FieldFlag_Pointer)) {
  268. throw Error((Formatter::format(), "Field `", name, "` of structure `",
  269. this->name, "` ought to be a pointer"));
  270. }
  271. db.reader->IncPtr(f->offset);
  272. Convert(ptrval, db);
  273. // actually it is meaningless on which Structure the Convert is called
  274. // because the `Pointer` argument triggers a special implementation.
  275. }
  276. catch (const Error& e) {
  277. _defaultInitializer<error_policy>()(out, e.what());
  278. out.reset();
  279. }
  280. bool readOk = true;
  281. if (ptrval.val) {
  282. // get block for ptr
  283. const FileBlockHead* block = LocateFileBlockForAddress(ptrval, db);
  284. db.reader->SetCurrentPos(block->start + static_cast<size_t>((ptrval.val - block->address.val)));
  285. // read block->num instances of given type to out
  286. readOk = readCustomData(out, cdtype, block->num, db);
  287. }
  288. // and recover the previous stream position
  289. db.reader->SetCurrentPos(old);
  290. #ifndef ASSIMP_BUILD_BLENDER_NO_STATS
  291. ++db.stats().fields_read;
  292. #endif
  293. return readOk;
  294. }
  295. //--------------------------------------------------------------------------------
  296. template <int error_policy, template <typename> class TOUT, typename T>
  297. bool Structure::ReadFieldPtrVector(vector<TOUT<T>>&out, const char* name, const FileDatabase& db) const {
  298. out.clear();
  299. const StreamReaderAny::pos old = db.reader->GetCurrentPos();
  300. Pointer ptrval;
  301. const Field* f;
  302. try {
  303. f = &(*this)[name];
  304. // sanity check, should never happen if the genblenddna script is right
  305. if (!(f->flags & FieldFlag_Pointer)) {
  306. throw Error((Formatter::format(), "Field `", name, "` of structure `",
  307. this->name, "` ought to be a pointer"));
  308. }
  309. db.reader->IncPtr(f->offset);
  310. Convert(ptrval, db);
  311. // actually it is meaningless on which Structure the Convert is called
  312. // because the `Pointer` argument triggers a special implementation.
  313. }
  314. catch (const Error& e) {
  315. _defaultInitializer<error_policy>()(out, e.what());
  316. out.clear();
  317. return false;
  318. }
  319. if (ptrval.val) {
  320. // find the file block the pointer is pointing to
  321. const FileBlockHead* block = LocateFileBlockForAddress(ptrval, db);
  322. db.reader->SetCurrentPos(block->start + static_cast<size_t>((ptrval.val - block->address.val)));
  323. // FIXME: basically, this could cause problems with 64 bit pointers on 32 bit systems.
  324. // I really ought to improve StreamReader to work with 64 bit indices exclusively.
  325. const Structure& s = db.dna[f->type];
  326. for (size_t i = 0; i < block->num; ++i) {
  327. TOUT<T> p(new T);
  328. s.Convert(*p, db);
  329. out.push_back(p);
  330. }
  331. }
  332. db.reader->SetCurrentPos(old);
  333. #ifndef ASSIMP_BUILD_BLENDER_NO_STATS
  334. ++db.stats().fields_read;
  335. #endif
  336. return true;
  337. }
  338. //--------------------------------------------------------------------------------
  339. template <template <typename> class TOUT, typename T>
  340. bool Structure :: ResolvePointer(TOUT<T>& out, const Pointer & ptrval, const FileDatabase& db,
  341. const Field& f,
  342. bool non_recursive /*= false*/) const
  343. {
  344. out.reset(); // ensure null pointers work
  345. if (!ptrval.val) {
  346. return false;
  347. }
  348. const Structure& s = db.dna[f.type];
  349. // find the file block the pointer is pointing to
  350. const FileBlockHead* block = LocateFileBlockForAddress(ptrval,db);
  351. // also determine the target type from the block header
  352. // and check if it matches the type which we expect.
  353. const Structure& ss = db.dna[block->dna_index];
  354. if (ss != s) {
  355. throw Error((Formatter::format(),"Expected target to be of type `",s.name,
  356. "` but seemingly it is a `",ss.name,"` instead"
  357. ));
  358. }
  359. // try to retrieve the object from the cache
  360. db.cache(out).get(s,out,ptrval);
  361. if (out) {
  362. return true;
  363. }
  364. // seek to this location, but save the previous stream pointer.
  365. const StreamReaderAny::pos pold = db.reader->GetCurrentPos();
  366. db.reader->SetCurrentPos(block->start+ static_cast<size_t>((ptrval.val - block->address.val) ));
  367. // FIXME: basically, this could cause problems with 64 bit pointers on 32 bit systems.
  368. // I really ought to improve StreamReader to work with 64 bit indices exclusively.
  369. // continue conversion after allocating the required storage
  370. size_t num = block->size / ss.size;
  371. T* o = _allocate(out,num);
  372. // cache the object before we convert it to avoid cyclic recursion.
  373. db.cache(out).set(s,out,ptrval);
  374. // if the non_recursive flag is set, we don't do anything but leave
  375. // the cursor at the correct position to resolve the object.
  376. if (!non_recursive) {
  377. for (size_t i = 0; i < num; ++i,++o) {
  378. s.Convert(*o,db);
  379. }
  380. db.reader->SetCurrentPos(pold);
  381. }
  382. #ifndef ASSIMP_BUILD_BLENDER_NO_STATS
  383. if(out) {
  384. ++db.stats().pointers_resolved;
  385. }
  386. #endif
  387. return false;
  388. }
  389. //--------------------------------------------------------------------------------
  390. inline bool Structure :: ResolvePointer( std::shared_ptr< FileOffset >& out, const Pointer & ptrval,
  391. const FileDatabase& db,
  392. const Field&,
  393. bool) const
  394. {
  395. // Currently used exclusively by PackedFile::data to represent
  396. // a simple offset into the mapped BLEND file.
  397. out.reset();
  398. if (!ptrval.val) {
  399. return false;
  400. }
  401. // find the file block the pointer is pointing to
  402. const FileBlockHead* block = LocateFileBlockForAddress(ptrval,db);
  403. out = std::shared_ptr< FileOffset > (new FileOffset());
  404. out->val = block->start+ static_cast<size_t>((ptrval.val - block->address.val) );
  405. return false;
  406. }
  407. //--------------------------------------------------------------------------------
  408. template <template <typename> class TOUT, typename T>
  409. bool Structure :: ResolvePointer(vector< TOUT<T> >& out, const Pointer & ptrval,
  410. const FileDatabase& db,
  411. const Field& f,
  412. bool) const
  413. {
  414. // This is a function overload, not a template specialization. According to
  415. // the partial ordering rules, it should be selected by the compiler
  416. // for array-of-pointer inputs, i.e. Object::mats.
  417. out.reset();
  418. if (!ptrval.val) {
  419. return false;
  420. }
  421. // find the file block the pointer is pointing to
  422. const FileBlockHead* block = LocateFileBlockForAddress(ptrval,db);
  423. const size_t num = block->size / (db.i64bit?8:4);
  424. // keep the old stream position
  425. const StreamReaderAny::pos pold = db.reader->GetCurrentPos();
  426. db.reader->SetCurrentPos(block->start+ static_cast<size_t>((ptrval.val - block->address.val) ));
  427. bool res = false;
  428. // allocate raw storage for the array
  429. out.resize(num);
  430. for (size_t i = 0; i< num; ++i) {
  431. Pointer val;
  432. Convert(val,db);
  433. // and resolve the pointees
  434. res = ResolvePointer(out[i],val,db,f) && res;
  435. }
  436. db.reader->SetCurrentPos(pold);
  437. return res;
  438. }
  439. //--------------------------------------------------------------------------------
  440. template <> bool Structure :: ResolvePointer<std::shared_ptr,ElemBase>(std::shared_ptr<ElemBase>& out,
  441. const Pointer & ptrval,
  442. const FileDatabase& db,
  443. const Field&,
  444. bool
  445. ) const
  446. {
  447. // Special case when the data type needs to be determined at runtime.
  448. // Less secure than in the `strongly-typed` case.
  449. out.reset();
  450. if (!ptrval.val) {
  451. return false;
  452. }
  453. // find the file block the pointer is pointing to
  454. const FileBlockHead* block = LocateFileBlockForAddress(ptrval,db);
  455. // determine the target type from the block header
  456. const Structure& s = db.dna[block->dna_index];
  457. // try to retrieve the object from the cache
  458. db.cache(out).get(s,out,ptrval);
  459. if (out) {
  460. return true;
  461. }
  462. // seek to this location, but save the previous stream pointer.
  463. const StreamReaderAny::pos pold = db.reader->GetCurrentPos();
  464. db.reader->SetCurrentPos(block->start+ static_cast<size_t>((ptrval.val - block->address.val) ));
  465. // FIXME: basically, this could cause problems with 64 bit pointers on 32 bit systems.
  466. // I really ought to improve StreamReader to work with 64 bit indices exclusively.
  467. // continue conversion after allocating the required storage
  468. DNA::FactoryPair builders = db.dna.GetBlobToStructureConverter(s,db);
  469. if (!builders.first) {
  470. // this might happen if DNA::RegisterConverters hasn't been called so far
  471. // or if the target type is not contained in `our` DNA.
  472. out.reset();
  473. ASSIMP_LOG_WARN_F( "Failed to find a converter for the `",s.name,"` structure" );
  474. return false;
  475. }
  476. // allocate the object hull
  477. out = (s.*builders.first)();
  478. // cache the object immediately to prevent infinite recursion in a
  479. // circular list with a single element (i.e. a self-referencing element).
  480. db.cache(out).set(s,out,ptrval);
  481. // and do the actual conversion
  482. (s.*builders.second)(out,db);
  483. db.reader->SetCurrentPos(pold);
  484. // store a pointer to the name string of the actual type
  485. // in the object itself. This allows the conversion code
  486. // to perform additional type checking.
  487. out->dna_type = s.name.c_str();
  488. #ifndef ASSIMP_BUILD_BLENDER_NO_STATS
  489. ++db.stats().pointers_resolved;
  490. #endif
  491. return false;
  492. }
  493. //--------------------------------------------------------------------------------
  494. const FileBlockHead* Structure :: LocateFileBlockForAddress(const Pointer & ptrval, const FileDatabase& db) const
  495. {
  496. // the file blocks appear in list sorted by
  497. // with ascending base addresses so we can run a
  498. // binary search to locate the pointer quickly.
  499. // NOTE: Blender seems to distinguish between side-by-side
  500. // data (stored in the same data block) and far pointers,
  501. // which are only used for structures starting with an ID.
  502. // We don't need to make this distinction, our algorithm
  503. // works regardless where the data is stored.
  504. vector<FileBlockHead>::const_iterator it = std::lower_bound(db.entries.begin(),db.entries.end(),ptrval);
  505. if (it == db.entries.end()) {
  506. // this is crucial, pointers may not be invalid.
  507. // this is either a corrupted file or an attempted attack.
  508. throw DeadlyImportError((Formatter::format(),"Failure resolving pointer 0x",
  509. std::hex,ptrval.val,", no file block falls into this address range"
  510. ));
  511. }
  512. if (ptrval.val >= (*it).address.val + (*it).size) {
  513. throw DeadlyImportError((Formatter::format(),"Failure resolving pointer 0x",
  514. std::hex,ptrval.val,", nearest file block starting at 0x",
  515. (*it).address.val," ends at 0x",
  516. (*it).address.val + (*it).size
  517. ));
  518. }
  519. return &*it;
  520. }
  521. // ------------------------------------------------------------------------------------------------
  522. // NOTE: The MSVC debugger keeps showing up this annoying `a cast to a smaller data type has
  523. // caused a loss of data`-warning. Avoid this warning by a masking with an appropriate bitmask.
  524. template <typename T> struct signless;
  525. template <> struct signless<char> {typedef unsigned char type;};
  526. template <> struct signless<short> {typedef unsigned short type;};
  527. template <> struct signless<int> {typedef unsigned int type;};
  528. template <> struct signless<unsigned char> { typedef unsigned char type; };
  529. template <typename T>
  530. struct static_cast_silent {
  531. template <typename V>
  532. T operator()(V in) {
  533. return static_cast<T>(in & static_cast<typename signless<T>::type>(-1));
  534. }
  535. };
  536. template <> struct static_cast_silent<float> {
  537. template <typename V> float operator()(V in) {
  538. return static_cast<float> (in);
  539. }
  540. };
  541. template <> struct static_cast_silent<double> {
  542. template <typename V> double operator()(V in) {
  543. return static_cast<double>(in);
  544. }
  545. };
  546. // ------------------------------------------------------------------------------------------------
  547. template <typename T> inline void ConvertDispatcher(T& out, const Structure& in,const FileDatabase& db)
  548. {
  549. if (in.name == "int") {
  550. out = static_cast_silent<T>()(db.reader->GetU4());
  551. }
  552. else if (in.name == "short") {
  553. out = static_cast_silent<T>()(db.reader->GetU2());
  554. }
  555. else if (in.name == "char") {
  556. out = static_cast_silent<T>()(db.reader->GetU1());
  557. }
  558. else if (in.name == "float") {
  559. out = static_cast<T>(db.reader->GetF4());
  560. }
  561. else if (in.name == "double") {
  562. out = static_cast<T>(db.reader->GetF8());
  563. }
  564. else {
  565. throw DeadlyImportError("Unknown source for conversion to primitive data type: "+in.name);
  566. }
  567. }
  568. // ------------------------------------------------------------------------------------------------
  569. template <> inline void Structure :: Convert<int> (int& dest,const FileDatabase& db) const
  570. {
  571. ConvertDispatcher(dest,*this,db);
  572. }
  573. // ------------------------------------------------------------------------------------------------
  574. template<> inline void Structure :: Convert<short> (short& dest,const FileDatabase& db) const
  575. {
  576. // automatic rescaling from short to float and vice versa (seems to be used by normals)
  577. if (name == "float") {
  578. float f = db.reader->GetF4();
  579. if ( f > 1.0f )
  580. f = 1.0f;
  581. dest = static_cast<short>( f * 32767.f);
  582. //db.reader->IncPtr(-4);
  583. return;
  584. }
  585. else if (name == "double") {
  586. dest = static_cast<short>(db.reader->GetF8() * 32767.);
  587. //db.reader->IncPtr(-8);
  588. return;
  589. }
  590. ConvertDispatcher(dest,*this,db);
  591. }
  592. // ------------------------------------------------------------------------------------------------
  593. template <> inline void Structure :: Convert<char> (char& dest,const FileDatabase& db) const
  594. {
  595. // automatic rescaling from char to float and vice versa (seems useful for RGB colors)
  596. if (name == "float") {
  597. dest = static_cast<char>(db.reader->GetF4() * 255.f);
  598. return;
  599. }
  600. else if (name == "double") {
  601. dest = static_cast<char>(db.reader->GetF8() * 255.f);
  602. return;
  603. }
  604. ConvertDispatcher(dest,*this,db);
  605. }
  606. // ------------------------------------------------------------------------------------------------
  607. template <> inline void Structure::Convert<unsigned char>(unsigned char& dest, const FileDatabase& db) const
  608. {
  609. // automatic rescaling from char to float and vice versa (seems useful for RGB colors)
  610. if (name == "float") {
  611. dest = static_cast<unsigned char>(db.reader->GetF4() * 255.f);
  612. return;
  613. }
  614. else if (name == "double") {
  615. dest = static_cast<unsigned char>(db.reader->GetF8() * 255.f);
  616. return;
  617. }
  618. ConvertDispatcher(dest, *this, db);
  619. }
  620. // ------------------------------------------------------------------------------------------------
  621. template <> inline void Structure :: Convert<float> (float& dest,const FileDatabase& db) const
  622. {
  623. // automatic rescaling from char to float and vice versa (seems useful for RGB colors)
  624. if (name == "char") {
  625. dest = db.reader->GetI1() / 255.f;
  626. return;
  627. }
  628. // automatic rescaling from short to float and vice versa (used by normals)
  629. else if (name == "short") {
  630. dest = db.reader->GetI2() / 32767.f;
  631. return;
  632. }
  633. ConvertDispatcher(dest,*this,db);
  634. }
  635. // ------------------------------------------------------------------------------------------------
  636. template <> inline void Structure :: Convert<double> (double& dest,const FileDatabase& db) const
  637. {
  638. if (name == "char") {
  639. dest = db.reader->GetI1() / 255.;
  640. return;
  641. }
  642. else if (name == "short") {
  643. dest = db.reader->GetI2() / 32767.;
  644. return;
  645. }
  646. ConvertDispatcher(dest,*this,db);
  647. }
  648. // ------------------------------------------------------------------------------------------------
  649. template <> inline void Structure :: Convert<Pointer> (Pointer& dest,const FileDatabase& db) const
  650. {
  651. if (db.i64bit) {
  652. dest.val = db.reader->GetU8();
  653. //db.reader->IncPtr(-8);
  654. return;
  655. }
  656. dest.val = db.reader->GetU4();
  657. //db.reader->IncPtr(-4);
  658. }
  659. //--------------------------------------------------------------------------------
  660. const Structure& DNA :: operator [] (const std::string& ss) const
  661. {
  662. std::map<std::string, size_t>::const_iterator it = indices.find(ss);
  663. if (it == indices.end()) {
  664. throw Error((Formatter::format(),
  665. "BlendDNA: Did not find a structure named `",ss,"`"
  666. ));
  667. }
  668. return structures[(*it).second];
  669. }
  670. //--------------------------------------------------------------------------------
  671. const Structure* DNA :: Get (const std::string& ss) const
  672. {
  673. std::map<std::string, size_t>::const_iterator it = indices.find(ss);
  674. return it == indices.end() ? NULL : &structures[(*it).second];
  675. }
  676. //--------------------------------------------------------------------------------
  677. const Structure& DNA :: operator [] (const size_t i) const
  678. {
  679. if (i >= structures.size()) {
  680. throw Error((Formatter::format(),
  681. "BlendDNA: There is no structure with index `",i,"`"
  682. ));
  683. }
  684. return structures[i];
  685. }
  686. //--------------------------------------------------------------------------------
  687. template <template <typename> class TOUT> template <typename T> void ObjectCache<TOUT> :: get (
  688. const Structure& s,
  689. TOUT<T>& out,
  690. const Pointer& ptr
  691. ) const {
  692. if(s.cache_idx == static_cast<size_t>(-1)) {
  693. s.cache_idx = db.next_cache_idx++;
  694. caches.resize(db.next_cache_idx);
  695. return;
  696. }
  697. typename StructureCache::const_iterator it = caches[s.cache_idx].find(ptr);
  698. if (it != caches[s.cache_idx].end()) {
  699. out = std::static_pointer_cast<T>( (*it).second );
  700. #ifndef ASSIMP_BUILD_BLENDER_NO_STATS
  701. ++db.stats().cache_hits;
  702. #endif
  703. }
  704. // otherwise, out remains untouched
  705. }
  706. //--------------------------------------------------------------------------------
  707. template <template <typename> class TOUT> template <typename T> void ObjectCache<TOUT> :: set (
  708. const Structure& s,
  709. const TOUT<T>& out,
  710. const Pointer& ptr
  711. ) {
  712. if(s.cache_idx == static_cast<size_t>(-1)) {
  713. s.cache_idx = db.next_cache_idx++;
  714. caches.resize(db.next_cache_idx);
  715. }
  716. caches[s.cache_idx][ptr] = std::static_pointer_cast<ElemBase>( out );
  717. #ifndef ASSIMP_BUILD_BLENDER_NO_STATS
  718. ++db.stats().cached_objects;
  719. #endif
  720. }
  721. }}
  722. #endif