ACLoader.cpp 32 KB

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