BlenderDNA.h 29 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816
  1. /*
  2. Open Asset Import Library (assimp)
  3. ----------------------------------------------------------------------
  4. Copyright (c) 2006-2025, 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.h
  34. * @brief Blender `DNA` (file format specification embedded in
  35. * blend file itself) loader.
  36. */
  37. #ifndef INCLUDED_AI_BLEND_DNA_H
  38. #define INCLUDED_AI_BLEND_DNA_H
  39. #include <assimp/BaseImporter.h>
  40. #include <assimp/StreamReader.h>
  41. #include <stdint.h>
  42. #include <assimp/DefaultLogger.hpp>
  43. #include <map>
  44. #include <memory>
  45. // enable verbose log output. really verbose, so be careful.
  46. #ifdef ASSIMP_BUILD_DEBUG
  47. #define ASSIMP_BUILD_BLENDER_DEBUG
  48. #endif
  49. // set this to non-zero to dump BlenderDNA stuff to dna.txt.
  50. // you could set it on the assimp build command line too without touching it here.
  51. // !!! please make sure this is set to 0 in the repo !!!
  52. #ifndef ASSIMP_BUILD_BLENDER_DEBUG_DNA
  53. #define ASSIMP_BUILD_BLENDER_DEBUG_DNA 0
  54. #endif
  55. // #define ASSIMP_BUILD_BLENDER_NO_STATS
  56. namespace Assimp {
  57. template <bool, bool>
  58. class StreamReader;
  59. typedef StreamReader<true, true> StreamReaderAny;
  60. namespace Blender {
  61. class FileDatabase;
  62. struct FileBlockHead;
  63. template <template <typename> class TOUT>
  64. class ObjectCache;
  65. // -------------------------------------------------------------------------------
  66. /** Exception class used by the blender loader to selectively catch exceptions
  67. * thrown in its own code (DeadlyImportErrors thrown in general utility
  68. * functions are untouched then). If such an exception is not caught by
  69. * the loader itself, it will still be caught by Assimp due to its
  70. * ancestry. */
  71. // -------------------------------------------------------------------------------
  72. struct Error : DeadlyImportError {
  73. template <typename... T>
  74. explicit Error(T &&...args) :
  75. DeadlyImportError(args...) {
  76. }
  77. };
  78. // -------------------------------------------------------------------------------
  79. /** The only purpose of this structure is to feed a virtual dtor into its
  80. * descendents. It serves as base class for all data structure fields. */
  81. // -------------------------------------------------------------------------------
  82. struct ElemBase {
  83. ElemBase() :
  84. dna_type(nullptr) {
  85. // empty
  86. }
  87. virtual ~ElemBase() = default;
  88. /** Type name of the element. The type
  89. * string points is the `c_str` of the `name` attribute of the
  90. * corresponding `Structure`, that is, it is only valid as long
  91. * as the DNA is not modified. The dna_type is only set if the
  92. * data type is not static, i.e. a std::shared_ptr<ElemBase>
  93. * in the scene description would have its type resolved
  94. * at runtime, so this member is always set. */
  95. const char *dna_type;
  96. };
  97. // -------------------------------------------------------------------------------
  98. /** Represents a generic pointer to a memory location, which can be either 32
  99. * or 64 bits. These pointers are loaded from the BLEND file and finally
  100. * fixed to point to the real, converted representation of the objects
  101. * they used to point to.*/
  102. // -------------------------------------------------------------------------------
  103. struct Pointer {
  104. Pointer() :
  105. val() {
  106. // empty
  107. }
  108. uint64_t val;
  109. };
  110. // -------------------------------------------------------------------------------
  111. /** Represents a generic offset within a BLEND file */
  112. // -------------------------------------------------------------------------------
  113. struct FileOffset {
  114. FileOffset() :
  115. val() {
  116. // empty
  117. }
  118. uint64_t val;
  119. };
  120. // -------------------------------------------------------------------------------
  121. /** Dummy derivate of std::vector to be able to use it in templates simultaenously
  122. * with std::shared_ptr, which takes only one template argument
  123. * while std::vector takes three. Also we need to provide some special member
  124. * functions of shared_ptr */
  125. // -------------------------------------------------------------------------------
  126. template <typename T>
  127. class vector : public std::vector<T> {
  128. public:
  129. using std::vector<T>::resize;
  130. using std::vector<T>::empty;
  131. void reset() {
  132. resize(0);
  133. }
  134. operator bool() const {
  135. return !empty();
  136. }
  137. };
  138. // -------------------------------------------------------------------------------
  139. /** Mixed flags for use in #Field */
  140. // -------------------------------------------------------------------------------
  141. enum FieldFlags {
  142. FieldFlag_Pointer = 0x1,
  143. FieldFlag_Array = 0x2
  144. };
  145. // -------------------------------------------------------------------------------
  146. /** Represents a single member of a data structure in a BLEND file */
  147. // -------------------------------------------------------------------------------
  148. struct Field {
  149. std::string name;
  150. std::string type;
  151. size_t size;
  152. size_t offset;
  153. /** Size of each array dimension. For flat arrays,
  154. * the second dimension is set to 1. */
  155. size_t array_sizes[2];
  156. /** Any of the #FieldFlags enumerated values */
  157. unsigned int flags;
  158. };
  159. // -------------------------------------------------------------------------------
  160. /** Range of possible behaviors for fields absence in the input file. Some are
  161. * mission critical so we need them, while others can silently be default
  162. * initialized and no animations are harmed. */
  163. // -------------------------------------------------------------------------------
  164. enum ErrorPolicy {
  165. /** Substitute default value and ignore */
  166. ErrorPolicy_Igno,
  167. /** Substitute default value and write to log */
  168. ErrorPolicy_Warn,
  169. /** Substitute a massive error message and crash the whole matrix. Its time for another zion */
  170. ErrorPolicy_Fail
  171. };
  172. #ifdef ASSIMP_BUILD_BLENDER_DEBUG
  173. #define ErrorPolicy_Igno ErrorPolicy_Warn
  174. #endif
  175. // -------------------------------------------------------------------------------
  176. /** Represents a data structure in a BLEND file. A Structure defines n fields
  177. * and their locations and encodings the input stream. Usually, every
  178. * Structure instance pertains to one equally-named data structure in the
  179. * BlenderScene.h header. This class defines various utilities to map a
  180. * binary `blob` read from the file to such a structure instance with
  181. * meaningful contents. */
  182. // -------------------------------------------------------------------------------
  183. class Structure {
  184. template <template <typename> class>
  185. friend class ObjectCache;
  186. public:
  187. Structure() :
  188. cache_idx(static_cast<size_t>(-1)) {
  189. // empty
  190. }
  191. // publicly accessible members
  192. std::string name;
  193. vector<Field> fields;
  194. std::map<std::string, size_t> indices;
  195. size_t size;
  196. // --------------------------------------------------------
  197. /** Access a field of the structure by its canonical name. The pointer version
  198. * returns nullptr on failure while the reference version raises an import error. */
  199. inline const Field &operator[](const std::string &ss) const;
  200. inline const Field *Get(const std::string &ss) const;
  201. // --------------------------------------------------------
  202. /** Access a field of the structure by its index */
  203. inline const Field &operator[](const size_t i) const;
  204. // --------------------------------------------------------
  205. inline bool operator==(const Structure &other) const {
  206. return name == other.name; // name is meant to be an unique identifier
  207. }
  208. // --------------------------------------------------------
  209. inline bool operator!=(const Structure &other) const {
  210. return name != other.name;
  211. }
  212. // --------------------------------------------------------
  213. /** Try to read an instance of the structure from the stream
  214. * and attempt to convert to `T`. This is done by
  215. * an appropriate specialization. If none is available,
  216. * a compiler complain is the result.
  217. * @param dest Destination value to be written
  218. * @param db File database, including input stream. */
  219. template <typename T>
  220. void Convert(T &dest, const FileDatabase &db) const;
  221. // --------------------------------------------------------
  222. // generic converter
  223. template <typename T>
  224. void Convert(std::shared_ptr<ElemBase> in, const FileDatabase &db) const;
  225. // --------------------------------------------------------
  226. // generic allocator
  227. template <typename T>
  228. std::shared_ptr<ElemBase> Allocate() const;
  229. // --------------------------------------------------------
  230. // field parsing for 1d arrays
  231. template <int error_policy, typename T, size_t M>
  232. void ReadFieldArray(T (&out)[M], const char *name,
  233. const FileDatabase &db) const;
  234. // --------------------------------------------------------
  235. // field parsing for 2d arrays
  236. template <int error_policy, typename T, size_t M, size_t N>
  237. void ReadFieldArray2(T (&out)[M][N], const char *name,
  238. const FileDatabase &db) const;
  239. // --------------------------------------------------------
  240. // field parsing for pointer or dynamic array types
  241. // (std::shared_ptr)
  242. // The return value indicates whether the data was already cached.
  243. template <int error_policy, template <typename> class TOUT, typename T>
  244. bool ReadFieldPtr(TOUT<T> &out, const char *name,
  245. const FileDatabase &db,
  246. bool non_recursive = false) const;
  247. // --------------------------------------------------------
  248. // field parsing for static arrays of pointer or dynamic
  249. // array types (std::shared_ptr[])
  250. // The return value indicates whether the data was already cached.
  251. template <int error_policy, template <typename> class TOUT, typename T, size_t N>
  252. bool ReadFieldPtr(TOUT<T> (&out)[N], const char *name,
  253. const FileDatabase &db) const;
  254. // --------------------------------------------------------
  255. // field parsing for `normal` values
  256. // The return value indicates whether the data was already cached.
  257. template <int error_policy, typename T>
  258. void ReadField(T &out, const char *name,
  259. const FileDatabase &db) const;
  260. // --------------------------------------------------------
  261. /**
  262. * @brief field parsing for dynamic vectors
  263. * @param[in] out vector of struct to be filled
  264. * @param[in] name of field
  265. * @param[in] db to access the file, dna, ...
  266. * @return true when read was successful
  267. */
  268. template <int error_policy, template <typename> class TOUT, typename T>
  269. bool ReadFieldPtrVector(vector<TOUT<T>> &out, const char *name, const FileDatabase &db) const;
  270. /**
  271. * @brief parses raw customdata
  272. * @param[in] out shared_ptr to be filled
  273. * @param[in] cdtype customdata type to read
  274. * @param[in] name of field ptr
  275. * @param[in] db to access the file, dna, ...
  276. * @return true when read was successful
  277. */
  278. template <int error_policy>
  279. bool ReadCustomDataPtr(std::shared_ptr<ElemBase> &out, int cdtype, const char *name, const FileDatabase &db) const;
  280. private:
  281. // --------------------------------------------------------
  282. template <template <typename> class TOUT, typename T>
  283. bool ResolvePointer(TOUT<T> &out, const Pointer &ptrval,
  284. const FileDatabase &db, const Field &f,
  285. bool non_recursive = false) const;
  286. // --------------------------------------------------------
  287. template <template <typename> class TOUT, typename T>
  288. bool ResolvePointer(vector<TOUT<T>> &out, const Pointer &ptrval,
  289. const FileDatabase &db, const Field &f, bool) const;
  290. // --------------------------------------------------------
  291. bool ResolvePointer(std::shared_ptr<FileOffset> &out, const Pointer &ptrval,
  292. const FileDatabase &db, const Field &f, bool) const;
  293. // --------------------------------------------------------
  294. inline const FileBlockHead *LocateFileBlockForAddress(
  295. const Pointer &ptrval,
  296. const FileDatabase &db) const;
  297. private:
  298. // ------------------------------------------------------------------------------
  299. template <typename T>
  300. T *_allocate(std::shared_ptr<T> &out, size_t &s) const {
  301. out = std::shared_ptr<T>(new T());
  302. s = 1;
  303. return out.get();
  304. }
  305. template <typename T>
  306. T *_allocate(vector<T> &out, size_t &s) const {
  307. out.resize(s);
  308. return s ? &out.front() : nullptr;
  309. }
  310. // --------------------------------------------------------
  311. template <int error_policy>
  312. struct _defaultInitializer {
  313. template <typename T, unsigned int N>
  314. void operator()(T (&out)[N], const char * = nullptr) {
  315. for (unsigned int i = 0; i < N; ++i) {
  316. out[i] = T();
  317. }
  318. }
  319. template <typename T, unsigned int N, unsigned int M>
  320. void operator()(T (&out)[N][M], const char * = nullptr) {
  321. for (unsigned int i = 0; i < N; ++i) {
  322. for (unsigned int j = 0; j < M; ++j) {
  323. out[i][j] = T();
  324. }
  325. }
  326. }
  327. template <typename T>
  328. void operator()(T &out, const char * = nullptr) {
  329. out = T();
  330. }
  331. };
  332. private:
  333. mutable size_t cache_idx;
  334. };
  335. // --------------------------------------------------------
  336. template <>
  337. struct Structure::_defaultInitializer<ErrorPolicy_Warn> {
  338. template <typename T>
  339. void operator()(T &out, const char *reason = "<add reason>") {
  340. ASSIMP_LOG_WARN(reason);
  341. // ... and let the show go on
  342. _defaultInitializer<0 /*ErrorPolicy_Igno*/>()(out);
  343. }
  344. };
  345. template <>
  346. struct Structure::_defaultInitializer<ErrorPolicy_Fail> {
  347. template <typename T>
  348. void operator()(T & /*out*/, const char *message = "") {
  349. // obviously, it is crucial that _DefaultInitializer is used
  350. // only from within a catch clause.
  351. throw DeadlyImportError("Constructing BlenderDNA Structure encountered an error: ", message);
  352. }
  353. };
  354. // -------------------------------------------------------------------------------------------------------
  355. template <>
  356. inline bool Structure ::ResolvePointer<std::shared_ptr, ElemBase>(std::shared_ptr<ElemBase> &out,
  357. const Pointer &ptrval,
  358. const FileDatabase &db,
  359. const Field &f,
  360. bool) const;
  361. template <> bool Structure :: ResolvePointer<std::shared_ptr,ElemBase>(
  362. std::shared_ptr<ElemBase>& out, const Pointer & ptrval,
  363. const FileDatabase& db, const Field&, bool) const;
  364. template <> inline void Structure :: Convert<int> (int& dest,const FileDatabase& db) const;
  365. template<> inline void Structure :: Convert<short> (short& dest,const FileDatabase& db) const;
  366. template <> inline void Structure :: Convert<char> (char& dest,const FileDatabase& db) const;
  367. template <> inline void Structure::Convert<unsigned char>(unsigned char& dest, const FileDatabase& db) const;
  368. template <> inline void Structure :: Convert<float> (float& dest,const FileDatabase& db) const;
  369. template <> inline void Structure :: Convert<double> (double& dest,const FileDatabase& db) const;
  370. template <> inline void Structure :: Convert<Pointer> (Pointer& dest,const FileDatabase& db) const;
  371. // -------------------------------------------------------------------------------
  372. /** Represents the full data structure information for a single BLEND file.
  373. * This data is extracted from the DNA1 chunk in the file.
  374. * #DNAParser does the reading and represents currently the only place where
  375. * DNA is altered.*/
  376. // -------------------------------------------------------------------------------
  377. class DNA {
  378. public:
  379. typedef void (Structure::*ConvertProcPtr)(
  380. std::shared_ptr<ElemBase> in,
  381. const FileDatabase &) const;
  382. typedef std::shared_ptr<ElemBase> (
  383. Structure::*AllocProcPtr)() const;
  384. typedef std::pair<AllocProcPtr, ConvertProcPtr> FactoryPair;
  385. public:
  386. std::map<std::string, FactoryPair> converters;
  387. vector<Structure> structures;
  388. std::map<std::string, size_t> indices;
  389. public:
  390. // --------------------------------------------------------
  391. /** Access a structure by its canonical name, the pointer version returns nullptr on failure
  392. * while the reference version raises an error. */
  393. inline const Structure &operator[](const std::string &ss) const;
  394. inline const Structure *Get(const std::string &ss) const;
  395. // --------------------------------------------------------
  396. /** Access a structure by its index */
  397. inline const Structure &operator[](const size_t i) const;
  398. public:
  399. // --------------------------------------------------------
  400. /** Add structure definitions for all the primitive types,
  401. * i.e. integer, short, char, float */
  402. void AddPrimitiveStructures();
  403. // --------------------------------------------------------
  404. /** Fill the @c converters member with converters for all
  405. * known data types. The implementation of this method is
  406. * in BlenderScene.cpp and is machine-generated.
  407. * Converters are used to quickly handle objects whose
  408. * exact data type is a runtime-property and not yet
  409. * known at compile time (consider Object::data).*/
  410. void RegisterConverters();
  411. // --------------------------------------------------------
  412. /** Take an input blob from the stream, interpret it according to
  413. * a its structure name and convert it to the intermediate
  414. * representation.
  415. * @param structure Destination structure definition
  416. * @param db File database.
  417. * @return A null pointer if no appropriate converter is available.*/
  418. std::shared_ptr<ElemBase> ConvertBlobToStructure(
  419. const Structure &structure,
  420. const FileDatabase &db) const;
  421. // --------------------------------------------------------
  422. /** Find a suitable conversion function for a given Structure.
  423. * Such a converter function takes a blob from the input
  424. * stream, reads as much as it needs, and builds up a
  425. * complete object in intermediate representation.
  426. * @param structure Destination structure definition
  427. * @param db File database.
  428. * @return A null pointer in .first if no appropriate converter is available.*/
  429. FactoryPair GetBlobToStructureConverter(
  430. const Structure &structure,
  431. const FileDatabase &db) const;
  432. #if ASSIMP_BUILD_BLENDER_DEBUG_DNA
  433. // --------------------------------------------------------
  434. /** Dump the DNA to a text file. This is for debugging purposes.
  435. * The output file is `dna.txt` in the current working folder*/
  436. void DumpToFile();
  437. #endif
  438. // --------------------------------------------------------
  439. /** Extract array dimensions from a C array declaration, such
  440. * as `...[4][6]`. Returned string would be `...[][]`.
  441. * @param out
  442. * @param array_sizes Receive maximally two array dimensions,
  443. * the second element is set to 1 if the array is flat.
  444. * Both are set to 1 if the input is not an array.
  445. * @throw DeadlyImportError if more than 2 dimensions are
  446. * encountered. */
  447. static void ExtractArraySize(
  448. const std::string &out,
  449. size_t array_sizes[2]);
  450. };
  451. // special converters for primitive types
  452. template <>
  453. inline void Structure ::Convert<int>(int &dest, const FileDatabase &db) const;
  454. template <>
  455. inline void Structure ::Convert<short>(short &dest, const FileDatabase &db) const;
  456. template <>
  457. inline void Structure ::Convert<char>(char &dest, const FileDatabase &db) const;
  458. template <>
  459. inline void Structure ::Convert<float>(float &dest, const FileDatabase &db) const;
  460. template <>
  461. inline void Structure ::Convert<double>(double &dest, const FileDatabase &db) const;
  462. template <>
  463. inline void Structure ::Convert<Pointer>(Pointer &dest, const FileDatabase &db) const;
  464. // -------------------------------------------------------------------------------
  465. /** Describes a master file block header. Each master file sections holds n
  466. * elements of a certain SDNA structure (or otherwise unspecified data). */
  467. // -------------------------------------------------------------------------------
  468. struct FileBlockHead {
  469. // points right after the header of the file block
  470. StreamReaderAny::pos start;
  471. std::string id;
  472. size_t size;
  473. // original memory address of the data
  474. Pointer address;
  475. // index into DNA
  476. unsigned int dna_index;
  477. // number of structure instances to follow
  478. size_t num;
  479. // file blocks are sorted by address to quickly locate specific memory addresses
  480. bool operator<(const FileBlockHead &o) const {
  481. return address.val < o.address.val;
  482. }
  483. // for std::upper_bound
  484. operator const Pointer &() const {
  485. return address;
  486. }
  487. };
  488. // for std::upper_bound
  489. inline bool operator<(const Pointer &a, const Pointer &b) {
  490. return a.val < b.val;
  491. }
  492. // -------------------------------------------------------------------------------
  493. /** Utility to read all master file blocks in turn. */
  494. // -------------------------------------------------------------------------------
  495. class SectionParser {
  496. public:
  497. // --------------------------------------------------------
  498. /** @param stream Inout stream, must point to the
  499. * first section in the file. Call Next() once
  500. * to have it read.
  501. * @param ptr64 Pointer size in file is 64 bits? */
  502. SectionParser(StreamReaderAny &stream, bool ptr64) :
  503. stream(stream), ptr64(ptr64) {
  504. current.size = current.start = 0;
  505. }
  506. public:
  507. // --------------------------------------------------------
  508. const FileBlockHead &GetCurrent() const {
  509. return current;
  510. }
  511. public:
  512. // --------------------------------------------------------
  513. /** Advance to the next section.
  514. * @throw DeadlyImportError if the last chunk was passed. */
  515. void Next();
  516. public:
  517. FileBlockHead current;
  518. StreamReaderAny &stream;
  519. bool ptr64;
  520. };
  521. #ifndef ASSIMP_BUILD_BLENDER_NO_STATS
  522. // -------------------------------------------------------------------------------
  523. /** Import statistics, i.e. number of file blocks read*/
  524. // -------------------------------------------------------------------------------
  525. class Statistics {
  526. public:
  527. Statistics() :
  528. fields_read(), pointers_resolved(), cache_hits()
  529. // , blocks_read ()
  530. ,
  531. cached_objects() {}
  532. public:
  533. /** total number of fields we read */
  534. unsigned int fields_read;
  535. /** total number of resolved pointers */
  536. unsigned int pointers_resolved;
  537. /** number of pointers resolved from the cache */
  538. unsigned int cache_hits;
  539. /** number of blocks (from FileDatabase::entries)
  540. we did actually read from. */
  541. // unsigned int blocks_read;
  542. /** objects in FileData::cache */
  543. unsigned int cached_objects;
  544. };
  545. #endif
  546. // -------------------------------------------------------------------------------
  547. /** The object cache - all objects addressed by pointers are added here. This
  548. * avoids circular references and avoids object duplication. */
  549. // -------------------------------------------------------------------------------
  550. template <template <typename> class TOUT>
  551. class ObjectCache {
  552. public:
  553. typedef std::map<Pointer, TOUT<ElemBase>> StructureCache;
  554. public:
  555. ObjectCache(const FileDatabase &db) :
  556. db(db) {
  557. // currently there are only ~400 structure records per blend file.
  558. // we read only a small part of them and don't cache objects
  559. // which we don't need, so this should suffice.
  560. caches.reserve(64);
  561. }
  562. public:
  563. // --------------------------------------------------------
  564. /** Check whether a specific item is in the cache.
  565. * @param s Data type of the item
  566. * @param out Output pointer. Unchanged if the
  567. * cache doesn't know the item yet.
  568. * @param ptr Item address to look for. */
  569. template <typename T>
  570. void get(
  571. const Structure &s,
  572. TOUT<T> &out,
  573. const Pointer &ptr) const;
  574. // --------------------------------------------------------
  575. /** Add an item to the cache after the item has
  576. * been fully read. Do not insert anything that
  577. * may be faulty or might cause the loading
  578. * to abort.
  579. * @param s Data type of the item
  580. * @param out Item to insert into the cache
  581. * @param ptr address (cache key) of the item. */
  582. template <typename T>
  583. void set(const Structure &s,
  584. const TOUT<T> &out,
  585. const Pointer &ptr);
  586. private:
  587. mutable vector<StructureCache> caches;
  588. const FileDatabase &db;
  589. };
  590. // -------------------------------------------------------------------------------
  591. // -------------------------------------------------------------------------------
  592. template <>
  593. class ObjectCache<Blender::vector> {
  594. public:
  595. ObjectCache(const FileDatabase &) {}
  596. template <typename T>
  597. void get(const Structure &, vector<T> &, const Pointer &) {}
  598. template <typename T>
  599. void set(const Structure &, const vector<T> &, const Pointer &) {}
  600. };
  601. #ifdef _MSC_VER
  602. #pragma warning(disable : 4355)
  603. #endif
  604. // -------------------------------------------------------------------------------
  605. /** Memory representation of a full BLEND file and all its dependencies. The
  606. * output aiScene is constructed from an instance of this data structure. */
  607. // -------------------------------------------------------------------------------
  608. class FileDatabase {
  609. template <template <typename> class TOUT>
  610. friend class ObjectCache;
  611. public:
  612. FileDatabase() :
  613. _cacheArrays(*this), _cache(*this), next_cache_idx() {}
  614. public:
  615. // publicly accessible fields
  616. bool i64bit;
  617. bool little;
  618. DNA dna;
  619. std::shared_ptr<StreamReaderAny> reader;
  620. vector<FileBlockHead> entries;
  621. public:
  622. Statistics &stats() const {
  623. return _stats;
  624. }
  625. // For all our templates to work on both shared_ptr's and vector's
  626. // using the same code, a dummy cache for arrays is provided. Actually,
  627. // arrays of objects are never cached because we can't easily
  628. // ensure their proper destruction.
  629. template <typename T>
  630. ObjectCache<std::shared_ptr> &cache(std::shared_ptr<T> & /*in*/) const {
  631. return _cache;
  632. }
  633. template <typename T>
  634. ObjectCache<vector> &cache(vector<T> & /*in*/) const {
  635. return _cacheArrays;
  636. }
  637. private:
  638. #ifndef ASSIMP_BUILD_BLENDER_NO_STATS
  639. mutable Statistics _stats;
  640. #endif
  641. mutable ObjectCache<vector> _cacheArrays;
  642. mutable ObjectCache<std::shared_ptr> _cache;
  643. mutable size_t next_cache_idx;
  644. };
  645. #ifdef _MSC_VER
  646. #pragma warning(default : 4355)
  647. #endif
  648. // -------------------------------------------------------------------------------
  649. /** Factory to extract a #DNA from the DNA1 file block in a BLEND file. */
  650. // -------------------------------------------------------------------------------
  651. class DNAParser {
  652. public:
  653. /** Bind the parser to a empty DNA and an input stream */
  654. DNAParser(FileDatabase &db) :
  655. db(db) {}
  656. public:
  657. // --------------------------------------------------------
  658. /** Locate the DNA in the file and parse it. The input
  659. * stream is expected to point to the beginning of the DN1
  660. * chunk at the time this method is called and is
  661. * undefined afterwards.
  662. * @throw DeadlyImportError if the DNA cannot be read.
  663. * @note The position of the stream pointer is undefined
  664. * afterwards.*/
  665. void Parse();
  666. public:
  667. /** Obtain a reference to the extracted DNA information */
  668. const Blender::DNA &GetDNA() const {
  669. return db.dna;
  670. }
  671. private:
  672. FileDatabase &db;
  673. };
  674. /**
  675. * @brief read CustomData's data to ptr to mem
  676. * @param[out] out memory ptr to set
  677. * @param[in] cdtype to read
  678. * @param[in] cnt cnt of elements to read
  679. * @param[in] db to read elements from
  680. * @return true when ok
  681. */
  682. bool readCustomData(std::shared_ptr<ElemBase> &out, int cdtype, size_t cnt, const FileDatabase &db);
  683. } // namespace Blender
  684. } // namespace Assimp
  685. #include "BlenderDNA.inl"
  686. #endif