ACLoader.cpp 27 KB

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