Q3DLoader.cpp 21 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575
  1. /*
  2. ---------------------------------------------------------------------------
  3. Open Asset Import Library (assimp)
  4. ---------------------------------------------------------------------------
  5. Copyright (c) 2006-2022, assimp team
  6. All rights reserved.
  7. Redistribution and use of this software in source and binary forms,
  8. with or without modification, are permitted provided that the following
  9. conditions are met:
  10. * Redistributions of source code must retain the above
  11. copyright notice, this list of conditions and the
  12. following disclaimer.
  13. * Redistributions in binary form must reproduce the above
  14. copyright notice, this list of conditions and the
  15. following disclaimer in the documentation and/or other
  16. materials provided with the distribution.
  17. * Neither the name of the assimp team, nor the names of its
  18. contributors may be used to endorse or promote products
  19. derived from this software without specific prior
  20. written permission of the assimp team.
  21. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
  22. "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
  23. LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
  24. A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
  25. OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
  26. SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
  27. LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
  28. DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
  29. THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
  30. (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
  31. OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
  32. ---------------------------------------------------------------------------
  33. */
  34. /** @file Q3DLoader.cpp
  35. * @brief Implementation of the Q3D importer class
  36. */
  37. #ifndef ASSIMP_BUILD_NO_Q3D_IMPORTER
  38. // internal headers
  39. #include "Q3DLoader.h"
  40. #include <assimp/StringUtils.h>
  41. #include <assimp/StreamReader.h>
  42. #include <assimp/fast_atof.h>
  43. #include <assimp/importerdesc.h>
  44. #include <assimp/scene.h>
  45. #include <assimp/DefaultLogger.hpp>
  46. #include <assimp/IOSystem.hpp>
  47. namespace Assimp {
  48. static constexpr aiImporterDesc desc = {
  49. "Quick3D Importer",
  50. "",
  51. "",
  52. "http://www.quick3d.com/",
  53. aiImporterFlags_SupportBinaryFlavour,
  54. 0,
  55. 0,
  56. 0,
  57. 0,
  58. "q3o q3s"
  59. };
  60. // ------------------------------------------------------------------------------------------------
  61. // Constructor to be privately used by Importer
  62. Q3DImporter::Q3DImporter() = default;
  63. // ------------------------------------------------------------------------------------------------
  64. // Destructor, private as well
  65. Q3DImporter::~Q3DImporter() = default;
  66. // ------------------------------------------------------------------------------------------------
  67. // Returns whether the class can handle the format of the given file.
  68. bool Q3DImporter::CanRead(const std::string &pFile, IOSystem *pIOHandler, bool /*checkSig*/) const {
  69. static const char *tokens[] = { "quick3Do", "quick3Ds" };
  70. return SearchFileHeaderForToken(pIOHandler, pFile, tokens, AI_COUNT_OF(tokens));
  71. }
  72. // ------------------------------------------------------------------------------------------------
  73. const aiImporterDesc *Q3DImporter::GetInfo() const {
  74. return &desc;
  75. }
  76. // ------------------------------------------------------------------------------------------------
  77. // Imports the given file into the given scene structure.
  78. void Q3DImporter::InternReadFile(const std::string &pFile,
  79. aiScene *pScene, IOSystem *pIOHandler) {
  80. auto file = pIOHandler->Open(pFile, "rb");
  81. if (!file)
  82. throw DeadlyImportError("Quick3D: Could not open ", pFile);
  83. StreamReaderLE stream(file);
  84. // The header is 22 bytes large
  85. if (stream.GetRemainingSize() < 22)
  86. throw DeadlyImportError("File is either empty or corrupt: ", pFile);
  87. // Check the file's signature
  88. if (ASSIMP_strincmp((const char *)stream.GetPtr(), "quick3Do", 8) &&
  89. ASSIMP_strincmp((const char *)stream.GetPtr(), "quick3Ds", 8)) {
  90. throw DeadlyImportError("Not a Quick3D file. Signature string is: ", ai_str_toprintable((const char *)stream.GetPtr(), 8));
  91. }
  92. // Print the file format version
  93. ASSIMP_LOG_INFO("Quick3D File format version: ",
  94. std::string(&((const char *)stream.GetPtr())[8], 2));
  95. // ... an store it
  96. char major = ((const char *)stream.GetPtr())[8];
  97. char minor = ((const char *)stream.GetPtr())[9];
  98. stream.IncPtr(10);
  99. unsigned int numMeshes = (unsigned int)stream.GetI4();
  100. unsigned int numMats = (unsigned int)stream.GetI4();
  101. unsigned int numTextures = (unsigned int)stream.GetI4();
  102. std::vector<Material> materials;
  103. try {
  104. materials.reserve(numMats);
  105. } catch (const std::bad_alloc &) {
  106. ASSIMP_LOG_ERROR("Invalid alloc for materials.");
  107. throw DeadlyImportError("Invalid Quick3D-file, material allocation failed.");
  108. }
  109. std::vector<Mesh> meshes;
  110. try {
  111. meshes.reserve(numMeshes);
  112. } catch (const std::bad_alloc &) {
  113. ASSIMP_LOG_ERROR("Invalid alloc for meshes.");
  114. throw DeadlyImportError("Invalid Quick3D-file, mesh allocation failed.");
  115. }
  116. // Allocate the scene root node
  117. pScene->mRootNode = new aiNode();
  118. aiColor3D fgColor(0.6f, 0.6f, 0.6f);
  119. // Now read all file chunks
  120. while (true) {
  121. if (stream.GetRemainingSize() < 1) break;
  122. char c = stream.GetI1();
  123. switch (c) {
  124. // Meshes chunk
  125. case 'm': {
  126. for (unsigned int quak = 0; quak < numMeshes; ++quak) {
  127. meshes.emplace_back();
  128. Mesh &mesh = meshes.back();
  129. // read all vertices
  130. unsigned int numVerts = (unsigned int)stream.GetI4();
  131. if (!numVerts)
  132. throw DeadlyImportError("Quick3D: Found mesh with zero vertices");
  133. std::vector<aiVector3D> &verts = mesh.verts;
  134. verts.resize(numVerts);
  135. for (unsigned int i = 0; i < numVerts; ++i) {
  136. verts[i].x = stream.GetF4();
  137. verts[i].y = stream.GetF4();
  138. verts[i].z = stream.GetF4();
  139. }
  140. // read all faces
  141. numVerts = (unsigned int)stream.GetI4();
  142. if (!numVerts)
  143. throw DeadlyImportError("Quick3D: Found mesh with zero faces");
  144. std::vector<Face> &faces = mesh.faces;
  145. faces.reserve(numVerts);
  146. // number of indices
  147. for (unsigned int i = 0; i < numVerts; ++i) {
  148. faces.emplace_back(stream.GetI2());
  149. if (faces.back().indices.empty())
  150. throw DeadlyImportError("Quick3D: Found face with zero indices");
  151. }
  152. // indices
  153. for (unsigned int i = 0; i < numVerts; ++i) {
  154. Face &vec = faces[i];
  155. for (unsigned int a = 0; a < (unsigned int)vec.indices.size(); ++a)
  156. vec.indices[a] = stream.GetI4();
  157. }
  158. // material indices
  159. for (unsigned int i = 0; i < numVerts; ++i) {
  160. faces[i].mat = (unsigned int)stream.GetI4();
  161. }
  162. // read all normals
  163. numVerts = (unsigned int)stream.GetI4();
  164. std::vector<aiVector3D> &normals = mesh.normals;
  165. normals.resize(numVerts);
  166. for (unsigned int i = 0; i < numVerts; ++i) {
  167. normals[i].x = stream.GetF4();
  168. normals[i].y = stream.GetF4();
  169. normals[i].z = stream.GetF4();
  170. }
  171. numVerts = (unsigned int)stream.GetI4();
  172. if (numTextures && numVerts) {
  173. // read all texture coordinates
  174. std::vector<aiVector3D> &uv = mesh.uv;
  175. uv.resize(numVerts);
  176. for (unsigned int i = 0; i < numVerts; ++i) {
  177. uv[i].x = stream.GetF4();
  178. uv[i].y = stream.GetF4();
  179. }
  180. // UV indices
  181. for (unsigned int i = 0; i < (unsigned int)faces.size(); ++i) {
  182. Face &vec = faces[i];
  183. for (unsigned int a = 0; a < (unsigned int)vec.indices.size(); ++a) {
  184. vec.uvindices[a] = stream.GetI4();
  185. if (!i && !a)
  186. mesh.prevUVIdx = vec.uvindices[a];
  187. else if (vec.uvindices[a] != mesh.prevUVIdx)
  188. mesh.prevUVIdx = UINT_MAX;
  189. }
  190. }
  191. }
  192. // we don't need the rest, but we need to get to the next chunk
  193. stream.IncPtr(36);
  194. if (minor > '0' && major == '3')
  195. stream.IncPtr(mesh.faces.size());
  196. }
  197. } break;
  198. // materials chunk
  199. case 'c':
  200. for (unsigned int i = 0; i < numMats; ++i) {
  201. materials.emplace_back();
  202. Material &mat = materials.back();
  203. // read the material name
  204. c = stream.GetI1();
  205. while (c) {
  206. mat.name.data[mat.name.length++] = c;
  207. c = stream.GetI1();
  208. }
  209. // add the terminal character
  210. mat.name.data[mat.name.length] = '\0';
  211. // read the ambient color
  212. mat.ambient.r = stream.GetF4();
  213. mat.ambient.g = stream.GetF4();
  214. mat.ambient.b = stream.GetF4();
  215. // read the diffuse color
  216. mat.diffuse.r = stream.GetF4();
  217. mat.diffuse.g = stream.GetF4();
  218. mat.diffuse.b = stream.GetF4();
  219. // read the ambient color
  220. mat.specular.r = stream.GetF4();
  221. mat.specular.g = stream.GetF4();
  222. mat.specular.b = stream.GetF4();
  223. // read the transparency
  224. mat.transparency = stream.GetF4();
  225. // FIX: it could be the texture index ...
  226. mat.texIdx = (unsigned int)stream.GetI4();
  227. }
  228. break;
  229. // texture chunk
  230. case 't':
  231. pScene->mNumTextures = numTextures;
  232. if (!numTextures) {
  233. break;
  234. }
  235. pScene->mTextures = new aiTexture *[pScene->mNumTextures];
  236. // to make sure we won't crash if we leave through an exception
  237. ::memset(pScene->mTextures, 0, sizeof(void *) * pScene->mNumTextures);
  238. for (unsigned int i = 0; i < pScene->mNumTextures; ++i) {
  239. aiTexture *tex = pScene->mTextures[i] = new aiTexture;
  240. // skip the texture name
  241. while (stream.GetI1())
  242. ;
  243. // read texture width and height
  244. tex->mWidth = (unsigned int)stream.GetI4();
  245. tex->mHeight = (unsigned int)stream.GetI4();
  246. if (!tex->mWidth || !tex->mHeight) {
  247. throw DeadlyImportError("Quick3D: Invalid texture. Width or height is zero");
  248. }
  249. unsigned int mul = tex->mWidth * tex->mHeight;
  250. aiTexel *begin = tex->pcData = new aiTexel[mul];
  251. aiTexel *const end = &begin[mul - 1] + 1;
  252. for (; begin != end; ++begin) {
  253. begin->r = stream.GetI1();
  254. begin->g = stream.GetI1();
  255. begin->b = stream.GetI1();
  256. begin->a = 0xff;
  257. }
  258. }
  259. break;
  260. // scene chunk
  261. case 's': {
  262. // skip position and rotation
  263. stream.IncPtr(12);
  264. for (unsigned int i = 0; i < 4; ++i)
  265. for (unsigned int a = 0; a < 4; ++a)
  266. pScene->mRootNode->mTransformation[i][a] = stream.GetF4();
  267. stream.IncPtr(16);
  268. // now setup a single camera
  269. pScene->mNumCameras = 1;
  270. pScene->mCameras = new aiCamera *[1];
  271. aiCamera *cam = pScene->mCameras[0] = new aiCamera();
  272. cam->mPosition.x = stream.GetF4();
  273. cam->mPosition.y = stream.GetF4();
  274. cam->mPosition.z = stream.GetF4();
  275. cam->mName.Set("Q3DCamera");
  276. // skip eye rotation for the moment
  277. stream.IncPtr(12);
  278. // read the default material color
  279. fgColor.r = stream.GetF4();
  280. fgColor.g = stream.GetF4();
  281. fgColor.b = stream.GetF4();
  282. // skip some unimportant properties
  283. stream.IncPtr(29);
  284. // setup a single point light with no attenuation
  285. pScene->mNumLights = 1;
  286. pScene->mLights = new aiLight *[1];
  287. aiLight *light = pScene->mLights[0] = new aiLight();
  288. light->mName.Set("Q3DLight");
  289. light->mType = aiLightSource_POINT;
  290. light->mAttenuationConstant = 1;
  291. light->mAttenuationLinear = 0;
  292. light->mAttenuationQuadratic = 0;
  293. light->mColorDiffuse.r = stream.GetF4();
  294. light->mColorDiffuse.g = stream.GetF4();
  295. light->mColorDiffuse.b = stream.GetF4();
  296. light->mColorSpecular = light->mColorDiffuse;
  297. // We don't need the rest, but we need to know where this chunk ends.
  298. unsigned int temp = (unsigned int)(stream.GetI4() * stream.GetI4());
  299. // skip the background file name
  300. while (stream.GetI1())
  301. ;
  302. // skip background texture data + the remaining fields
  303. stream.IncPtr(temp * 3 + 20); // 4 bytes of unknown data here
  304. // TODO
  305. goto outer;
  306. }
  307. default:
  308. throw DeadlyImportError("Quick3D: Unknown chunk");
  309. };
  310. }
  311. outer:
  312. // If we have no mesh loaded - break here
  313. if (meshes.empty())
  314. throw DeadlyImportError("Quick3D: No meshes loaded");
  315. // If we have no materials loaded - generate a default mat
  316. if (materials.empty()) {
  317. ASSIMP_LOG_INFO("Quick3D: No material found, generating one");
  318. materials.emplace_back();
  319. materials.back().diffuse = fgColor;
  320. }
  321. // find out which materials we'll need
  322. typedef std::pair<unsigned int, unsigned int> FaceIdx;
  323. typedef std::vector<FaceIdx> FaceIdxArray;
  324. FaceIdxArray *fidx = new FaceIdxArray[materials.size()];
  325. unsigned int p = 0;
  326. for (std::vector<Mesh>::iterator it = meshes.begin(), end = meshes.end();
  327. it != end; ++it, ++p) {
  328. unsigned int q = 0;
  329. for (std::vector<Face>::iterator fit = (*it).faces.begin(), fend = (*it).faces.end();
  330. fit != fend; ++fit, ++q) {
  331. if ((*fit).mat >= materials.size()) {
  332. ASSIMP_LOG_WARN("Quick3D: Material index overflow");
  333. (*fit).mat = 0;
  334. }
  335. if (fidx[(*fit).mat].empty()) ++pScene->mNumMeshes;
  336. fidx[(*fit).mat].emplace_back(p, q);
  337. }
  338. }
  339. pScene->mNumMaterials = pScene->mNumMeshes;
  340. pScene->mMaterials = new aiMaterial *[pScene->mNumMaterials];
  341. pScene->mMeshes = new aiMesh *[pScene->mNumMaterials];
  342. for (unsigned int i = 0, real = 0; i < (unsigned int)materials.size(); ++i) {
  343. if (fidx[i].empty())
  344. continue;
  345. // Allocate a mesh and a material
  346. aiMesh *mesh = pScene->mMeshes[real] = new aiMesh();
  347. aiMaterial *mat = new aiMaterial();
  348. pScene->mMaterials[real] = mat;
  349. mesh->mMaterialIndex = real;
  350. // Build the output material
  351. Material &srcMat = materials[i];
  352. mat->AddProperty(&srcMat.diffuse, 1, AI_MATKEY_COLOR_DIFFUSE);
  353. mat->AddProperty(&srcMat.specular, 1, AI_MATKEY_COLOR_SPECULAR);
  354. mat->AddProperty(&srcMat.ambient, 1, AI_MATKEY_COLOR_AMBIENT);
  355. // NOTE: Ignore transparency for the moment - it seems
  356. // unclear how to interpret the data
  357. #if 0
  358. if (!(minor > '0' && major == '3'))
  359. srcMat.transparency = 1.0f - srcMat.transparency;
  360. mat->AddProperty(&srcMat.transparency, 1, AI_MATKEY_OPACITY);
  361. #endif
  362. // add shininess - Quick3D seems to use it ins its viewer
  363. srcMat.transparency = 16.f;
  364. mat->AddProperty(&srcMat.transparency, 1, AI_MATKEY_SHININESS);
  365. int m = (int)aiShadingMode_Phong;
  366. mat->AddProperty(&m, 1, AI_MATKEY_SHADING_MODEL);
  367. if (srcMat.name.length)
  368. mat->AddProperty(&srcMat.name, AI_MATKEY_NAME);
  369. // Add a texture
  370. if (srcMat.texIdx < pScene->mNumTextures || real < pScene->mNumTextures) {
  371. srcMat.name.data[0] = '*';
  372. srcMat.name.length = ASSIMP_itoa10(&srcMat.name.data[1], 1000,
  373. (srcMat.texIdx < pScene->mNumTextures ? srcMat.texIdx : real));
  374. mat->AddProperty(&srcMat.name, AI_MATKEY_TEXTURE_DIFFUSE(0));
  375. }
  376. mesh->mNumFaces = (unsigned int)fidx[i].size();
  377. aiFace *faces = mesh->mFaces = new aiFace[mesh->mNumFaces];
  378. // Now build the output mesh. First find out how many
  379. // vertices we'll need
  380. for (FaceIdxArray::const_iterator it = fidx[i].begin(), end = fidx[i].end();
  381. it != end; ++it) {
  382. mesh->mNumVertices += (unsigned int)meshes[(*it).first].faces[(*it).second].indices.size();
  383. }
  384. aiVector3D *verts = mesh->mVertices = new aiVector3D[mesh->mNumVertices];
  385. aiVector3D *norms = mesh->mNormals = new aiVector3D[mesh->mNumVertices];
  386. aiVector3D *uv = nullptr;
  387. if (real < pScene->mNumTextures) {
  388. uv = mesh->mTextureCoords[0] = new aiVector3D[mesh->mNumVertices];
  389. mesh->mNumUVComponents[0] = 2;
  390. }
  391. // Build the final array
  392. unsigned int cnt = 0;
  393. for (FaceIdxArray::const_iterator it = fidx[i].begin(), end = fidx[i].end();
  394. it != end; ++it, ++faces) {
  395. Mesh &curMesh = meshes[(*it).first];
  396. Face &face = curMesh.faces[(*it).second];
  397. faces->mNumIndices = (unsigned int)face.indices.size();
  398. faces->mIndices = new unsigned int[faces->mNumIndices];
  399. aiVector3D faceNormal;
  400. bool fnOK = false;
  401. for (unsigned int n = 0; n < faces->mNumIndices; ++n, ++cnt, ++norms, ++verts) {
  402. if (face.indices[n] >= curMesh.verts.size()) {
  403. ASSIMP_LOG_WARN("Quick3D: Vertex index overflow");
  404. face.indices[n] = 0;
  405. }
  406. // copy vertices
  407. *verts = curMesh.verts[face.indices[n]];
  408. if (face.indices[n] >= curMesh.normals.size() && faces->mNumIndices >= 3) {
  409. // we have no normal here - assign the face normal
  410. if (!fnOK) {
  411. const aiVector3D &pV1 = curMesh.verts[face.indices[0]];
  412. const aiVector3D &pV2 = curMesh.verts[face.indices[1]];
  413. const aiVector3D &pV3 = curMesh.verts[face.indices.size() - 1];
  414. faceNormal = (pV2 - pV1) ^ (pV3 - pV1).Normalize();
  415. fnOK = true;
  416. }
  417. *norms = faceNormal;
  418. } else {
  419. *norms = curMesh.normals[face.indices[n]];
  420. }
  421. // copy texture coordinates
  422. if (uv && curMesh.uv.size()) {
  423. if (curMesh.prevUVIdx != 0xffffffff && curMesh.uv.size() >= curMesh.verts.size()) // workaround
  424. {
  425. *uv = curMesh.uv[face.indices[n]];
  426. } else {
  427. if (face.uvindices[n] >= curMesh.uv.size()) {
  428. ASSIMP_LOG_WARN("Quick3D: Texture coordinate index overflow");
  429. face.uvindices[n] = 0;
  430. }
  431. *uv = curMesh.uv[face.uvindices[n]];
  432. }
  433. uv->y = 1.f - uv->y;
  434. ++uv;
  435. }
  436. // setup the new vertex index
  437. faces->mIndices[n] = cnt;
  438. }
  439. }
  440. ++real;
  441. }
  442. // Delete our nice helper array
  443. delete[] fidx;
  444. // Now we need to attach the meshes to the root node of the scene
  445. pScene->mRootNode->mNumMeshes = pScene->mNumMeshes;
  446. pScene->mRootNode->mMeshes = new unsigned int[pScene->mNumMeshes];
  447. for (unsigned int i = 0; i < pScene->mNumMeshes; ++i) {
  448. pScene->mRootNode->mMeshes[i] = i;
  449. }
  450. // Add cameras and light sources to the scene root node
  451. pScene->mRootNode->mNumChildren = pScene->mNumLights + pScene->mNumCameras;
  452. if (pScene->mRootNode->mNumChildren) {
  453. pScene->mRootNode->mChildren = new aiNode *[pScene->mRootNode->mNumChildren];
  454. // the light source
  455. aiNode *nd = pScene->mRootNode->mChildren[0] = new aiNode();
  456. nd->mParent = pScene->mRootNode;
  457. nd->mName.Set("Q3DLight");
  458. nd->mTransformation = pScene->mRootNode->mTransformation;
  459. nd->mTransformation.Inverse();
  460. // camera
  461. nd = pScene->mRootNode->mChildren[1] = new aiNode();
  462. nd->mParent = pScene->mRootNode;
  463. nd->mName.Set("Q3DCamera");
  464. nd->mTransformation = pScene->mRootNode->mChildren[0]->mTransformation;
  465. }
  466. }
  467. } // namespace Assimp
  468. #endif // !! ASSIMP_BUILD_NO_Q3D_IMPORTER