AssbinFileWriter.cpp 29 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832
  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. /** @file AssbinFileWriter.cpp
  34. * @brief Implementation of Assbin file writer.
  35. */
  36. #include "AssbinFileWriter.h"
  37. #include "Common/assbin_chunks.h"
  38. #include "PostProcessing/ProcessHelper.h"
  39. #include <assimp/Exceptional.h>
  40. #include <assimp/version.h>
  41. #include <assimp/Exporter.hpp>
  42. #include <assimp/IOStream.hpp>
  43. #ifdef ASSIMP_BUILD_NO_OWN_ZLIB
  44. #include <zlib.h>
  45. #else
  46. #include "../contrib/zlib/zlib.h"
  47. #endif
  48. #include <time.h>
  49. #ifdef _WIN32
  50. #pragma warning(push)
  51. #pragma warning(disable : 4706)
  52. #endif // _WIN32
  53. namespace Assimp {
  54. template <typename T>
  55. size_t Write(IOStream *stream, const T &v) {
  56. return stream->Write(&v, sizeof(T), 1);
  57. }
  58. // -----------------------------------------------------------------------------------
  59. // Serialize an aiString
  60. template <>
  61. inline size_t Write<aiString>(IOStream *stream, const aiString &s) {
  62. const size_t s2 = (uint32_t)s.length;
  63. stream->Write(&s, 4, 1);
  64. stream->Write(s.data, s2, 1);
  65. return s2 + 4;
  66. }
  67. // -----------------------------------------------------------------------------------
  68. // Serialize an unsigned int as uint32_t
  69. template <>
  70. inline size_t Write<unsigned int>(IOStream *stream, const unsigned int &w) {
  71. const uint32_t t = (uint32_t)w;
  72. if (w > t) {
  73. // this shouldn't happen, integers in Assimp data structures never exceed 2^32
  74. throw DeadlyExportError("loss of data due to 64 -> 32 bit integer conversion");
  75. }
  76. stream->Write(&t, 4, 1);
  77. return 4;
  78. }
  79. // -----------------------------------------------------------------------------------
  80. // Serialize an unsigned int as uint16_t
  81. template <>
  82. inline size_t Write<uint16_t>(IOStream *stream, const uint16_t &w) {
  83. static_assert(sizeof(uint16_t) == 2, "sizeof(uint16_t)==2");
  84. stream->Write(&w, 2, 1);
  85. return 2;
  86. }
  87. // -----------------------------------------------------------------------------------
  88. // Serialize a float
  89. template <>
  90. inline size_t Write<float>(IOStream *stream, const float &f) {
  91. static_assert(sizeof(float) == 4, "sizeof(float)==4");
  92. stream->Write(&f, 4, 1);
  93. return 4;
  94. }
  95. // -----------------------------------------------------------------------------------
  96. // Serialize a double
  97. template <>
  98. inline size_t Write<double>(IOStream *stream, const double &f) {
  99. static_assert(sizeof(double) == 8, "sizeof(double)==8");
  100. stream->Write(&f, 8, 1);
  101. return 8;
  102. }
  103. // -----------------------------------------------------------------------------------
  104. // Serialize a vec3
  105. template <>
  106. inline size_t Write<aiVector3D>(IOStream *stream, const aiVector3D &v) {
  107. size_t t = Write<float>(stream, v.x);
  108. t += Write<float>(stream, v.y);
  109. t += Write<float>(stream, v.z);
  110. return t;
  111. }
  112. // -----------------------------------------------------------------------------------
  113. // Serialize a color value
  114. template <>
  115. inline size_t Write<aiColor3D>(IOStream *stream, const aiColor3D &v) {
  116. size_t t = Write<float>(stream, v.r);
  117. t += Write<float>(stream, v.g);
  118. t += Write<float>(stream, v.b);
  119. return t;
  120. }
  121. // -----------------------------------------------------------------------------------
  122. // Serialize a color value
  123. template <>
  124. inline size_t Write<aiColor4D>(IOStream *stream, const aiColor4D &v) {
  125. size_t t = Write<float>(stream, v.r);
  126. t += Write<float>(stream, v.g);
  127. t += Write<float>(stream, v.b);
  128. t += Write<float>(stream, v.a);
  129. return t;
  130. }
  131. // -----------------------------------------------------------------------------------
  132. // Serialize a quaternion
  133. template <>
  134. inline size_t Write<aiQuaternion>(IOStream *stream, const aiQuaternion &v) {
  135. size_t t = Write<float>(stream, v.w);
  136. t += Write<float>(stream, v.x);
  137. t += Write<float>(stream, v.y);
  138. t += Write<float>(stream, v.z);
  139. ai_assert(t == 16);
  140. return 16;
  141. }
  142. // -----------------------------------------------------------------------------------
  143. // Serialize a vertex weight
  144. template <>
  145. inline size_t Write<aiVertexWeight>(IOStream *stream, const aiVertexWeight &v) {
  146. size_t t = Write<unsigned int>(stream, v.mVertexId);
  147. return t + Write<float>(stream, v.mWeight);
  148. }
  149. // -----------------------------------------------------------------------------------
  150. // Serialize a mat4x4
  151. template <>
  152. inline size_t Write<aiMatrix4x4>(IOStream *stream, const aiMatrix4x4 &m) {
  153. for (unsigned int i = 0; i < 4; ++i) {
  154. for (unsigned int i2 = 0; i2 < 4; ++i2) {
  155. Write<float>(stream, m[i][i2]);
  156. }
  157. }
  158. return 64;
  159. }
  160. // -----------------------------------------------------------------------------------
  161. // Serialize an aiVectorKey
  162. template <>
  163. inline size_t Write<aiVectorKey>(IOStream *stream, const aiVectorKey &v) {
  164. const size_t t = Write<double>(stream, v.mTime);
  165. return t + Write<aiVector3D>(stream, v.mValue);
  166. }
  167. // -----------------------------------------------------------------------------------
  168. // Serialize an aiQuatKey
  169. template <>
  170. inline size_t Write<aiQuatKey>(IOStream *stream, const aiQuatKey &v) {
  171. const size_t t = Write<double>(stream, v.mTime);
  172. return t + Write<aiQuaternion>(stream, v.mValue);
  173. }
  174. template <typename T>
  175. inline size_t WriteBounds(IOStream *stream, const T *in, unsigned int size) {
  176. T minc, maxc;
  177. ArrayBounds(in, size, minc, maxc);
  178. const size_t t = Write<T>(stream, minc);
  179. return t + Write<T>(stream, maxc);
  180. }
  181. // We use this to write out non-byte arrays so that we write using the specializations.
  182. // This way we avoid writing out extra bytes that potentially come from struct alignment.
  183. template <typename T>
  184. inline size_t WriteArray(IOStream *stream, const T *in, unsigned int size) {
  185. size_t n = 0;
  186. for (unsigned int i = 0; i < size; i++)
  187. n += Write<T>(stream, in[i]);
  188. return n;
  189. }
  190. // ----------------------------------------------------------------------------------
  191. /** @class AssbinChunkWriter
  192. * @brief Chunk writer mechanism for the .assbin file structure
  193. *
  194. * This is a standard in-memory IOStream (most of the code is based on BlobIOStream),
  195. * the difference being that this takes another IOStream as a "container" in the
  196. * constructor, and when it is destroyed, it appends the magic number, the chunk size,
  197. * and the chunk contents to the container stream. This allows relatively easy chunk
  198. * chunk construction, even recursively.
  199. */
  200. class AssbinChunkWriter : public IOStream {
  201. private:
  202. uint8_t *buffer;
  203. uint32_t magic;
  204. IOStream *container;
  205. size_t cur_size, cursor, initial;
  206. private:
  207. // -------------------------------------------------------------------
  208. void Grow(size_t need = 0) {
  209. size_t new_size = std::max(initial, std::max(need, cur_size + (cur_size >> 1)));
  210. const uint8_t *const old = buffer;
  211. buffer = new uint8_t[new_size];
  212. if (old) {
  213. memcpy(buffer, old, cur_size);
  214. delete[] old;
  215. }
  216. cur_size = new_size;
  217. }
  218. public:
  219. AssbinChunkWriter(IOStream *container, uint32_t magic, size_t initial = 4096) :
  220. buffer(nullptr),
  221. magic(magic),
  222. container(container),
  223. cur_size(0),
  224. cursor(0),
  225. initial(initial) {
  226. // empty
  227. }
  228. virtual ~AssbinChunkWriter() {
  229. if (container) {
  230. container->Write(&magic, sizeof(uint32_t), 1);
  231. container->Write(&cursor, sizeof(uint32_t), 1);
  232. container->Write(buffer, 1, cursor);
  233. }
  234. if (buffer) delete[] buffer;
  235. }
  236. void *GetBufferPointer() { return buffer; }
  237. // -------------------------------------------------------------------
  238. virtual size_t Read(void * /*pvBuffer*/, size_t /*pSize*/, size_t /*pCount*/) {
  239. return 0;
  240. }
  241. virtual aiReturn Seek(size_t /*pOffset*/, aiOrigin /*pOrigin*/) {
  242. return aiReturn_FAILURE;
  243. }
  244. virtual size_t Tell() const {
  245. return cursor;
  246. }
  247. virtual void Flush() {
  248. // not implemented
  249. }
  250. virtual size_t FileSize() const {
  251. return cursor;
  252. }
  253. // -------------------------------------------------------------------
  254. virtual size_t Write(const void *pvBuffer, size_t pSize, size_t pCount) {
  255. pSize *= pCount;
  256. if (cursor + pSize > cur_size) {
  257. Grow(cursor + pSize);
  258. }
  259. memcpy(buffer + cursor, pvBuffer, pSize);
  260. cursor += pSize;
  261. return pCount;
  262. }
  263. };
  264. // ----------------------------------------------------------------------------------
  265. /** @class AssbinFileWriter
  266. * @brief Assbin file writer class
  267. *
  268. * This class writes an .assbin file, and is responsible for the file layout.
  269. */
  270. class AssbinFileWriter {
  271. private:
  272. bool shortened;
  273. bool compressed;
  274. protected:
  275. // -----------------------------------------------------------------------------------
  276. void WriteBinaryNode(IOStream *container, const aiNode *node) {
  277. AssbinChunkWriter chunk(container, ASSBIN_CHUNK_AINODE);
  278. unsigned int nb_metadata = (node->mMetaData != NULL ? node->mMetaData->mNumProperties : 0);
  279. Write<aiString>(&chunk, node->mName);
  280. Write<aiMatrix4x4>(&chunk, node->mTransformation);
  281. Write<unsigned int>(&chunk, node->mNumChildren);
  282. Write<unsigned int>(&chunk, node->mNumMeshes);
  283. Write<unsigned int>(&chunk, nb_metadata);
  284. for (unsigned int i = 0; i < node->mNumMeshes; ++i) {
  285. Write<unsigned int>(&chunk, node->mMeshes[i]);
  286. }
  287. for (unsigned int i = 0; i < node->mNumChildren; ++i) {
  288. WriteBinaryNode(&chunk, node->mChildren[i]);
  289. }
  290. for (unsigned int i = 0; i < nb_metadata; ++i) {
  291. const aiString &key = node->mMetaData->mKeys[i];
  292. aiMetadataType type = node->mMetaData->mValues[i].mType;
  293. void *value = node->mMetaData->mValues[i].mData;
  294. Write<aiString>(&chunk, key);
  295. Write<uint16_t>(&chunk, (uint16_t)type);
  296. switch (type) {
  297. case AI_BOOL:
  298. Write<bool>(&chunk, *((bool *)value));
  299. break;
  300. case AI_INT32:
  301. Write<int32_t>(&chunk, *((int32_t *)value));
  302. break;
  303. case AI_UINT64:
  304. Write<uint64_t>(&chunk, *((uint64_t *)value));
  305. break;
  306. case AI_FLOAT:
  307. Write<float>(&chunk, *((float *)value));
  308. break;
  309. case AI_DOUBLE:
  310. Write<double>(&chunk, *((double *)value));
  311. break;
  312. case AI_AISTRING:
  313. Write<aiString>(&chunk, *((aiString *)value));
  314. break;
  315. case AI_AIVECTOR3D:
  316. Write<aiVector3D>(&chunk, *((aiVector3D *)value));
  317. break;
  318. #ifdef SWIG
  319. case FORCE_32BIT:
  320. #endif // SWIG
  321. default:
  322. break;
  323. }
  324. }
  325. }
  326. // -----------------------------------------------------------------------------------
  327. void WriteBinaryTexture(IOStream *container, const aiTexture *tex) {
  328. AssbinChunkWriter chunk(container, ASSBIN_CHUNK_AITEXTURE);
  329. Write<unsigned int>(&chunk, tex->mWidth);
  330. Write<unsigned int>(&chunk, tex->mHeight);
  331. // Write the texture format, but don't include the null terminator.
  332. chunk.Write(tex->achFormatHint, sizeof(char), HINTMAXTEXTURELEN - 1);
  333. if (!shortened) {
  334. if (!tex->mHeight) {
  335. chunk.Write(tex->pcData, 1, tex->mWidth);
  336. } else {
  337. chunk.Write(tex->pcData, 1, tex->mWidth * tex->mHeight * 4);
  338. }
  339. }
  340. }
  341. // -----------------------------------------------------------------------------------
  342. void WriteBinaryBone(IOStream *container, const aiBone *b) {
  343. AssbinChunkWriter chunk(container, ASSBIN_CHUNK_AIBONE);
  344. Write<aiString>(&chunk, b->mName);
  345. Write<unsigned int>(&chunk, b->mNumWeights);
  346. Write<aiMatrix4x4>(&chunk, b->mOffsetMatrix);
  347. // for the moment we write dumb min/max values for the bones, too.
  348. // maybe I'll add a better, hash-like solution later
  349. if (shortened) {
  350. WriteBounds(&chunk, b->mWeights, b->mNumWeights);
  351. } // else write as usual
  352. else
  353. WriteArray<aiVertexWeight>(&chunk, b->mWeights, b->mNumWeights);
  354. }
  355. // -----------------------------------------------------------------------------------
  356. void WriteBinaryMesh(IOStream *container, const aiMesh *mesh) {
  357. AssbinChunkWriter chunk(container, ASSBIN_CHUNK_AIMESH);
  358. Write<unsigned int>(&chunk, mesh->mPrimitiveTypes);
  359. Write<unsigned int>(&chunk, mesh->mNumVertices);
  360. Write<unsigned int>(&chunk, mesh->mNumFaces);
  361. Write<unsigned int>(&chunk, mesh->mNumBones);
  362. Write<unsigned int>(&chunk, mesh->mMaterialIndex);
  363. // first of all, write bits for all existent vertex components
  364. unsigned int c = 0;
  365. if (mesh->mVertices) {
  366. c |= ASSBIN_MESH_HAS_POSITIONS;
  367. }
  368. if (mesh->mNormals) {
  369. c |= ASSBIN_MESH_HAS_NORMALS;
  370. }
  371. if (mesh->mTangents && mesh->mBitangents) {
  372. c |= ASSBIN_MESH_HAS_TANGENTS_AND_BITANGENTS;
  373. }
  374. for (unsigned int n = 0; n < AI_MAX_NUMBER_OF_TEXTURECOORDS; ++n) {
  375. if (!mesh->mTextureCoords[n]) {
  376. break;
  377. }
  378. c |= ASSBIN_MESH_HAS_TEXCOORD(n);
  379. }
  380. for (unsigned int n = 0; n < AI_MAX_NUMBER_OF_COLOR_SETS; ++n) {
  381. if (!mesh->mColors[n]) {
  382. break;
  383. }
  384. c |= ASSBIN_MESH_HAS_COLOR(n);
  385. }
  386. Write<unsigned int>(&chunk, c);
  387. aiVector3D minVec, maxVec;
  388. if (mesh->mVertices) {
  389. if (shortened) {
  390. WriteBounds(&chunk, mesh->mVertices, mesh->mNumVertices);
  391. } // else write as usual
  392. else
  393. WriteArray<aiVector3D>(&chunk, mesh->mVertices, mesh->mNumVertices);
  394. }
  395. if (mesh->mNormals) {
  396. if (shortened) {
  397. WriteBounds(&chunk, mesh->mNormals, mesh->mNumVertices);
  398. } // else write as usual
  399. else
  400. WriteArray<aiVector3D>(&chunk, mesh->mNormals, mesh->mNumVertices);
  401. }
  402. if (mesh->mTangents && mesh->mBitangents) {
  403. if (shortened) {
  404. WriteBounds(&chunk, mesh->mTangents, mesh->mNumVertices);
  405. WriteBounds(&chunk, mesh->mBitangents, mesh->mNumVertices);
  406. } // else write as usual
  407. else {
  408. WriteArray<aiVector3D>(&chunk, mesh->mTangents, mesh->mNumVertices);
  409. WriteArray<aiVector3D>(&chunk, mesh->mBitangents, mesh->mNumVertices);
  410. }
  411. }
  412. for (unsigned int n = 0; n < AI_MAX_NUMBER_OF_COLOR_SETS; ++n) {
  413. if (!mesh->mColors[n])
  414. break;
  415. if (shortened) {
  416. WriteBounds(&chunk, mesh->mColors[n], mesh->mNumVertices);
  417. } // else write as usual
  418. else
  419. WriteArray<aiColor4D>(&chunk, mesh->mColors[n], mesh->mNumVertices);
  420. }
  421. for (unsigned int n = 0; n < AI_MAX_NUMBER_OF_TEXTURECOORDS; ++n) {
  422. if (!mesh->mTextureCoords[n])
  423. break;
  424. // write number of UV components
  425. Write<unsigned int>(&chunk, mesh->mNumUVComponents[n]);
  426. if (shortened) {
  427. WriteBounds(&chunk, mesh->mTextureCoords[n], mesh->mNumVertices);
  428. } // else write as usual
  429. else
  430. WriteArray<aiVector3D>(&chunk, mesh->mTextureCoords[n], mesh->mNumVertices);
  431. }
  432. // write faces. There are no floating-point calculations involved
  433. // in these, so we can write a simple hash over the face data
  434. // to the dump file. We generate a single 32 Bit hash for 512 faces
  435. // using Assimp's standard hashing function.
  436. if (shortened) {
  437. unsigned int processed = 0;
  438. for (unsigned int job; (job = std::min(mesh->mNumFaces - processed, 512u)); processed += job) {
  439. uint32_t hash = 0;
  440. for (unsigned int a = 0; a < job; ++a) {
  441. const aiFace &f = mesh->mFaces[processed + a];
  442. uint32_t tmp = f.mNumIndices;
  443. hash = SuperFastHash(reinterpret_cast<const char *>(&tmp), sizeof tmp, hash);
  444. for (unsigned int i = 0; i < f.mNumIndices; ++i) {
  445. static_assert(AI_MAX_VERTICES <= 0xffffffff, "AI_MAX_VERTICES <= 0xffffffff");
  446. tmp = static_cast<uint32_t>(f.mIndices[i]);
  447. hash = SuperFastHash(reinterpret_cast<const char *>(&tmp), sizeof tmp, hash);
  448. }
  449. }
  450. Write<unsigned int>(&chunk, hash);
  451. }
  452. } else // else write as usual
  453. {
  454. // if there are less than 2^16 vertices, we can simply use 16 bit integers ...
  455. for (unsigned int i = 0; i < mesh->mNumFaces; ++i) {
  456. const aiFace &f = mesh->mFaces[i];
  457. static_assert(AI_MAX_FACE_INDICES <= 0xffff, "AI_MAX_FACE_INDICES <= 0xffff");
  458. Write<uint16_t>(&chunk, static_cast<uint16_t>(f.mNumIndices));
  459. for (unsigned int a = 0; a < f.mNumIndices; ++a) {
  460. if (mesh->mNumVertices < (1u << 16)) {
  461. Write<uint16_t>(&chunk, static_cast<uint16_t>(f.mIndices[a]));
  462. } else {
  463. Write<unsigned int>(&chunk, f.mIndices[a]);
  464. }
  465. }
  466. }
  467. }
  468. // write bones
  469. if (mesh->mNumBones) {
  470. for (unsigned int a = 0; a < mesh->mNumBones; ++a) {
  471. const aiBone *b = mesh->mBones[a];
  472. WriteBinaryBone(&chunk, b);
  473. }
  474. }
  475. }
  476. // -----------------------------------------------------------------------------------
  477. void WriteBinaryMaterialProperty(IOStream *container, const aiMaterialProperty *prop) {
  478. AssbinChunkWriter chunk(container, ASSBIN_CHUNK_AIMATERIALPROPERTY);
  479. Write<aiString>(&chunk, prop->mKey);
  480. Write<unsigned int>(&chunk, prop->mSemantic);
  481. Write<unsigned int>(&chunk, prop->mIndex);
  482. Write<unsigned int>(&chunk, prop->mDataLength);
  483. Write<unsigned int>(&chunk, (unsigned int)prop->mType);
  484. chunk.Write(prop->mData, 1, prop->mDataLength);
  485. }
  486. // -----------------------------------------------------------------------------------
  487. void WriteBinaryMaterial(IOStream *container, const aiMaterial *mat) {
  488. AssbinChunkWriter chunk(container, ASSBIN_CHUNK_AIMATERIAL);
  489. Write<unsigned int>(&chunk, mat->mNumProperties);
  490. for (unsigned int i = 0; i < mat->mNumProperties; ++i) {
  491. WriteBinaryMaterialProperty(&chunk, mat->mProperties[i]);
  492. }
  493. }
  494. // -----------------------------------------------------------------------------------
  495. void WriteBinaryNodeAnim(IOStream *container, const aiNodeAnim *nd) {
  496. AssbinChunkWriter chunk(container, ASSBIN_CHUNK_AINODEANIM);
  497. Write<aiString>(&chunk, nd->mNodeName);
  498. Write<unsigned int>(&chunk, nd->mNumPositionKeys);
  499. Write<unsigned int>(&chunk, nd->mNumRotationKeys);
  500. Write<unsigned int>(&chunk, nd->mNumScalingKeys);
  501. Write<unsigned int>(&chunk, nd->mPreState);
  502. Write<unsigned int>(&chunk, nd->mPostState);
  503. if (nd->mPositionKeys) {
  504. if (shortened) {
  505. WriteBounds(&chunk, nd->mPositionKeys, nd->mNumPositionKeys);
  506. } // else write as usual
  507. else
  508. WriteArray<aiVectorKey>(&chunk, nd->mPositionKeys, nd->mNumPositionKeys);
  509. }
  510. if (nd->mRotationKeys) {
  511. if (shortened) {
  512. WriteBounds(&chunk, nd->mRotationKeys, nd->mNumRotationKeys);
  513. } // else write as usual
  514. else
  515. WriteArray<aiQuatKey>(&chunk, nd->mRotationKeys, nd->mNumRotationKeys);
  516. }
  517. if (nd->mScalingKeys) {
  518. if (shortened) {
  519. WriteBounds(&chunk, nd->mScalingKeys, nd->mNumScalingKeys);
  520. } // else write as usual
  521. else
  522. WriteArray<aiVectorKey>(&chunk, nd->mScalingKeys, nd->mNumScalingKeys);
  523. }
  524. }
  525. // -----------------------------------------------------------------------------------
  526. void WriteBinaryAnim(IOStream *container, const aiAnimation *anim) {
  527. AssbinChunkWriter chunk(container, ASSBIN_CHUNK_AIANIMATION);
  528. Write<aiString>(&chunk, anim->mName);
  529. Write<double>(&chunk, anim->mDuration);
  530. Write<double>(&chunk, anim->mTicksPerSecond);
  531. Write<unsigned int>(&chunk, anim->mNumChannels);
  532. for (unsigned int a = 0; a < anim->mNumChannels; ++a) {
  533. const aiNodeAnim *nd = anim->mChannels[a];
  534. WriteBinaryNodeAnim(&chunk, nd);
  535. }
  536. }
  537. // -----------------------------------------------------------------------------------
  538. void WriteBinaryLight(IOStream *container, const aiLight *l) {
  539. AssbinChunkWriter chunk(container, ASSBIN_CHUNK_AILIGHT);
  540. Write<aiString>(&chunk, l->mName);
  541. Write<unsigned int>(&chunk, l->mType);
  542. if (l->mType != aiLightSource_DIRECTIONAL) {
  543. Write<float>(&chunk, l->mAttenuationConstant);
  544. Write<float>(&chunk, l->mAttenuationLinear);
  545. Write<float>(&chunk, l->mAttenuationQuadratic);
  546. }
  547. Write<aiColor3D>(&chunk, l->mColorDiffuse);
  548. Write<aiColor3D>(&chunk, l->mColorSpecular);
  549. Write<aiColor3D>(&chunk, l->mColorAmbient);
  550. if (l->mType == aiLightSource_SPOT) {
  551. Write<float>(&chunk, l->mAngleInnerCone);
  552. Write<float>(&chunk, l->mAngleOuterCone);
  553. }
  554. }
  555. // -----------------------------------------------------------------------------------
  556. void WriteBinaryCamera(IOStream *container, const aiCamera *cam) {
  557. AssbinChunkWriter chunk(container, ASSBIN_CHUNK_AICAMERA);
  558. Write<aiString>(&chunk, cam->mName);
  559. Write<aiVector3D>(&chunk, cam->mPosition);
  560. Write<aiVector3D>(&chunk, cam->mLookAt);
  561. Write<aiVector3D>(&chunk, cam->mUp);
  562. Write<float>(&chunk, cam->mHorizontalFOV);
  563. Write<float>(&chunk, cam->mClipPlaneNear);
  564. Write<float>(&chunk, cam->mClipPlaneFar);
  565. Write<float>(&chunk, cam->mAspect);
  566. }
  567. // -----------------------------------------------------------------------------------
  568. void WriteBinaryScene(IOStream *container, const aiScene *scene) {
  569. AssbinChunkWriter chunk(container, ASSBIN_CHUNK_AISCENE);
  570. // basic scene information
  571. Write<unsigned int>(&chunk, scene->mFlags);
  572. Write<unsigned int>(&chunk, scene->mNumMeshes);
  573. Write<unsigned int>(&chunk, scene->mNumMaterials);
  574. Write<unsigned int>(&chunk, scene->mNumAnimations);
  575. Write<unsigned int>(&chunk, scene->mNumTextures);
  576. Write<unsigned int>(&chunk, scene->mNumLights);
  577. Write<unsigned int>(&chunk, scene->mNumCameras);
  578. // write node graph
  579. WriteBinaryNode(&chunk, scene->mRootNode);
  580. // write all meshes
  581. for (unsigned int i = 0; i < scene->mNumMeshes; ++i) {
  582. const aiMesh *mesh = scene->mMeshes[i];
  583. WriteBinaryMesh(&chunk, mesh);
  584. }
  585. // write materials
  586. for (unsigned int i = 0; i < scene->mNumMaterials; ++i) {
  587. const aiMaterial *mat = scene->mMaterials[i];
  588. WriteBinaryMaterial(&chunk, mat);
  589. }
  590. // write all animations
  591. for (unsigned int i = 0; i < scene->mNumAnimations; ++i) {
  592. const aiAnimation *anim = scene->mAnimations[i];
  593. WriteBinaryAnim(&chunk, anim);
  594. }
  595. // write all textures
  596. for (unsigned int i = 0; i < scene->mNumTextures; ++i) {
  597. const aiTexture *mesh = scene->mTextures[i];
  598. WriteBinaryTexture(&chunk, mesh);
  599. }
  600. // write lights
  601. for (unsigned int i = 0; i < scene->mNumLights; ++i) {
  602. const aiLight *l = scene->mLights[i];
  603. WriteBinaryLight(&chunk, l);
  604. }
  605. // write cameras
  606. for (unsigned int i = 0; i < scene->mNumCameras; ++i) {
  607. const aiCamera *cam = scene->mCameras[i];
  608. WriteBinaryCamera(&chunk, cam);
  609. }
  610. }
  611. public:
  612. AssbinFileWriter(bool shortened, bool compressed) :
  613. shortened(shortened), compressed(compressed) {
  614. }
  615. // -----------------------------------------------------------------------------------
  616. // Write a binary model dump
  617. void WriteBinaryDump(const char *pFile, const char *cmd, IOSystem *pIOSystem, const aiScene *pScene) {
  618. IOStream *out = pIOSystem->Open(pFile, "wb");
  619. if (!out)
  620. throw std::runtime_error("Unable to open output file " + std::string(pFile) + '\n');
  621. auto CloseIOStream = [&]() {
  622. if (out) {
  623. pIOSystem->Close(out);
  624. out = nullptr; // Ensure this is only done once.
  625. }
  626. };
  627. try {
  628. time_t tt = time(NULL);
  629. #if _WIN32
  630. tm *p = gmtime(&tt);
  631. #else
  632. struct tm now;
  633. tm *p = gmtime_r(&tt, &now);
  634. #endif
  635. // header
  636. char s[64];
  637. memset(s, 0, 64);
  638. #if _MSC_VER >= 1400
  639. sprintf_s(s, "ASSIMP.binary-dump.%s", asctime(p));
  640. #else
  641. ai_snprintf(s, 64, "ASSIMP.binary-dump.%s", asctime(p));
  642. #endif
  643. out->Write(s, 44, 1);
  644. // == 44 bytes
  645. Write<unsigned int>(out, ASSBIN_VERSION_MAJOR);
  646. Write<unsigned int>(out, ASSBIN_VERSION_MINOR);
  647. Write<unsigned int>(out, aiGetVersionRevision());
  648. Write<unsigned int>(out, aiGetCompileFlags());
  649. Write<uint16_t>(out, shortened);
  650. Write<uint16_t>(out, compressed);
  651. // == 20 bytes
  652. char buff[256] = { 0 };
  653. ai_snprintf(buff, 256, "%s", pFile);
  654. out->Write(buff, sizeof(char), 256);
  655. memset(buff, 0, sizeof(buff));
  656. ai_snprintf(buff, 128, "%s", cmd);
  657. out->Write(buff, sizeof(char), 128);
  658. // leave 64 bytes free for future extensions
  659. memset(buff, 0xcd, 64);
  660. out->Write(buff, sizeof(char), 64);
  661. // == 435 bytes
  662. // ==== total header size: 512 bytes
  663. ai_assert(out->Tell() == ASSBIN_HEADER_LENGTH);
  664. // Up to here the data is uncompressed. For compressed files, the rest
  665. // is compressed using standard DEFLATE from zlib.
  666. if (compressed) {
  667. AssbinChunkWriter uncompressedStream(NULL, 0);
  668. WriteBinaryScene(&uncompressedStream, pScene);
  669. uLongf uncompressedSize = static_cast<uLongf>(uncompressedStream.Tell());
  670. uLongf compressedSize = (uLongf)compressBound(uncompressedSize);
  671. uint8_t *compressedBuffer = new uint8_t[compressedSize];
  672. int res = compress2(compressedBuffer, &compressedSize, (const Bytef *)uncompressedStream.GetBufferPointer(), uncompressedSize, 9);
  673. if (res != Z_OK) {
  674. delete[] compressedBuffer;
  675. throw DeadlyExportError("Compression failed.");
  676. }
  677. out->Write(&uncompressedSize, sizeof(uint32_t), 1);
  678. out->Write(compressedBuffer, sizeof(char), compressedSize);
  679. delete[] compressedBuffer;
  680. } else {
  681. WriteBinaryScene(out, pScene);
  682. }
  683. CloseIOStream();
  684. } catch (...) {
  685. CloseIOStream();
  686. throw;
  687. }
  688. }
  689. };
  690. void DumpSceneToAssbin(
  691. const char *pFile, const char *cmd, IOSystem *pIOSystem,
  692. const aiScene *pScene, bool shortened, bool compressed) {
  693. AssbinFileWriter fileWriter(shortened, compressed);
  694. fileWriter.WriteBinaryDump(pFile, cmd, pIOSystem, pScene);
  695. }
  696. #ifdef _WIN32
  697. #pragma warning(pop)
  698. #endif // _WIN32
  699. } // end of namespace Assimp