2
0

ACLoader.cpp 36 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874
  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 Implementation of the AC3D importer class */
  35. #ifndef ASSIMP_BUILD_NO_AC_IMPORTER
  36. // internal headers
  37. #include "ACLoader.h"
  38. #include "Common/Importer.h"
  39. #include <assimp/BaseImporter.h>
  40. #include <assimp/ParsingUtils.h>
  41. #include <assimp/Subdivision.h>
  42. #include <assimp/config.h>
  43. #include <assimp/fast_atof.h>
  44. #include <assimp/importerdesc.h>
  45. #include <assimp/light.h>
  46. #include <assimp/material.h>
  47. #include <assimp/scene.h>
  48. #include <assimp/DefaultLogger.hpp>
  49. #include <assimp/IOSystem.hpp>
  50. #include <assimp/Importer.hpp>
  51. #include <memory>
  52. using namespace Assimp;
  53. static const aiImporterDesc desc = {
  54. "AC3D Importer",
  55. "",
  56. "",
  57. "",
  58. aiImporterFlags_SupportTextFlavour,
  59. 0,
  60. 0,
  61. 0,
  62. 0,
  63. "ac acc ac3d"
  64. };
  65. // ------------------------------------------------------------------------------------------------
  66. // skip to the next token
  67. inline const char *AcSkipToNextToken(const char *buffer) {
  68. if (!SkipSpaces(&buffer)) {
  69. ASSIMP_LOG_ERROR("AC3D: Unexpected EOF/EOL");
  70. }
  71. return buffer;
  72. }
  73. // ------------------------------------------------------------------------------------------------
  74. // read a string (may be enclosed in double quotation marks). buffer must point to "
  75. inline const char *AcGetString(const char *buffer, std::string &out) {
  76. if (*buffer == '\0') {
  77. throw DeadlyImportError("AC3D: Unexpected EOF in string");
  78. }
  79. ++buffer;
  80. const char *sz = buffer;
  81. while ('\"' != *buffer) {
  82. if (IsLineEnd(*buffer)) {
  83. ASSIMP_LOG_ERROR("AC3D: Unexpected EOF/EOL in string");
  84. out = "ERROR";
  85. break;
  86. }
  87. ++buffer;
  88. }
  89. if (IsLineEnd(*buffer)) {
  90. return buffer;
  91. }
  92. out = std::string(sz, (unsigned int)(buffer - sz));
  93. ++buffer;
  94. return buffer;
  95. }
  96. // ------------------------------------------------------------------------------------------------
  97. // read 1 to n floats prefixed with an optional predefined identifier
  98. template <class T>
  99. inline const char *TAcCheckedLoadFloatArray(const char *buffer, const char *name, size_t name_length, size_t num, T *out) {
  100. buffer = AcSkipToNextToken(buffer);
  101. if (0 != name_length) {
  102. if (0 != strncmp(buffer, name, name_length) || !IsSpace(buffer[name_length])) {
  103. ASSIMP_LOG_ERROR("AC3D: Unexpexted token. " + std::string(name) + " was expected.");
  104. return buffer;
  105. }
  106. buffer += name_length + 1;
  107. }
  108. for (unsigned int _i = 0; _i < num; ++_i) {
  109. buffer = AcSkipToNextToken(buffer);
  110. buffer = fast_atoreal_move<float>(buffer, ((float *)out)[_i]);
  111. }
  112. return buffer;
  113. }
  114. // ------------------------------------------------------------------------------------------------
  115. // Constructor to be privately used by Importer
  116. AC3DImporter::AC3DImporter() :
  117. buffer(),
  118. configSplitBFCull(),
  119. configEvalSubdivision(),
  120. mNumMeshes(),
  121. mLights(),
  122. mLightsCounter(0),
  123. mGroupsCounter(0),
  124. mPolysCounter(0),
  125. mWorldsCounter(0) {
  126. // nothing to be done here
  127. }
  128. // ------------------------------------------------------------------------------------------------
  129. // Destructor, private as well
  130. AC3DImporter::~AC3DImporter() {
  131. // nothing to be done here
  132. }
  133. // ------------------------------------------------------------------------------------------------
  134. // Returns whether the class can handle the format of the given file.
  135. bool AC3DImporter::CanRead(const std::string &pFile, IOSystem *pIOHandler, bool checkSig) const {
  136. std::string extension = GetExtension(pFile);
  137. // fixme: are acc and ac3d *really* used? Some sources say they are
  138. if (extension == "ac" || extension == "ac3d" || extension == "acc") {
  139. return true;
  140. }
  141. if (!extension.length() || checkSig) {
  142. uint32_t token = AI_MAKE_MAGIC("AC3D");
  143. return CheckMagicToken(pIOHandler, pFile, &token, 1, 0);
  144. }
  145. return false;
  146. }
  147. // ------------------------------------------------------------------------------------------------
  148. // Loader meta information
  149. const aiImporterDesc *AC3DImporter::GetInfo() const {
  150. return &desc;
  151. }
  152. // ------------------------------------------------------------------------------------------------
  153. // Get a pointer to the next line from the file
  154. bool AC3DImporter::GetNextLine() {
  155. SkipLine(&buffer);
  156. return SkipSpaces(&buffer);
  157. }
  158. // ------------------------------------------------------------------------------------------------
  159. // Parse an object section in an AC file
  160. void AC3DImporter::LoadObjectSection(std::vector<Object> &objects) {
  161. if (!TokenMatch(buffer, "OBJECT", 6))
  162. return;
  163. SkipSpaces(&buffer);
  164. ++mNumMeshes;
  165. objects.push_back(Object());
  166. Object &obj = objects.back();
  167. aiLight *light = nullptr;
  168. if (!ASSIMP_strincmp(buffer, "light", 5)) {
  169. // This is a light source. Add it to the list
  170. mLights->push_back(light = new aiLight());
  171. // Return a point light with no attenuation
  172. light->mType = aiLightSource_POINT;
  173. light->mColorDiffuse = light->mColorSpecular = aiColor3D(1.f, 1.f, 1.f);
  174. light->mAttenuationConstant = 1.f;
  175. // Generate a default name for both the light source and the node
  176. // FIXME - what's the right way to print a size_t? Is 'zu' universally available? stick with the safe version.
  177. light->mName.length = ::ai_snprintf(light->mName.data, MAXLEN, "ACLight_%i", static_cast<unsigned int>(mLights->size()) - 1);
  178. obj.name = std::string(light->mName.data);
  179. ASSIMP_LOG_VERBOSE_DEBUG("AC3D: Light source encountered");
  180. obj.type = Object::Light;
  181. } else if (!ASSIMP_strincmp(buffer, "group", 5)) {
  182. obj.type = Object::Group;
  183. } else if (!ASSIMP_strincmp(buffer, "world", 5)) {
  184. obj.type = Object::World;
  185. } else
  186. obj.type = Object::Poly;
  187. while (GetNextLine()) {
  188. if (TokenMatch(buffer, "kids", 4)) {
  189. SkipSpaces(&buffer);
  190. unsigned int num = strtoul10(buffer, &buffer);
  191. GetNextLine();
  192. if (num) {
  193. // load the children of this object recursively
  194. obj.children.reserve(num);
  195. for (unsigned int i = 0; i < num; ++i)
  196. LoadObjectSection(obj.children);
  197. }
  198. return;
  199. } else if (TokenMatch(buffer, "name", 4)) {
  200. SkipSpaces(&buffer);
  201. buffer = AcGetString(buffer, obj.name);
  202. // If this is a light source, we'll also need to store
  203. // the name of the node in it.
  204. if (light) {
  205. light->mName.Set(obj.name);
  206. }
  207. } else if (TokenMatch(buffer, "texture", 7)) {
  208. SkipSpaces(&buffer);
  209. buffer = AcGetString(buffer, obj.texture);
  210. } else if (TokenMatch(buffer, "texrep", 6)) {
  211. SkipSpaces(&buffer);
  212. buffer = TAcCheckedLoadFloatArray(buffer, "", 0, 2, &obj.texRepeat);
  213. if (!obj.texRepeat.x || !obj.texRepeat.y)
  214. obj.texRepeat = aiVector2D(1.f, 1.f);
  215. } else if (TokenMatch(buffer, "texoff", 6)) {
  216. SkipSpaces(&buffer);
  217. buffer = TAcCheckedLoadFloatArray(buffer, "", 0, 2, &obj.texOffset);
  218. } else if (TokenMatch(buffer, "rot", 3)) {
  219. SkipSpaces(&buffer);
  220. buffer = TAcCheckedLoadFloatArray(buffer, "", 0, 9, &obj.rotation);
  221. } else if (TokenMatch(buffer, "loc", 3)) {
  222. SkipSpaces(&buffer);
  223. buffer = TAcCheckedLoadFloatArray(buffer, "", 0, 3, &obj.translation);
  224. } else if (TokenMatch(buffer, "subdiv", 6)) {
  225. SkipSpaces(&buffer);
  226. obj.subDiv = strtoul10(buffer, &buffer);
  227. } else if (TokenMatch(buffer, "crease", 6)) {
  228. SkipSpaces(&buffer);
  229. obj.crease = fast_atof(buffer);
  230. } else if (TokenMatch(buffer, "numvert", 7)) {
  231. SkipSpaces(&buffer);
  232. unsigned int t = strtoul10(buffer, &buffer);
  233. if (t >= AI_MAX_ALLOC(aiVector3D)) {
  234. throw DeadlyImportError("AC3D: Too many vertices, would run out of memory");
  235. }
  236. obj.vertices.reserve(t);
  237. for (unsigned int i = 0; i < t; ++i) {
  238. if (!GetNextLine()) {
  239. ASSIMP_LOG_ERROR("AC3D: Unexpected EOF: not all vertices have been parsed yet");
  240. break;
  241. } else if (!IsNumeric(*buffer)) {
  242. ASSIMP_LOG_ERROR("AC3D: Unexpected token: not all vertices have been parsed yet");
  243. --buffer; // make sure the line is processed a second time
  244. break;
  245. }
  246. obj.vertices.push_back(aiVector3D());
  247. aiVector3D &v = obj.vertices.back();
  248. buffer = TAcCheckedLoadFloatArray(buffer, "", 0, 3, &v.x);
  249. }
  250. } else if (TokenMatch(buffer, "numsurf", 7)) {
  251. SkipSpaces(&buffer);
  252. bool Q3DWorkAround = false;
  253. const unsigned int t = strtoul10(buffer, &buffer);
  254. obj.surfaces.reserve(t);
  255. for (unsigned int i = 0; i < t; ++i) {
  256. GetNextLine();
  257. if (!TokenMatch(buffer, "SURF", 4)) {
  258. // FIX: this can occur for some files - Quick 3D for
  259. // example writes no surf chunks
  260. if (!Q3DWorkAround) {
  261. ASSIMP_LOG_WARN("AC3D: SURF token was expected");
  262. ASSIMP_LOG_VERBOSE_DEBUG("Continuing with Quick3D Workaround enabled");
  263. }
  264. --buffer; // make sure the line is processed a second time
  265. // break; --- see fix notes above
  266. Q3DWorkAround = true;
  267. }
  268. SkipSpaces(&buffer);
  269. obj.surfaces.push_back(Surface());
  270. Surface &surf = obj.surfaces.back();
  271. surf.flags = strtoul_cppstyle(buffer);
  272. while (1) {
  273. if (!GetNextLine()) {
  274. throw DeadlyImportError("AC3D: Unexpected EOF: surface is incomplete");
  275. }
  276. if (TokenMatch(buffer, "mat", 3)) {
  277. SkipSpaces(&buffer);
  278. surf.mat = strtoul10(buffer);
  279. } else if (TokenMatch(buffer, "refs", 4)) {
  280. // --- see fix notes above
  281. if (Q3DWorkAround) {
  282. if (!surf.entries.empty()) {
  283. buffer -= 6;
  284. break;
  285. }
  286. }
  287. SkipSpaces(&buffer);
  288. const unsigned int m = strtoul10(buffer);
  289. surf.entries.reserve(m);
  290. obj.numRefs += m;
  291. for (unsigned int k = 0; k < m; ++k) {
  292. if (!GetNextLine()) {
  293. ASSIMP_LOG_ERROR("AC3D: Unexpected EOF: surface references are incomplete");
  294. break;
  295. }
  296. surf.entries.push_back(Surface::SurfaceEntry());
  297. Surface::SurfaceEntry &entry = surf.entries.back();
  298. entry.first = strtoul10(buffer, &buffer);
  299. SkipSpaces(&buffer);
  300. buffer = TAcCheckedLoadFloatArray(buffer, "", 0, 2, &entry.second);
  301. }
  302. } else {
  303. --buffer; // make sure the line is processed a second time
  304. break;
  305. }
  306. }
  307. }
  308. }
  309. }
  310. ASSIMP_LOG_ERROR("AC3D: Unexpected EOF: \'kids\' line was expected");
  311. }
  312. // ------------------------------------------------------------------------------------------------
  313. // Convert a material from AC3DImporter::Material to aiMaterial
  314. void AC3DImporter::ConvertMaterial(const Object &object,
  315. const Material &matSrc,
  316. aiMaterial &matDest) {
  317. aiString s;
  318. if (matSrc.name.length()) {
  319. s.Set(matSrc.name);
  320. matDest.AddProperty(&s, AI_MATKEY_NAME);
  321. }
  322. if (object.texture.length()) {
  323. s.Set(object.texture);
  324. matDest.AddProperty(&s, AI_MATKEY_TEXTURE_DIFFUSE(0));
  325. // UV transformation
  326. if (1.f != object.texRepeat.x || 1.f != object.texRepeat.y ||
  327. object.texOffset.x || object.texOffset.y) {
  328. aiUVTransform transform;
  329. transform.mScaling = object.texRepeat;
  330. transform.mTranslation = object.texOffset;
  331. matDest.AddProperty(&transform, 1, AI_MATKEY_UVTRANSFORM_DIFFUSE(0));
  332. }
  333. }
  334. matDest.AddProperty<aiColor3D>(&matSrc.rgb, 1, AI_MATKEY_COLOR_DIFFUSE);
  335. matDest.AddProperty<aiColor3D>(&matSrc.amb, 1, AI_MATKEY_COLOR_AMBIENT);
  336. matDest.AddProperty<aiColor3D>(&matSrc.emis, 1, AI_MATKEY_COLOR_EMISSIVE);
  337. matDest.AddProperty<aiColor3D>(&matSrc.spec, 1, AI_MATKEY_COLOR_SPECULAR);
  338. int n = -1;
  339. if (matSrc.shin) {
  340. n = aiShadingMode_Phong;
  341. matDest.AddProperty<float>(&matSrc.shin, 1, AI_MATKEY_SHININESS);
  342. } else {
  343. n = aiShadingMode_Gouraud;
  344. }
  345. matDest.AddProperty<int>(&n, 1, AI_MATKEY_SHADING_MODEL);
  346. float f = 1.f - matSrc.trans;
  347. matDest.AddProperty<float>(&f, 1, AI_MATKEY_OPACITY);
  348. }
  349. // ------------------------------------------------------------------------------------------------
  350. // Converts the loaded data to the internal verbose representation
  351. aiNode *AC3DImporter::ConvertObjectSection(Object &object,
  352. std::vector<aiMesh *> &meshes,
  353. std::vector<aiMaterial *> &outMaterials,
  354. const std::vector<Material> &materials,
  355. aiNode *parent) {
  356. aiNode *node = new aiNode();
  357. node->mParent = parent;
  358. if (object.vertices.size()) {
  359. if (!object.surfaces.size() || !object.numRefs) {
  360. /* " An object with 7 vertices (no surfaces, no materials defined).
  361. This is a good way of getting point data into AC3D.
  362. The Vertex->create convex-surface/object can be used on these
  363. vertices to 'wrap' a 3d shape around them "
  364. (http://www.opencity.info/html/ac3dfileformat.html)
  365. therefore: if no surfaces are defined return point data only
  366. */
  367. ASSIMP_LOG_INFO("AC3D: No surfaces defined in object definition, "
  368. "a point list is returned");
  369. meshes.push_back(new aiMesh());
  370. aiMesh *mesh = meshes.back();
  371. mesh->mNumFaces = mesh->mNumVertices = (unsigned int)object.vertices.size();
  372. aiFace *faces = mesh->mFaces = new aiFace[mesh->mNumFaces];
  373. aiVector3D *verts = mesh->mVertices = new aiVector3D[mesh->mNumVertices];
  374. for (unsigned int i = 0; i < mesh->mNumVertices; ++i, ++faces, ++verts) {
  375. *verts = object.vertices[i];
  376. faces->mNumIndices = 1;
  377. faces->mIndices = new unsigned int[1];
  378. faces->mIndices[0] = i;
  379. }
  380. // use the primary material in this case. this should be the
  381. // default material if all objects of the file contain points
  382. // and no faces.
  383. mesh->mMaterialIndex = 0;
  384. outMaterials.push_back(new aiMaterial());
  385. ConvertMaterial(object, materials[0], *outMaterials.back());
  386. } else {
  387. // need to generate one or more meshes for this object.
  388. // find out how many different materials we have
  389. typedef std::pair<unsigned int, unsigned int> IntPair;
  390. typedef std::vector<IntPair> MatTable;
  391. MatTable needMat(materials.size(), IntPair(0, 0));
  392. std::vector<Surface>::iterator it, end = object.surfaces.end();
  393. std::vector<Surface::SurfaceEntry>::iterator it2, end2;
  394. for (it = object.surfaces.begin(); it != end; ++it) {
  395. unsigned int idx = (*it).mat;
  396. if (idx >= needMat.size()) {
  397. ASSIMP_LOG_ERROR("AC3D: material index is out of range");
  398. idx = 0;
  399. }
  400. if ((*it).entries.empty()) {
  401. ASSIMP_LOG_WARN("AC3D: surface her zero vertex references");
  402. }
  403. // validate all vertex indices to make sure we won't crash here
  404. for (it2 = (*it).entries.begin(),
  405. end2 = (*it).entries.end();
  406. it2 != end2; ++it2) {
  407. if ((*it2).first >= object.vertices.size()) {
  408. ASSIMP_LOG_WARN("AC3D: Invalid vertex reference");
  409. (*it2).first = 0;
  410. }
  411. }
  412. if (!needMat[idx].first) {
  413. ++node->mNumMeshes;
  414. }
  415. switch ((*it).GetType()) {
  416. // closed line
  417. case Surface::ClosedLine:
  418. needMat[idx].first += (unsigned int)(*it).entries.size();
  419. needMat[idx].second += (unsigned int)(*it).entries.size() << 1u;
  420. break;
  421. // unclosed line
  422. case Surface::OpenLine:
  423. needMat[idx].first += (unsigned int)(*it).entries.size() - 1;
  424. needMat[idx].second += ((unsigned int)(*it).entries.size() - 1) << 1u;
  425. break;
  426. // triangle strip
  427. case Surface::TriangleStrip:
  428. needMat[idx].first += (unsigned int)(*it).entries.size() - 2;
  429. needMat[idx].second += ((unsigned int)(*it).entries.size() - 2) * 3;
  430. break;
  431. default:
  432. // Coerce unknowns to a polygon and warn
  433. ASSIMP_LOG_WARN_F("AC3D: The type flag of a surface is unknown: ", (*it).flags);
  434. (*it).flags &= ~(Surface::Mask);
  435. // fallthrough
  436. // polygon
  437. case Surface::Polygon:
  438. // the number of faces increments by one, the number
  439. // of vertices by surface.numref.
  440. needMat[idx].first++;
  441. needMat[idx].second += (unsigned int)(*it).entries.size();
  442. };
  443. }
  444. unsigned int *pip = node->mMeshes = new unsigned int[node->mNumMeshes];
  445. unsigned int mat = 0;
  446. const size_t oldm = meshes.size();
  447. for (MatTable::const_iterator cit = needMat.begin(), cend = needMat.end();
  448. cit != cend; ++cit, ++mat) {
  449. if (!(*cit).first) {
  450. continue;
  451. }
  452. // allocate a new aiMesh object
  453. *pip++ = (unsigned int)meshes.size();
  454. aiMesh *mesh = new aiMesh();
  455. meshes.push_back(mesh);
  456. mesh->mMaterialIndex = static_cast<unsigned int>(outMaterials.size());
  457. outMaterials.push_back(new aiMaterial());
  458. ConvertMaterial(object, materials[mat], *outMaterials.back());
  459. // allocate storage for vertices and normals
  460. mesh->mNumFaces = (*cit).first;
  461. if (mesh->mNumFaces == 0) {
  462. throw DeadlyImportError("AC3D: No faces");
  463. } else if (mesh->mNumFaces > AI_MAX_ALLOC(aiFace)) {
  464. throw DeadlyImportError("AC3D: Too many faces, would run out of memory");
  465. }
  466. aiFace *faces = mesh->mFaces = new aiFace[mesh->mNumFaces];
  467. mesh->mNumVertices = (*cit).second;
  468. if (mesh->mNumVertices == 0) {
  469. throw DeadlyImportError("AC3D: No vertices");
  470. } else if (mesh->mNumVertices > AI_MAX_ALLOC(aiVector3D)) {
  471. throw DeadlyImportError("AC3D: Too many vertices, would run out of memory");
  472. }
  473. aiVector3D *vertices = mesh->mVertices = new aiVector3D[mesh->mNumVertices];
  474. unsigned int cur = 0;
  475. // allocate UV coordinates, but only if the texture name for the
  476. // surface is not empty
  477. aiVector3D *uv = nullptr;
  478. if (object.texture.length()) {
  479. uv = mesh->mTextureCoords[0] = new aiVector3D[mesh->mNumVertices];
  480. mesh->mNumUVComponents[0] = 2;
  481. }
  482. for (it = object.surfaces.begin(); it != end; ++it) {
  483. if (mat == (*it).mat) {
  484. const Surface &src = *it;
  485. // closed polygon
  486. uint8_t type = (*it).GetType();
  487. if (type == Surface::Polygon) {
  488. aiFace &face = *faces++;
  489. face.mNumIndices = (unsigned int)src.entries.size();
  490. if (0 != face.mNumIndices) {
  491. face.mIndices = new unsigned int[face.mNumIndices];
  492. for (unsigned int i = 0; i < face.mNumIndices; ++i, ++vertices) {
  493. const Surface::SurfaceEntry &entry = src.entries[i];
  494. face.mIndices[i] = cur++;
  495. // copy vertex positions
  496. if (static_cast<unsigned>(vertices - mesh->mVertices) >= mesh->mNumVertices) {
  497. throw DeadlyImportError("AC3D: Invalid number of vertices");
  498. }
  499. *vertices = object.vertices[entry.first] + object.translation;
  500. // copy texture coordinates
  501. if (uv) {
  502. uv->x = entry.second.x;
  503. uv->y = entry.second.y;
  504. ++uv;
  505. }
  506. }
  507. }
  508. } else if (type == Surface::TriangleStrip) {
  509. for (unsigned int i = 0; i < (unsigned int)src.entries.size() - 2; ++i) {
  510. const Surface::SurfaceEntry &entry1 = src.entries[i];
  511. const Surface::SurfaceEntry &entry2 = src.entries[i + 1];
  512. const Surface::SurfaceEntry &entry3 = src.entries[i + 2];
  513. // skip degenerate triangles
  514. if (object.vertices[entry1.first] == object.vertices[entry2.first] ||
  515. object.vertices[entry1.first] == object.vertices[entry3.first] ||
  516. object.vertices[entry2.first] == object.vertices[entry3.first]) {
  517. mesh->mNumFaces--;
  518. mesh->mNumVertices -= 3;
  519. continue;
  520. }
  521. aiFace &face = *faces++;
  522. face.mNumIndices = 3;
  523. face.mIndices = new unsigned int[face.mNumIndices];
  524. face.mIndices[0] = cur++;
  525. face.mIndices[1] = cur++;
  526. face.mIndices[2] = cur++;
  527. if (!(i & 1)) {
  528. *vertices++ = object.vertices[entry1.first] + object.translation;
  529. if (uv) {
  530. uv->x = entry1.second.x;
  531. uv->y = entry1.second.y;
  532. ++uv;
  533. }
  534. *vertices++ = object.vertices[entry2.first] + object.translation;
  535. if (uv) {
  536. uv->x = entry2.second.x;
  537. uv->y = entry2.second.y;
  538. ++uv;
  539. }
  540. } else {
  541. *vertices++ = object.vertices[entry2.first] + object.translation;
  542. if (uv) {
  543. uv->x = entry2.second.x;
  544. uv->y = entry2.second.y;
  545. ++uv;
  546. }
  547. *vertices++ = object.vertices[entry1.first] + object.translation;
  548. if (uv) {
  549. uv->x = entry1.second.x;
  550. uv->y = entry1.second.y;
  551. ++uv;
  552. }
  553. }
  554. if (static_cast<unsigned>(vertices - mesh->mVertices) >= mesh->mNumVertices) {
  555. throw DeadlyImportError("AC3D: Invalid number of vertices");
  556. }
  557. *vertices++ = object.vertices[entry3.first] + object.translation;
  558. if (uv) {
  559. uv->x = entry3.second.x;
  560. uv->y = entry3.second.y;
  561. ++uv;
  562. }
  563. }
  564. } else {
  565. it2 = (*it).entries.begin();
  566. // either a closed or an unclosed line
  567. unsigned int tmp = (unsigned int)(*it).entries.size();
  568. if (Surface::OpenLine == type) --tmp;
  569. for (unsigned int m = 0; m < tmp; ++m) {
  570. aiFace &face = *faces++;
  571. face.mNumIndices = 2;
  572. face.mIndices = new unsigned int[2];
  573. face.mIndices[0] = cur++;
  574. face.mIndices[1] = cur++;
  575. // copy vertex positions
  576. if (it2 == (*it).entries.end()) {
  577. throw DeadlyImportError("AC3D: Bad line");
  578. }
  579. ai_assert((*it2).first < object.vertices.size());
  580. *vertices++ = object.vertices[(*it2).first];
  581. // copy texture coordinates
  582. if (uv) {
  583. uv->x = (*it2).second.x;
  584. uv->y = (*it2).second.y;
  585. ++uv;
  586. }
  587. if (Surface::ClosedLine == type && tmp - 1 == m) {
  588. // if this is a closed line repeat its beginning now
  589. it2 = (*it).entries.begin();
  590. } else
  591. ++it2;
  592. // second point
  593. *vertices++ = object.vertices[(*it2).first];
  594. if (uv) {
  595. uv->x = (*it2).second.x;
  596. uv->y = (*it2).second.y;
  597. ++uv;
  598. }
  599. }
  600. }
  601. }
  602. }
  603. }
  604. // Now apply catmull clark subdivision if necessary. We split meshes into
  605. // materials which is not done by AC3D during smoothing, so we need to
  606. // collect all meshes using the same material group.
  607. if (object.subDiv) {
  608. if (configEvalSubdivision) {
  609. std::unique_ptr<Subdivider> div(Subdivider::Create(Subdivider::CATMULL_CLARKE));
  610. ASSIMP_LOG_INFO("AC3D: Evaluating subdivision surface: " + object.name);
  611. std::vector<aiMesh *> cpy(meshes.size() - oldm, nullptr);
  612. div->Subdivide(&meshes[oldm], cpy.size(), &cpy.front(), object.subDiv, true);
  613. std::copy(cpy.begin(), cpy.end(), meshes.begin() + oldm);
  614. // previous meshes are deleted vy Subdivide().
  615. } else {
  616. ASSIMP_LOG_INFO("AC3D: Letting the subdivision surface untouched due to my configuration: " + object.name);
  617. }
  618. }
  619. }
  620. }
  621. if (object.name.length())
  622. node->mName.Set(object.name);
  623. else {
  624. // generate a name depending on the type of the node
  625. switch (object.type) {
  626. case Object::Group:
  627. node->mName.length = ::ai_snprintf(node->mName.data, MAXLEN, "ACGroup_%i", mGroupsCounter++);
  628. break;
  629. case Object::Poly:
  630. node->mName.length = ::ai_snprintf(node->mName.data, MAXLEN, "ACPoly_%i", mPolysCounter++);
  631. break;
  632. case Object::Light:
  633. node->mName.length = ::ai_snprintf(node->mName.data, MAXLEN, "ACLight_%i", mLightsCounter++);
  634. break;
  635. // there shouldn't be more than one world, but we don't care
  636. case Object::World:
  637. node->mName.length = ::ai_snprintf(node->mName.data, MAXLEN, "ACWorld_%i", mWorldsCounter++);
  638. break;
  639. }
  640. }
  641. // setup the local transformation matrix of the object
  642. // compute the transformation offset to the parent node
  643. node->mTransformation = aiMatrix4x4(object.rotation);
  644. if (object.type == Object::Group || !object.numRefs) {
  645. node->mTransformation.a4 = object.translation.x;
  646. node->mTransformation.b4 = object.translation.y;
  647. node->mTransformation.c4 = object.translation.z;
  648. }
  649. // add children to the object
  650. if (object.children.size()) {
  651. node->mNumChildren = (unsigned int)object.children.size();
  652. node->mChildren = new aiNode *[node->mNumChildren];
  653. for (unsigned int i = 0; i < node->mNumChildren; ++i) {
  654. node->mChildren[i] = ConvertObjectSection(object.children[i], meshes, outMaterials, materials, node);
  655. }
  656. }
  657. return node;
  658. }
  659. // ------------------------------------------------------------------------------------------------
  660. void AC3DImporter::SetupProperties(const Importer *pImp) {
  661. configSplitBFCull = pImp->GetPropertyInteger(AI_CONFIG_IMPORT_AC_SEPARATE_BFCULL, 1) ? true : false;
  662. configEvalSubdivision = pImp->GetPropertyInteger(AI_CONFIG_IMPORT_AC_EVAL_SUBDIVISION, 1) ? true : false;
  663. }
  664. // ------------------------------------------------------------------------------------------------
  665. // Imports the given file into the given scene structure.
  666. void AC3DImporter::InternReadFile(const std::string &pFile,
  667. aiScene *pScene, IOSystem *pIOHandler) {
  668. std::unique_ptr<IOStream> file(pIOHandler->Open(pFile, "rb"));
  669. // Check whether we can read from the file
  670. if (file.get() == nullptr) {
  671. throw DeadlyImportError("Failed to open AC3D file " + pFile + ".");
  672. }
  673. // allocate storage and copy the contents of the file to a memory buffer
  674. std::vector<char> mBuffer2;
  675. TextFileToBuffer(file.get(), mBuffer2);
  676. buffer = &mBuffer2[0];
  677. mNumMeshes = 0;
  678. mLightsCounter = mPolysCounter = mWorldsCounter = mGroupsCounter = 0;
  679. if (::strncmp(buffer, "AC3D", 4)) {
  680. throw DeadlyImportError("AC3D: No valid AC3D file, magic sequence not found");
  681. }
  682. // print the file format version to the console
  683. unsigned int version = HexDigitToDecimal(buffer[4]);
  684. char msg[3];
  685. ASSIMP_itoa10(msg, 3, version);
  686. ASSIMP_LOG_INFO_F("AC3D file format version: ", msg);
  687. std::vector<Material> materials;
  688. materials.reserve(5);
  689. std::vector<Object> rootObjects;
  690. rootObjects.reserve(5);
  691. std::vector<aiLight *> lights;
  692. mLights = &lights;
  693. while (GetNextLine()) {
  694. if (TokenMatch(buffer, "MATERIAL", 8)) {
  695. materials.push_back(Material());
  696. Material &mat = materials.back();
  697. // manually parse the material ... sscanf would use the buldin atof ...
  698. // Format: (name) rgb %f %f %f amb %f %f %f emis %f %f %f spec %f %f %f shi %d trans %f
  699. buffer = AcSkipToNextToken(buffer);
  700. if ('\"' == *buffer) {
  701. buffer = AcGetString(buffer, mat.name);
  702. buffer = AcSkipToNextToken(buffer);
  703. }
  704. buffer = TAcCheckedLoadFloatArray(buffer, "rgb", 3, 3, &mat.rgb);
  705. buffer = TAcCheckedLoadFloatArray(buffer, "amb", 3, 3, &mat.amb);
  706. buffer = TAcCheckedLoadFloatArray(buffer, "emis", 4, 3, &mat.emis);
  707. buffer = TAcCheckedLoadFloatArray(buffer, "spec", 4, 3, &mat.spec);
  708. buffer = TAcCheckedLoadFloatArray(buffer, "shi", 3, 1, &mat.shin);
  709. buffer = TAcCheckedLoadFloatArray(buffer, "trans", 5, 1, &mat.trans);
  710. }
  711. LoadObjectSection(rootObjects);
  712. }
  713. if (rootObjects.empty() || !mNumMeshes) {
  714. throw DeadlyImportError("AC3D: No meshes have been loaded");
  715. }
  716. if (materials.empty()) {
  717. ASSIMP_LOG_WARN("AC3D: No material has been found");
  718. materials.push_back(Material());
  719. }
  720. mNumMeshes += (mNumMeshes >> 2u) + 1;
  721. std::vector<aiMesh *> meshes;
  722. meshes.reserve(mNumMeshes);
  723. std::vector<aiMaterial *> omaterials;
  724. materials.reserve(mNumMeshes);
  725. // generate a dummy root if there are multiple objects on the top layer
  726. Object *root;
  727. if (1 == rootObjects.size())
  728. root = &rootObjects[0];
  729. else {
  730. root = new Object();
  731. }
  732. // now convert the imported stuff to our output data structure
  733. pScene->mRootNode = ConvertObjectSection(*root, meshes, omaterials, materials);
  734. if (1 != rootObjects.size()) {
  735. delete root;
  736. }
  737. if (!::strncmp(pScene->mRootNode->mName.data, "Node", 4)) {
  738. pScene->mRootNode->mName.Set("<AC3DWorld>");
  739. }
  740. // copy meshes
  741. if (meshes.empty()) {
  742. throw DeadlyImportError("An unknown error occurred during converting");
  743. }
  744. pScene->mNumMeshes = (unsigned int)meshes.size();
  745. pScene->mMeshes = new aiMesh *[pScene->mNumMeshes];
  746. ::memcpy(pScene->mMeshes, &meshes[0], pScene->mNumMeshes * sizeof(void *));
  747. // copy materials
  748. pScene->mNumMaterials = (unsigned int)omaterials.size();
  749. pScene->mMaterials = new aiMaterial *[pScene->mNumMaterials];
  750. ::memcpy(pScene->mMaterials, &omaterials[0], pScene->mNumMaterials * sizeof(void *));
  751. // copy lights
  752. pScene->mNumLights = (unsigned int)lights.size();
  753. if (lights.size()) {
  754. pScene->mLights = new aiLight *[lights.size()];
  755. ::memcpy(pScene->mLights, &lights[0], lights.size() * sizeof(void *));
  756. }
  757. }
  758. #endif //!defined ASSIMP_BUILD_NO_AC_IMPORTER