ACLoader.cpp 26 KB

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