Q3DLoader.cpp 21 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579
  1. /*
  2. ---------------------------------------------------------------------------
  3. Open Asset Import Library (assimp)
  4. ---------------------------------------------------------------------------
  5. Copyright (c) 2006-2020, 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/StreamReader.h>
  41. #include <assimp/fast_atof.h>
  42. #include <assimp/importerdesc.h>
  43. #include <assimp/scene.h>
  44. #include <assimp/DefaultLogger.hpp>
  45. #include <assimp/IOSystem.hpp>
  46. using namespace Assimp;
  47. static const aiImporterDesc desc = {
  48. "Quick3D Importer",
  49. "",
  50. "",
  51. "http://www.quick3d.com/",
  52. aiImporterFlags_SupportBinaryFlavour,
  53. 0,
  54. 0,
  55. 0,
  56. 0,
  57. "q3o q3s"
  58. };
  59. // ------------------------------------------------------------------------------------------------
  60. // Constructor to be privately used by Importer
  61. Q3DImporter::Q3DImporter() {
  62. // empty
  63. }
  64. // ------------------------------------------------------------------------------------------------
  65. // Destructor, private as well
  66. Q3DImporter::~Q3DImporter() {
  67. // empty
  68. }
  69. // ------------------------------------------------------------------------------------------------
  70. // Returns whether the class can handle the format of the given file.
  71. bool Q3DImporter::CanRead(const std::string &pFile, IOSystem *pIOHandler, bool checkSig) const {
  72. const std::string extension = GetExtension(pFile);
  73. if (extension == "q3s" || extension == "q3o")
  74. return true;
  75. else if (!extension.length() || checkSig) {
  76. if (!pIOHandler)
  77. return true;
  78. const char *tokens[] = { "quick3Do", "quick3Ds" };
  79. return SearchFileHeaderForToken(pIOHandler, pFile, tokens, 2);
  80. }
  81. return false;
  82. }
  83. // ------------------------------------------------------------------------------------------------
  84. const aiImporterDesc *Q3DImporter::GetInfo() const {
  85. return &desc;
  86. }
  87. // ------------------------------------------------------------------------------------------------
  88. // Imports the given file into the given scene structure.
  89. void Q3DImporter::InternReadFile(const std::string &pFile,
  90. aiScene *pScene, IOSystem *pIOHandler) {
  91. StreamReaderLE stream(pIOHandler->Open(pFile, "rb"));
  92. // The header is 22 bytes large
  93. if (stream.GetRemainingSize() < 22)
  94. throw DeadlyImportError("File is either empty or corrupt: " + pFile);
  95. // Check the file's signature
  96. if (ASSIMP_strincmp((const char *)stream.GetPtr(), "quick3Do", 8) &&
  97. ASSIMP_strincmp((const char *)stream.GetPtr(), "quick3Ds", 8)) {
  98. throw DeadlyImportError("Not a Quick3D file. Signature string is: " +
  99. std::string((const char *)stream.GetPtr(), 8));
  100. }
  101. // Print the file format version
  102. ASSIMP_LOG_INFO_F("Quick3D File format version: ",
  103. std::string(&((const char *)stream.GetPtr())[8], 2));
  104. // ... an store it
  105. char major = ((const char *)stream.GetPtr())[8];
  106. char minor = ((const char *)stream.GetPtr())[9];
  107. stream.IncPtr(10);
  108. unsigned int numMeshes = (unsigned int)stream.GetI4();
  109. unsigned int numMats = (unsigned int)stream.GetI4();
  110. unsigned int numTextures = (unsigned int)stream.GetI4();
  111. std::vector<Material> materials;
  112. materials.reserve(numMats);
  113. std::vector<Mesh> meshes;
  114. meshes.reserve(numMeshes);
  115. // Allocate the scene root node
  116. pScene->mRootNode = new aiNode();
  117. aiColor3D fgColor(0.6f, 0.6f, 0.6f);
  118. // Now read all file chunks
  119. while (true) {
  120. if (stream.GetRemainingSize() < 1) break;
  121. char c = stream.GetI1();
  122. switch (c) {
  123. // Meshes chunk
  124. case 'm': {
  125. for (unsigned int quak = 0; quak < numMeshes; ++quak) {
  126. meshes.push_back(Mesh());
  127. Mesh &mesh = meshes.back();
  128. // read all vertices
  129. unsigned int numVerts = (unsigned int)stream.GetI4();
  130. if (!numVerts)
  131. throw DeadlyImportError("Quick3D: Found mesh with zero vertices");
  132. std::vector<aiVector3D> &verts = mesh.verts;
  133. verts.resize(numVerts);
  134. for (unsigned int i = 0; i < numVerts; ++i) {
  135. verts[i].x = stream.GetF4();
  136. verts[i].y = stream.GetF4();
  137. verts[i].z = stream.GetF4();
  138. }
  139. // read all faces
  140. numVerts = (unsigned int)stream.GetI4();
  141. if (!numVerts)
  142. throw DeadlyImportError("Quick3D: Found mesh with zero faces");
  143. std::vector<Face> &faces = mesh.faces;
  144. faces.reserve(numVerts);
  145. // number of indices
  146. for (unsigned int i = 0; i < numVerts; ++i) {
  147. faces.push_back(Face(stream.GetI2()));
  148. if (faces.back().indices.empty())
  149. throw DeadlyImportError("Quick3D: Found face with zero indices");
  150. }
  151. // indices
  152. for (unsigned int i = 0; i < numVerts; ++i) {
  153. Face &vec = faces[i];
  154. for (unsigned int a = 0; a < (unsigned int)vec.indices.size(); ++a)
  155. vec.indices[a] = stream.GetI4();
  156. }
  157. // material indices
  158. for (unsigned int i = 0; i < numVerts; ++i) {
  159. faces[i].mat = (unsigned int)stream.GetI4();
  160. }
  161. // read all normals
  162. numVerts = (unsigned int)stream.GetI4();
  163. std::vector<aiVector3D> &normals = mesh.normals;
  164. normals.resize(numVerts);
  165. for (unsigned int i = 0; i < numVerts; ++i) {
  166. normals[i].x = stream.GetF4();
  167. normals[i].y = stream.GetF4();
  168. normals[i].z = stream.GetF4();
  169. }
  170. numVerts = (unsigned int)stream.GetI4();
  171. if (numTextures && numVerts) {
  172. // read all texture coordinates
  173. std::vector<aiVector3D> &uv = mesh.uv;
  174. uv.resize(numVerts);
  175. for (unsigned int i = 0; i < numVerts; ++i) {
  176. uv[i].x = stream.GetF4();
  177. uv[i].y = stream.GetF4();
  178. }
  179. // UV indices
  180. for (unsigned int i = 0; i < (unsigned int)faces.size(); ++i) {
  181. Face &vec = faces[i];
  182. for (unsigned int a = 0; a < (unsigned int)vec.indices.size(); ++a) {
  183. vec.uvindices[a] = stream.GetI4();
  184. if (!i && !a)
  185. mesh.prevUVIdx = vec.uvindices[a];
  186. else if (vec.uvindices[a] != mesh.prevUVIdx)
  187. mesh.prevUVIdx = UINT_MAX;
  188. }
  189. }
  190. }
  191. // we don't need the rest, but we need to get to the next chunk
  192. stream.IncPtr(36);
  193. if (minor > '0' && major == '3')
  194. stream.IncPtr(mesh.faces.size());
  195. }
  196. // stream.IncPtr(4); // unknown value here
  197. } break;
  198. // materials chunk
  199. case 'c':
  200. for (unsigned int i = 0; i < numMats; ++i) {
  201. materials.push_back(Material());
  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. // unknown value here
  226. // stream.IncPtr(4);
  227. // FIX: it could be the texture index ...
  228. mat.texIdx = (unsigned int)stream.GetI4();
  229. }
  230. break;
  231. // texture chunk
  232. case 't':
  233. pScene->mNumTextures = numTextures;
  234. if (!numTextures) {
  235. break;
  236. }
  237. pScene->mTextures = new aiTexture *[pScene->mNumTextures];
  238. // to make sure we won't crash if we leave through an exception
  239. ::memset(pScene->mTextures, 0, sizeof(void *) * pScene->mNumTextures);
  240. for (unsigned int i = 0; i < pScene->mNumTextures; ++i) {
  241. aiTexture *tex = pScene->mTextures[i] = new aiTexture;
  242. // skip the texture name
  243. while (stream.GetI1())
  244. ;
  245. // read texture width and height
  246. tex->mWidth = (unsigned int)stream.GetI4();
  247. tex->mHeight = (unsigned int)stream.GetI4();
  248. if (!tex->mWidth || !tex->mHeight) {
  249. throw DeadlyImportError("Quick3D: Invalid texture. Width or height is zero");
  250. }
  251. unsigned int mul = tex->mWidth * tex->mHeight;
  252. aiTexel *begin = tex->pcData = new aiTexel[mul];
  253. aiTexel *const end = &begin[mul - 1] + 1;
  254. for (; begin != end; ++begin) {
  255. begin->r = stream.GetI1();
  256. begin->g = stream.GetI1();
  257. begin->b = stream.GetI1();
  258. begin->a = 0xff;
  259. }
  260. }
  261. break;
  262. // scene chunk
  263. case 's': {
  264. // skip position and rotation
  265. stream.IncPtr(12);
  266. for (unsigned int i = 0; i < 4; ++i)
  267. for (unsigned int a = 0; a < 4; ++a)
  268. pScene->mRootNode->mTransformation[i][a] = stream.GetF4();
  269. stream.IncPtr(16);
  270. // now setup a single camera
  271. pScene->mNumCameras = 1;
  272. pScene->mCameras = new aiCamera *[1];
  273. aiCamera *cam = pScene->mCameras[0] = new aiCamera();
  274. cam->mPosition.x = stream.GetF4();
  275. cam->mPosition.y = stream.GetF4();
  276. cam->mPosition.z = stream.GetF4();
  277. cam->mName.Set("Q3DCamera");
  278. // skip eye rotation for the moment
  279. stream.IncPtr(12);
  280. // read the default material color
  281. fgColor.r = stream.GetF4();
  282. fgColor.g = stream.GetF4();
  283. fgColor.b = stream.GetF4();
  284. // skip some unimportant properties
  285. stream.IncPtr(29);
  286. // setup a single point light with no attenuation
  287. pScene->mNumLights = 1;
  288. pScene->mLights = new aiLight *[1];
  289. aiLight *light = pScene->mLights[0] = new aiLight();
  290. light->mName.Set("Q3DLight");
  291. light->mType = aiLightSource_POINT;
  292. light->mAttenuationConstant = 1;
  293. light->mAttenuationLinear = 0;
  294. light->mAttenuationQuadratic = 0;
  295. light->mColorDiffuse.r = stream.GetF4();
  296. light->mColorDiffuse.g = stream.GetF4();
  297. light->mColorDiffuse.b = stream.GetF4();
  298. light->mColorSpecular = light->mColorDiffuse;
  299. // We don't need the rest, but we need to know where this chunk ends.
  300. unsigned int temp = (unsigned int)(stream.GetI4() * stream.GetI4());
  301. // skip the background file name
  302. while (stream.GetI1())
  303. ;
  304. // skip background texture data + the remaining fields
  305. stream.IncPtr(temp * 3 + 20); // 4 bytes of unknown data here
  306. // TODO
  307. goto outer;
  308. } break;
  309. default:
  310. throw DeadlyImportError("Quick3D: Unknown chunk");
  311. break;
  312. };
  313. }
  314. outer:
  315. // If we have no mesh loaded - break here
  316. if (meshes.empty())
  317. throw DeadlyImportError("Quick3D: No meshes loaded");
  318. // If we have no materials loaded - generate a default mat
  319. if (materials.empty()) {
  320. ASSIMP_LOG_INFO("Quick3D: No material found, generating one");
  321. materials.push_back(Material());
  322. materials.back().diffuse = fgColor;
  323. }
  324. // find out which materials we'll need
  325. typedef std::pair<unsigned int, unsigned int> FaceIdx;
  326. typedef std::vector<FaceIdx> FaceIdxArray;
  327. FaceIdxArray *fidx = new FaceIdxArray[materials.size()];
  328. unsigned int p = 0;
  329. for (std::vector<Mesh>::iterator it = meshes.begin(), end = meshes.end();
  330. it != end; ++it, ++p) {
  331. unsigned int q = 0;
  332. for (std::vector<Face>::iterator fit = (*it).faces.begin(), fend = (*it).faces.end();
  333. fit != fend; ++fit, ++q) {
  334. if ((*fit).mat >= materials.size()) {
  335. ASSIMP_LOG_WARN("Quick3D: Material index overflow");
  336. (*fit).mat = 0;
  337. }
  338. if (fidx[(*fit).mat].empty()) ++pScene->mNumMeshes;
  339. fidx[(*fit).mat].push_back(FaceIdx(p, q));
  340. }
  341. }
  342. pScene->mNumMaterials = pScene->mNumMeshes;
  343. pScene->mMaterials = new aiMaterial *[pScene->mNumMaterials];
  344. pScene->mMeshes = new aiMesh *[pScene->mNumMaterials];
  345. for (unsigned int i = 0, real = 0; i < (unsigned int)materials.size(); ++i) {
  346. if (fidx[i].empty()) continue;
  347. // Allocate a mesh and a material
  348. aiMesh *mesh = pScene->mMeshes[real] = new aiMesh();
  349. aiMaterial *mat = new aiMaterial();
  350. pScene->mMaterials[real] = mat;
  351. mesh->mMaterialIndex = real;
  352. // Build the output material
  353. Material &srcMat = materials[i];
  354. mat->AddProperty(&srcMat.diffuse, 1, AI_MATKEY_COLOR_DIFFUSE);
  355. mat->AddProperty(&srcMat.specular, 1, AI_MATKEY_COLOR_SPECULAR);
  356. mat->AddProperty(&srcMat.ambient, 1, AI_MATKEY_COLOR_AMBIENT);
  357. // NOTE: Ignore transparency for the moment - it seems
  358. // unclear how to interpret the data
  359. #if 0
  360. if (!(minor > '0' && major == '3'))
  361. srcMat.transparency = 1.0f - srcMat.transparency;
  362. mat->AddProperty(&srcMat.transparency, 1, AI_MATKEY_OPACITY);
  363. #endif
  364. // add shininess - Quick3D seems to use it ins its viewer
  365. srcMat.transparency = 16.f;
  366. mat->AddProperty(&srcMat.transparency, 1, AI_MATKEY_SHININESS);
  367. int m = (int)aiShadingMode_Phong;
  368. mat->AddProperty(&m, 1, AI_MATKEY_SHADING_MODEL);
  369. if (srcMat.name.length)
  370. mat->AddProperty(&srcMat.name, AI_MATKEY_NAME);
  371. // Add a texture
  372. if (srcMat.texIdx < pScene->mNumTextures || real < pScene->mNumTextures) {
  373. srcMat.name.data[0] = '*';
  374. srcMat.name.length = ASSIMP_itoa10(&srcMat.name.data[1], 1000,
  375. (srcMat.texIdx < pScene->mNumTextures ? srcMat.texIdx : real));
  376. mat->AddProperty(&srcMat.name, AI_MATKEY_TEXTURE_DIFFUSE(0));
  377. }
  378. mesh->mNumFaces = (unsigned int)fidx[i].size();
  379. aiFace *faces = mesh->mFaces = new aiFace[mesh->mNumFaces];
  380. // Now build the output mesh. First find out how many
  381. // vertices we'll need
  382. for (FaceIdxArray::const_iterator it = fidx[i].begin(), end = fidx[i].end();
  383. it != end; ++it) {
  384. mesh->mNumVertices += (unsigned int)meshes[(*it).first].faces[(*it).second].indices.size();
  385. }
  386. aiVector3D *verts = mesh->mVertices = new aiVector3D[mesh->mNumVertices];
  387. aiVector3D *norms = mesh->mNormals = new aiVector3D[mesh->mNumVertices];
  388. aiVector3D *uv = nullptr;
  389. if (real < pScene->mNumTextures) {
  390. uv = mesh->mTextureCoords[0] = new aiVector3D[mesh->mNumVertices];
  391. mesh->mNumUVComponents[0] = 2;
  392. }
  393. // Build the final array
  394. unsigned int cnt = 0;
  395. for (FaceIdxArray::const_iterator it = fidx[i].begin(), end = fidx[i].end();
  396. it != end; ++it, ++faces) {
  397. Mesh &curMesh = meshes[(*it).first];
  398. Face &face = curMesh.faces[(*it).second];
  399. faces->mNumIndices = (unsigned int)face.indices.size();
  400. faces->mIndices = new unsigned int[faces->mNumIndices];
  401. aiVector3D faceNormal;
  402. bool fnOK = false;
  403. for (unsigned int n = 0; n < faces->mNumIndices; ++n, ++cnt, ++norms, ++verts) {
  404. if (face.indices[n] >= curMesh.verts.size()) {
  405. ASSIMP_LOG_WARN("Quick3D: Vertex index overflow");
  406. face.indices[n] = 0;
  407. }
  408. // copy vertices
  409. *verts = curMesh.verts[face.indices[n]];
  410. if (face.indices[n] >= curMesh.normals.size() && faces->mNumIndices >= 3) {
  411. // we have no normal here - assign the face normal
  412. if (!fnOK) {
  413. const aiVector3D &pV1 = curMesh.verts[face.indices[0]];
  414. const aiVector3D &pV2 = curMesh.verts[face.indices[1]];
  415. const aiVector3D &pV3 = curMesh.verts[face.indices.size() - 1];
  416. faceNormal = (pV2 - pV1) ^ (pV3 - pV1).Normalize();
  417. fnOK = true;
  418. }
  419. *norms = faceNormal;
  420. } else {
  421. *norms = curMesh.normals[face.indices[n]];
  422. }
  423. // copy texture coordinates
  424. if (uv && curMesh.uv.size()) {
  425. if (curMesh.prevUVIdx != 0xffffffff && curMesh.uv.size() >= curMesh.verts.size()) // workaround
  426. {
  427. *uv = curMesh.uv[face.indices[n]];
  428. } else {
  429. if (face.uvindices[n] >= curMesh.uv.size()) {
  430. ASSIMP_LOG_WARN("Quick3D: Texture coordinate index overflow");
  431. face.uvindices[n] = 0;
  432. }
  433. *uv = curMesh.uv[face.uvindices[n]];
  434. }
  435. uv->y = 1.f - uv->y;
  436. ++uv;
  437. }
  438. // setup the new vertex index
  439. faces->mIndices[n] = cnt;
  440. }
  441. }
  442. ++real;
  443. }
  444. // Delete our nice helper array
  445. delete[] fidx;
  446. // Now we need to attach the meshes to the root node of the scene
  447. pScene->mRootNode->mNumMeshes = pScene->mNumMeshes;
  448. pScene->mRootNode->mMeshes = new unsigned int[pScene->mNumMeshes];
  449. for (unsigned int i = 0; i < pScene->mNumMeshes; ++i)
  450. pScene->mRootNode->mMeshes[i] = i;
  451. /*pScene->mRootNode->mTransformation *= aiMatrix4x4(
  452. 1.f, 0.f, 0.f, 0.f,
  453. 0.f, -1.f,0.f, 0.f,
  454. 0.f, 0.f, 1.f, 0.f,
  455. 0.f, 0.f, 0.f, 1.f);*/
  456. // Add cameras and light sources to the scene root node
  457. pScene->mRootNode->mNumChildren = pScene->mNumLights + pScene->mNumCameras;
  458. if (pScene->mRootNode->mNumChildren) {
  459. pScene->mRootNode->mChildren = new aiNode *[pScene->mRootNode->mNumChildren];
  460. // the light source
  461. aiNode *nd = pScene->mRootNode->mChildren[0] = new aiNode();
  462. nd->mParent = pScene->mRootNode;
  463. nd->mName.Set("Q3DLight");
  464. nd->mTransformation = pScene->mRootNode->mTransformation;
  465. nd->mTransformation.Inverse();
  466. // camera
  467. nd = pScene->mRootNode->mChildren[1] = new aiNode();
  468. nd->mParent = pScene->mRootNode;
  469. nd->mName.Set("Q3DCamera");
  470. nd->mTransformation = pScene->mRootNode->mChildren[0]->mTransformation;
  471. }
  472. }
  473. #endif // !! ASSIMP_BUILD_NO_Q3D_IMPORTER