PlyLoader.cpp 40 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095
  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 PlyLoader.cpp
  35. * @brief Implementation of the PLY importer class
  36. */
  37. #ifndef ASSIMP_BUILD_NO_PLY_IMPORTER
  38. // internal headers
  39. #include "PlyLoader.h"
  40. #include "Macros.h"
  41. #include <boost/scoped_ptr.hpp>
  42. #include "../include/assimp/IOSystem.hpp"
  43. #include "../include/assimp/scene.h"
  44. using namespace Assimp;
  45. static const aiImporterDesc desc = {
  46. "Stanford Polygon Library (PLY) Importer",
  47. "",
  48. "",
  49. "",
  50. aiImporterFlags_SupportBinaryFlavour | aiImporterFlags_SupportTextFlavour,
  51. 0,
  52. 0,
  53. 0,
  54. 0,
  55. "ply"
  56. };
  57. // ------------------------------------------------------------------------------------------------
  58. // Internal stuff
  59. namespace
  60. {
  61. // ------------------------------------------------------------------------------------------------
  62. // Checks that property index is within range
  63. template <class T>
  64. const T &GetProperty(const std::vector<T> &props, int idx)
  65. {
  66. if( static_cast< size_t >( idx ) >= props.size() ) {
  67. throw DeadlyImportError( "Invalid .ply file: Property index is out of range." );
  68. }
  69. return props[idx];
  70. }
  71. }
  72. // ------------------------------------------------------------------------------------------------
  73. // Constructor to be privately used by Importer
  74. PLYImporter::PLYImporter()
  75. : mBuffer(),
  76. pcDOM()
  77. {}
  78. // ------------------------------------------------------------------------------------------------
  79. // Destructor, private as well
  80. PLYImporter::~PLYImporter()
  81. {}
  82. // ------------------------------------------------------------------------------------------------
  83. // Returns whether the class can handle the format of the given file.
  84. bool PLYImporter::CanRead( const std::string& pFile, IOSystem* pIOHandler, bool checkSig) const
  85. {
  86. const std::string extension = GetExtension(pFile);
  87. if (extension == "ply")
  88. return true;
  89. else if (!extension.length() || checkSig)
  90. {
  91. if (!pIOHandler)return true;
  92. const char* tokens[] = {"ply"};
  93. return SearchFileHeaderForToken(pIOHandler,pFile,tokens,1);
  94. }
  95. return false;
  96. }
  97. // ------------------------------------------------------------------------------------------------
  98. const aiImporterDesc* PLYImporter::GetInfo () const
  99. {
  100. return &desc;
  101. }
  102. // ------------------------------------------------------------------------------------------------
  103. // Imports the given file into the given scene structure.
  104. void PLYImporter::InternReadFile( const std::string& pFile,
  105. aiScene* pScene, IOSystem* pIOHandler)
  106. {
  107. boost::scoped_ptr<IOStream> file( pIOHandler->Open( pFile));
  108. // Check whether we can read from the file
  109. if( file.get() == NULL) {
  110. throw DeadlyImportError( "Failed to open PLY file " + pFile + ".");
  111. }
  112. // allocate storage and copy the contents of the file to a memory buffer
  113. std::vector<char> mBuffer2;
  114. TextFileToBuffer(file.get(),mBuffer2);
  115. mBuffer = (unsigned char*)&mBuffer2[0];
  116. // the beginning of the file must be PLY - magic, magic
  117. if ((mBuffer[0] != 'P' && mBuffer[0] != 'p') ||
  118. (mBuffer[1] != 'L' && mBuffer[1] != 'l') ||
  119. (mBuffer[2] != 'Y' && mBuffer[2] != 'y')) {
  120. throw DeadlyImportError( "Invalid .ply file: Magic number \'ply\' is no there");
  121. }
  122. char* szMe = (char*)&this->mBuffer[3];
  123. SkipSpacesAndLineEnd(szMe,(const char**)&szMe);
  124. // determine the format of the file data
  125. PLY::DOM sPlyDom;
  126. if (TokenMatch(szMe,"format",6))
  127. {
  128. if (TokenMatch(szMe,"ascii",5))
  129. {
  130. SkipLine(szMe,(const char**)&szMe);
  131. if(!PLY::DOM::ParseInstance(szMe,&sPlyDom))
  132. throw DeadlyImportError( "Invalid .ply file: Unable to build DOM (#1)");
  133. }
  134. else if (!::strncmp(szMe,"binary_",7))
  135. {
  136. bool bIsBE = false;
  137. szMe+=7;
  138. // binary_little_endian
  139. // binary_big_endian
  140. #if (defined AI_BUILD_BIG_ENDIAN)
  141. if ('l' == *szMe || 'L' == *szMe)bIsBE = true;
  142. #else
  143. if ('b' == *szMe || 'B' == *szMe)bIsBE = true;
  144. #endif // ! AI_BUILD_BIG_ENDIAN
  145. // skip the line, parse the rest of the header and build the DOM
  146. SkipLine(szMe,(const char**)&szMe);
  147. if(!PLY::DOM::ParseInstanceBinary(szMe,&sPlyDom,bIsBE))
  148. throw DeadlyImportError( "Invalid .ply file: Unable to build DOM (#2)");
  149. }
  150. else throw DeadlyImportError( "Invalid .ply file: Unknown file format");
  151. }
  152. else
  153. {
  154. AI_DEBUG_INVALIDATE_PTR(this->mBuffer);
  155. throw DeadlyImportError( "Invalid .ply file: Missing format specification");
  156. }
  157. this->pcDOM = &sPlyDom;
  158. // now load a list of vertices. This must be sucessfull in order to procede
  159. std::vector<aiVector3D> avPositions;
  160. this->LoadVertices(&avPositions,false);
  161. if (avPositions.empty())
  162. throw DeadlyImportError( "Invalid .ply file: No vertices found. "
  163. "Unable to parse the data format of the PLY file.");
  164. // now load a list of normals.
  165. std::vector<aiVector3D> avNormals;
  166. LoadVertices(&avNormals,true);
  167. // load the face list
  168. std::vector<PLY::Face> avFaces;
  169. LoadFaces(&avFaces);
  170. // if no face list is existing we assume that the vertex
  171. // list is containing a list of triangles
  172. if (avFaces.empty())
  173. {
  174. if (avPositions.size() < 3)
  175. {
  176. throw DeadlyImportError( "Invalid .ply file: Not enough "
  177. "vertices to build a proper face list. ");
  178. }
  179. const unsigned int iNum = (unsigned int)avPositions.size() / 3;
  180. for (unsigned int i = 0; i< iNum;++i)
  181. {
  182. PLY::Face sFace;
  183. sFace.mIndices.push_back((iNum*3));
  184. sFace.mIndices.push_back((iNum*3)+1);
  185. sFace.mIndices.push_back((iNum*3)+2);
  186. avFaces.push_back(sFace);
  187. }
  188. }
  189. // now load a list of all materials
  190. std::vector<aiMaterial*> avMaterials;
  191. LoadMaterial(&avMaterials);
  192. // now load a list of all vertex color channels
  193. std::vector<aiColor4D> avColors;
  194. avColors.reserve(avPositions.size());
  195. LoadVertexColor(&avColors);
  196. // now try to load texture coordinates
  197. std::vector<aiVector2D> avTexCoords;
  198. avTexCoords.reserve(avPositions.size());
  199. LoadTextureCoordinates(&avTexCoords);
  200. // now replace the default material in all faces and validate all material indices
  201. ReplaceDefaultMaterial(&avFaces,&avMaterials);
  202. // now convert this to a list of aiMesh instances
  203. std::vector<aiMesh*> avMeshes;
  204. avMeshes.reserve(avMaterials.size()+1);
  205. ConvertMeshes(&avFaces,&avPositions,&avNormals,
  206. &avColors,&avTexCoords,&avMaterials,&avMeshes);
  207. if (avMeshes.empty())
  208. throw DeadlyImportError( "Invalid .ply file: Unable to extract mesh data ");
  209. // now generate the output scene object. Fill the material list
  210. pScene->mNumMaterials = (unsigned int)avMaterials.size();
  211. pScene->mMaterials = new aiMaterial*[pScene->mNumMaterials];
  212. for (unsigned int i = 0; i < pScene->mNumMaterials;++i)
  213. pScene->mMaterials[i] = avMaterials[i];
  214. // fill the mesh list
  215. pScene->mNumMeshes = (unsigned int)avMeshes.size();
  216. pScene->mMeshes = new aiMesh*[pScene->mNumMeshes];
  217. for (unsigned int i = 0; i < pScene->mNumMeshes;++i)
  218. pScene->mMeshes[i] = avMeshes[i];
  219. // generate a simple node structure
  220. pScene->mRootNode = new aiNode();
  221. pScene->mRootNode->mNumMeshes = pScene->mNumMeshes;
  222. pScene->mRootNode->mMeshes = new unsigned int[pScene->mNumMeshes];
  223. for (unsigned int i = 0; i < pScene->mRootNode->mNumMeshes;++i)
  224. pScene->mRootNode->mMeshes[i] = i;
  225. }
  226. // ------------------------------------------------------------------------------------------------
  227. // Split meshes by material IDs
  228. void PLYImporter::ConvertMeshes(std::vector<PLY::Face>* avFaces,
  229. const std::vector<aiVector3D>* avPositions,
  230. const std::vector<aiVector3D>* avNormals,
  231. const std::vector<aiColor4D>* avColors,
  232. const std::vector<aiVector2D>* avTexCoords,
  233. const std::vector<aiMaterial*>* avMaterials,
  234. std::vector<aiMesh*>* avOut)
  235. {
  236. ai_assert(NULL != avFaces);
  237. ai_assert(NULL != avPositions);
  238. ai_assert(NULL != avMaterials);
  239. // split by materials
  240. std::vector<unsigned int>* aiSplit = new std::vector<unsigned int>[avMaterials->size()];
  241. unsigned int iNum = 0;
  242. for (std::vector<PLY::Face>::const_iterator i = avFaces->begin();i != avFaces->end();++i,++iNum)
  243. aiSplit[(*i).iMaterialIndex].push_back(iNum);
  244. // now generate submeshes
  245. for (unsigned int p = 0; p < avMaterials->size();++p)
  246. {
  247. if (aiSplit[p].size() != 0)
  248. {
  249. // allocate the mesh object
  250. aiMesh* p_pcOut = new aiMesh();
  251. p_pcOut->mMaterialIndex = p;
  252. p_pcOut->mNumFaces = (unsigned int)aiSplit[p].size();
  253. p_pcOut->mFaces = new aiFace[aiSplit[p].size()];
  254. // at first we need to determine the size of the output vector array
  255. unsigned int iNum = 0;
  256. for (unsigned int i = 0; i < aiSplit[p].size();++i)
  257. {
  258. iNum += (unsigned int)(*avFaces)[aiSplit[p][i]].mIndices.size();
  259. }
  260. p_pcOut->mNumVertices = iNum;
  261. if( 0 == iNum ) { // nothing to do
  262. delete[] aiSplit; // cleanup
  263. return;
  264. }
  265. p_pcOut->mVertices = new aiVector3D[iNum];
  266. if (!avColors->empty())
  267. p_pcOut->mColors[0] = new aiColor4D[iNum];
  268. if (!avTexCoords->empty())
  269. {
  270. p_pcOut->mNumUVComponents[0] = 2;
  271. p_pcOut->mTextureCoords[0] = new aiVector3D[iNum];
  272. }
  273. if (!avNormals->empty())
  274. p_pcOut->mNormals = new aiVector3D[iNum];
  275. // add all faces
  276. iNum = 0;
  277. unsigned int iVertex = 0;
  278. for (std::vector<unsigned int>::const_iterator i = aiSplit[p].begin();
  279. i != aiSplit[p].end();++i,++iNum)
  280. {
  281. p_pcOut->mFaces[iNum].mNumIndices = (unsigned int)(*avFaces)[*i].mIndices.size();
  282. p_pcOut->mFaces[iNum].mIndices = new unsigned int[p_pcOut->mFaces[iNum].mNumIndices];
  283. // build an unique set of vertices/colors for this face
  284. for (unsigned int q = 0; q < p_pcOut->mFaces[iNum].mNumIndices;++q)
  285. {
  286. p_pcOut->mFaces[iNum].mIndices[q] = iVertex;
  287. const size_t idx = ( *avFaces )[ *i ].mIndices[ q ];
  288. if( idx >= ( *avPositions ).size() ) {
  289. // out of border
  290. continue;
  291. }
  292. p_pcOut->mVertices[ iVertex ] = ( *avPositions )[ idx ];
  293. if (!avColors->empty())
  294. p_pcOut->mColors[ 0 ][ iVertex ] = ( *avColors )[ idx ];
  295. if (!avTexCoords->empty())
  296. {
  297. const aiVector2D& vec = ( *avTexCoords )[ idx ];
  298. p_pcOut->mTextureCoords[0][iVertex].x = vec.x;
  299. p_pcOut->mTextureCoords[0][iVertex].y = vec.y;
  300. }
  301. if (!avNormals->empty())
  302. p_pcOut->mNormals[ iVertex ] = ( *avNormals )[ idx ];
  303. iVertex++;
  304. }
  305. }
  306. // add the mesh to the output list
  307. avOut->push_back(p_pcOut);
  308. }
  309. }
  310. delete[] aiSplit; // cleanup
  311. }
  312. // ------------------------------------------------------------------------------------------------
  313. // Generate a default material if none was specified and apply it to all vanilla faces
  314. void PLYImporter::ReplaceDefaultMaterial(std::vector<PLY::Face>* avFaces,
  315. std::vector<aiMaterial*>* avMaterials)
  316. {
  317. bool bNeedDefaultMat = false;
  318. for (std::vector<PLY::Face>::iterator i = avFaces->begin();i != avFaces->end();++i) {
  319. if (0xFFFFFFFF == (*i).iMaterialIndex) {
  320. bNeedDefaultMat = true;
  321. (*i).iMaterialIndex = (unsigned int)avMaterials->size();
  322. }
  323. else if ((*i).iMaterialIndex >= avMaterials->size() ) {
  324. // clamp the index
  325. (*i).iMaterialIndex = (unsigned int)avMaterials->size()-1;
  326. }
  327. }
  328. if (bNeedDefaultMat) {
  329. // generate a default material
  330. aiMaterial* pcHelper = new aiMaterial();
  331. // fill in a default material
  332. int iMode = (int)aiShadingMode_Gouraud;
  333. pcHelper->AddProperty<int>(&iMode, 1, AI_MATKEY_SHADING_MODEL);
  334. aiColor3D clr;
  335. clr.b = clr.g = clr.r = 0.6f;
  336. pcHelper->AddProperty<aiColor3D>(&clr, 1,AI_MATKEY_COLOR_DIFFUSE);
  337. pcHelper->AddProperty<aiColor3D>(&clr, 1,AI_MATKEY_COLOR_SPECULAR);
  338. clr.b = clr.g = clr.r = 0.05f;
  339. pcHelper->AddProperty<aiColor3D>(&clr, 1,AI_MATKEY_COLOR_AMBIENT);
  340. // The face order is absolutely undefined for PLY, so we have to
  341. // use two-sided rendering to be sure it's ok.
  342. const int two_sided = 1;
  343. pcHelper->AddProperty(&two_sided,1,AI_MATKEY_TWOSIDED);
  344. avMaterials->push_back(pcHelper);
  345. }
  346. }
  347. // ------------------------------------------------------------------------------------------------
  348. void PLYImporter::LoadTextureCoordinates(std::vector<aiVector2D>* pvOut)
  349. {
  350. ai_assert(NULL != pvOut);
  351. unsigned int aiPositions[2] = {0xFFFFFFFF,0xFFFFFFFF};
  352. PLY::EDataType aiTypes[2] = {EDT_Char,EDT_Char};
  353. PLY::ElementInstanceList* pcList = NULL;
  354. unsigned int cnt = 0;
  355. // serach in the DOM for a vertex entry
  356. unsigned int _i = 0;
  357. for (std::vector<PLY::Element>::const_iterator i = pcDOM->alElements.begin();
  358. i != pcDOM->alElements.end();++i,++_i)
  359. {
  360. if (PLY::EEST_Vertex == (*i).eSemantic)
  361. {
  362. pcList = &this->pcDOM->alElementData[_i];
  363. // now check whether which normal components are available
  364. unsigned int _a = 0;
  365. for (std::vector<PLY::Property>::const_iterator a = (*i).alProperties.begin();
  366. a != (*i).alProperties.end();++a,++_a)
  367. {
  368. if ((*a).bIsList)continue;
  369. if (PLY::EST_UTextureCoord == (*a).Semantic)
  370. {
  371. cnt++;
  372. aiPositions[0] = _a;
  373. aiTypes[0] = (*a).eType;
  374. }
  375. else if (PLY::EST_VTextureCoord == (*a).Semantic)
  376. {
  377. cnt++;
  378. aiPositions[1] = _a;
  379. aiTypes[1] = (*a).eType;
  380. }
  381. }
  382. }
  383. }
  384. // check whether we have a valid source for the texture coordinates data
  385. if (NULL != pcList && 0 != cnt)
  386. {
  387. pvOut->reserve(pcList->alInstances.size());
  388. for (std::vector<ElementInstance>::const_iterator i = pcList->alInstances.begin();
  389. i != pcList->alInstances.end();++i)
  390. {
  391. // convert the vertices to sp floats
  392. aiVector2D vOut;
  393. if (0xFFFFFFFF != aiPositions[0])
  394. {
  395. vOut.x = PLY::PropertyInstance::ConvertTo<float>(
  396. GetProperty((*i).alProperties, aiPositions[0]).avList.front(),aiTypes[0]);
  397. }
  398. if (0xFFFFFFFF != aiPositions[1])
  399. {
  400. vOut.y = PLY::PropertyInstance::ConvertTo<float>(
  401. GetProperty((*i).alProperties, aiPositions[1]).avList.front(),aiTypes[1]);
  402. }
  403. // and add them to our nice list
  404. pvOut->push_back(vOut);
  405. }
  406. }
  407. }
  408. // ------------------------------------------------------------------------------------------------
  409. // Try to extract vertices from the PLY DOM
  410. void PLYImporter::LoadVertices(std::vector<aiVector3D>* pvOut, bool p_bNormals)
  411. {
  412. ai_assert(NULL != pvOut);
  413. unsigned int aiPositions[3] = {0xFFFFFFFF,0xFFFFFFFF,0xFFFFFFFF};
  414. PLY::EDataType aiTypes[3] = {EDT_Char,EDT_Char,EDT_Char};
  415. PLY::ElementInstanceList* pcList = NULL;
  416. unsigned int cnt = 0;
  417. // serach in the DOM for a vertex entry
  418. unsigned int _i = 0;
  419. for (std::vector<PLY::Element>::const_iterator i = pcDOM->alElements.begin();
  420. i != pcDOM->alElements.end();++i,++_i)
  421. {
  422. if (PLY::EEST_Vertex == (*i).eSemantic)
  423. {
  424. pcList = &pcDOM->alElementData[_i];
  425. // load normal vectors?
  426. if (p_bNormals)
  427. {
  428. // now check whether which normal components are available
  429. unsigned int _a = 0;
  430. for (std::vector<PLY::Property>::const_iterator a = (*i).alProperties.begin();
  431. a != (*i).alProperties.end();++a,++_a)
  432. {
  433. if ((*a).bIsList)continue;
  434. if (PLY::EST_XNormal == (*a).Semantic)
  435. {
  436. cnt++;
  437. aiPositions[0] = _a;
  438. aiTypes[0] = (*a).eType;
  439. }
  440. else if (PLY::EST_YNormal == (*a).Semantic)
  441. {
  442. cnt++;
  443. aiPositions[1] = _a;
  444. aiTypes[1] = (*a).eType;
  445. }
  446. else if (PLY::EST_ZNormal == (*a).Semantic)
  447. {
  448. cnt++;
  449. aiPositions[2] = _a;
  450. aiTypes[2] = (*a).eType;
  451. }
  452. }
  453. }
  454. // load vertex coordinates
  455. else
  456. {
  457. // now check whether which coordinate sets are available
  458. unsigned int _a = 0;
  459. for (std::vector<PLY::Property>::const_iterator a = (*i).alProperties.begin();
  460. a != (*i).alProperties.end();++a,++_a)
  461. {
  462. if ((*a).bIsList)continue;
  463. if (PLY::EST_XCoord == (*a).Semantic)
  464. {
  465. cnt++;
  466. aiPositions[0] = _a;
  467. aiTypes[0] = (*a).eType;
  468. }
  469. else if (PLY::EST_YCoord == (*a).Semantic)
  470. {
  471. cnt++;
  472. aiPositions[1] = _a;
  473. aiTypes[1] = (*a).eType;
  474. }
  475. else if (PLY::EST_ZCoord == (*a).Semantic)
  476. {
  477. cnt++;
  478. aiPositions[2] = _a;
  479. aiTypes[2] = (*a).eType;
  480. }
  481. if (3 == cnt)break;
  482. }
  483. }
  484. break;
  485. }
  486. }
  487. // check whether we have a valid source for the vertex data
  488. if (NULL != pcList && 0 != cnt)
  489. {
  490. pvOut->reserve(pcList->alInstances.size());
  491. for (std::vector<ElementInstance>::const_iterator
  492. i = pcList->alInstances.begin();
  493. i != pcList->alInstances.end();++i)
  494. {
  495. // convert the vertices to sp floats
  496. aiVector3D vOut;
  497. if (0xFFFFFFFF != aiPositions[0])
  498. {
  499. vOut.x = PLY::PropertyInstance::ConvertTo<float>(
  500. GetProperty((*i).alProperties, aiPositions[0]).avList.front(),aiTypes[0]);
  501. }
  502. if (0xFFFFFFFF != aiPositions[1])
  503. {
  504. vOut.y = PLY::PropertyInstance::ConvertTo<float>(
  505. GetProperty((*i).alProperties, aiPositions[1]).avList.front(),aiTypes[1]);
  506. }
  507. if (0xFFFFFFFF != aiPositions[2])
  508. {
  509. vOut.z = PLY::PropertyInstance::ConvertTo<float>(
  510. GetProperty((*i).alProperties, aiPositions[2]).avList.front(),aiTypes[2]);
  511. }
  512. // and add them to our nice list
  513. pvOut->push_back(vOut);
  514. }
  515. }
  516. }
  517. // ------------------------------------------------------------------------------------------------
  518. // Convert a color component to [0...1]
  519. float PLYImporter::NormalizeColorValue (PLY::PropertyInstance::ValueUnion val,
  520. PLY::EDataType eType)
  521. {
  522. switch (eType)
  523. {
  524. case EDT_Float:
  525. return val.fFloat;
  526. case EDT_Double:
  527. return (float)val.fDouble;
  528. case EDT_UChar:
  529. return (float)val.iUInt / (float)0xFF;
  530. case EDT_Char:
  531. return (float)(val.iInt+(0xFF/2)) / (float)0xFF;
  532. case EDT_UShort:
  533. return (float)val.iUInt / (float)0xFFFF;
  534. case EDT_Short:
  535. return (float)(val.iInt+(0xFFFF/2)) / (float)0xFFFF;
  536. case EDT_UInt:
  537. return (float)val.iUInt / (float)0xFFFF;
  538. case EDT_Int:
  539. return ((float)val.iInt / (float)0xFF) + 0.5f;
  540. default: ;
  541. };
  542. return 0.0f;
  543. }
  544. // ------------------------------------------------------------------------------------------------
  545. // Try to extract proper vertex colors from the PLY DOM
  546. void PLYImporter::LoadVertexColor(std::vector<aiColor4D>* pvOut)
  547. {
  548. ai_assert(NULL != pvOut);
  549. unsigned int aiPositions[4] = {0xFFFFFFFF,0xFFFFFFFF,0xFFFFFFFF,0xFFFFFFFF};
  550. PLY::EDataType aiTypes[4] = {EDT_Char, EDT_Char, EDT_Char, EDT_Char}; // silencing gcc
  551. unsigned int cnt = 0;
  552. PLY::ElementInstanceList* pcList = NULL;
  553. // serach in the DOM for a vertex entry
  554. unsigned int _i = 0;
  555. for (std::vector<PLY::Element>::const_iterator i = pcDOM->alElements.begin();
  556. i != pcDOM->alElements.end();++i,++_i)
  557. {
  558. if (PLY::EEST_Vertex == (*i).eSemantic)
  559. {
  560. pcList = &this->pcDOM->alElementData[_i];
  561. // now check whether which coordinate sets are available
  562. unsigned int _a = 0;
  563. for (std::vector<PLY::Property>::const_iterator
  564. a = (*i).alProperties.begin();
  565. a != (*i).alProperties.end();++a,++_a)
  566. {
  567. if ((*a).bIsList)continue;
  568. if (PLY::EST_Red == (*a).Semantic)
  569. {
  570. cnt++;
  571. aiPositions[0] = _a;
  572. aiTypes[0] = (*a).eType;
  573. }
  574. else if (PLY::EST_Green == (*a).Semantic)
  575. {
  576. cnt++;
  577. aiPositions[1] = _a;
  578. aiTypes[1] = (*a).eType;
  579. }
  580. else if (PLY::EST_Blue == (*a).Semantic)
  581. {
  582. cnt++;
  583. aiPositions[2] = _a;
  584. aiTypes[2] = (*a).eType;
  585. }
  586. else if (PLY::EST_Alpha == (*a).Semantic)
  587. {
  588. cnt++;
  589. aiPositions[3] = _a;
  590. aiTypes[3] = (*a).eType;
  591. }
  592. if (4 == cnt)break;
  593. }
  594. break;
  595. }
  596. }
  597. // check whether we have a valid source for the vertex data
  598. if (NULL != pcList && 0 != cnt)
  599. {
  600. pvOut->reserve(pcList->alInstances.size());
  601. for (std::vector<ElementInstance>::const_iterator i = pcList->alInstances.begin();
  602. i != pcList->alInstances.end();++i)
  603. {
  604. // convert the vertices to sp floats
  605. aiColor4D vOut;
  606. if (0xFFFFFFFF != aiPositions[0])
  607. {
  608. vOut.r = NormalizeColorValue(GetProperty((*i).alProperties,
  609. aiPositions[0]).avList.front(),aiTypes[0]);
  610. }
  611. if (0xFFFFFFFF != aiPositions[1])
  612. {
  613. vOut.g = NormalizeColorValue(GetProperty((*i).alProperties,
  614. aiPositions[1]).avList.front(),aiTypes[1]);
  615. }
  616. if (0xFFFFFFFF != aiPositions[2])
  617. {
  618. vOut.b = NormalizeColorValue(GetProperty((*i).alProperties,
  619. aiPositions[2]).avList.front(),aiTypes[2]);
  620. }
  621. // assume 1.0 for the alpha channel ifit is not set
  622. if (0xFFFFFFFF == aiPositions[3])vOut.a = 1.0f;
  623. else
  624. {
  625. vOut.a = NormalizeColorValue(GetProperty((*i).alProperties,
  626. aiPositions[3]).avList.front(),aiTypes[3]);
  627. }
  628. // and add them to our nice list
  629. pvOut->push_back(vOut);
  630. }
  631. }
  632. }
  633. // ------------------------------------------------------------------------------------------------
  634. // Try to extract proper faces from the PLY DOM
  635. void PLYImporter::LoadFaces(std::vector<PLY::Face>* pvOut)
  636. {
  637. ai_assert(NULL != pvOut);
  638. PLY::ElementInstanceList* pcList = NULL;
  639. bool bOne = false;
  640. // index of the vertex index list
  641. unsigned int iProperty = 0xFFFFFFFF;
  642. PLY::EDataType eType = EDT_Char;
  643. bool bIsTristrip = false;
  644. // index of the material index property
  645. unsigned int iMaterialIndex = 0xFFFFFFFF;
  646. PLY::EDataType eType2 = EDT_Char;
  647. // serach in the DOM for a face entry
  648. unsigned int _i = 0;
  649. for (std::vector<PLY::Element>::const_iterator i = pcDOM->alElements.begin();
  650. i != pcDOM->alElements.end();++i,++_i)
  651. {
  652. // face = unique number of vertex indices
  653. if (PLY::EEST_Face == (*i).eSemantic)
  654. {
  655. pcList = &pcDOM->alElementData[_i];
  656. unsigned int _a = 0;
  657. for (std::vector<PLY::Property>::const_iterator a = (*i).alProperties.begin();
  658. a != (*i).alProperties.end();++a,++_a)
  659. {
  660. if (PLY::EST_VertexIndex == (*a).Semantic)
  661. {
  662. // must be a dynamic list!
  663. if (!(*a).bIsList)continue;
  664. iProperty = _a;
  665. bOne = true;
  666. eType = (*a).eType;
  667. }
  668. else if (PLY::EST_MaterialIndex == (*a).Semantic)
  669. {
  670. if ((*a).bIsList)continue;
  671. iMaterialIndex = _a;
  672. bOne = true;
  673. eType2 = (*a).eType;
  674. }
  675. }
  676. break;
  677. }
  678. // triangle strip
  679. // TODO: triangle strip and material index support???
  680. else if (PLY::EEST_TriStrip == (*i).eSemantic)
  681. {
  682. // find a list property in this ...
  683. pcList = &this->pcDOM->alElementData[_i];
  684. unsigned int _a = 0;
  685. for (std::vector<PLY::Property>::const_iterator a = (*i).alProperties.begin();
  686. a != (*i).alProperties.end();++a,++_a)
  687. {
  688. // must be a dynamic list!
  689. if (!(*a).bIsList)continue;
  690. iProperty = _a;
  691. bOne = true;
  692. bIsTristrip = true;
  693. eType = (*a).eType;
  694. break;
  695. }
  696. break;
  697. }
  698. }
  699. // check whether we have at least one per-face information set
  700. if (pcList && bOne)
  701. {
  702. if (!bIsTristrip)
  703. {
  704. pvOut->reserve(pcList->alInstances.size());
  705. for (std::vector<ElementInstance>::const_iterator i = pcList->alInstances.begin();
  706. i != pcList->alInstances.end();++i)
  707. {
  708. PLY::Face sFace;
  709. // parse the list of vertex indices
  710. if (0xFFFFFFFF != iProperty)
  711. {
  712. const unsigned int iNum = (unsigned int)GetProperty((*i).alProperties, iProperty).avList.size();
  713. sFace.mIndices.resize(iNum);
  714. std::vector<PLY::PropertyInstance::ValueUnion>::const_iterator p =
  715. GetProperty((*i).alProperties, iProperty).avList.begin();
  716. for (unsigned int a = 0; a < iNum;++a,++p)
  717. {
  718. sFace.mIndices[a] = PLY::PropertyInstance::ConvertTo<unsigned int>(*p,eType);
  719. }
  720. }
  721. // parse the material index
  722. if (0xFFFFFFFF != iMaterialIndex)
  723. {
  724. sFace.iMaterialIndex = PLY::PropertyInstance::ConvertTo<unsigned int>(
  725. GetProperty((*i).alProperties, iMaterialIndex).avList.front(),eType2);
  726. }
  727. pvOut->push_back(sFace);
  728. }
  729. }
  730. else // triangle strips
  731. {
  732. // normally we have only one triangle strip instance where
  733. // a value of -1 indicates a restart of the strip
  734. bool flip = false;
  735. for (std::vector<ElementInstance>::const_iterator i = pcList->alInstances.begin();i != pcList->alInstances.end();++i) {
  736. const std::vector<PLY::PropertyInstance::ValueUnion>& quak = GetProperty((*i).alProperties, iProperty).avList;
  737. pvOut->reserve(pvOut->size() + quak.size() + (quak.size()>>2u));
  738. int aiTable[2] = {-1,-1};
  739. for (std::vector<PLY::PropertyInstance::ValueUnion>::const_iterator a = quak.begin();a != quak.end();++a) {
  740. const int p = PLY::PropertyInstance::ConvertTo<int>(*a,eType);
  741. if (-1 == p) {
  742. // restart the strip ...
  743. aiTable[0] = aiTable[1] = -1;
  744. flip = false;
  745. continue;
  746. }
  747. if (-1 == aiTable[0]) {
  748. aiTable[0] = p;
  749. continue;
  750. }
  751. if (-1 == aiTable[1]) {
  752. aiTable[1] = p;
  753. continue;
  754. }
  755. pvOut->push_back(PLY::Face());
  756. PLY::Face& sFace = pvOut->back();
  757. sFace.mIndices[0] = aiTable[0];
  758. sFace.mIndices[1] = aiTable[1];
  759. sFace.mIndices[2] = p;
  760. if ((flip = !flip)) {
  761. std::swap(sFace.mIndices[0],sFace.mIndices[1]);
  762. }
  763. aiTable[0] = aiTable[1];
  764. aiTable[1] = p;
  765. }
  766. }
  767. }
  768. }
  769. }
  770. // ------------------------------------------------------------------------------------------------
  771. // Get a RGBA color in [0...1] range
  772. void PLYImporter::GetMaterialColor(const std::vector<PLY::PropertyInstance>& avList,
  773. unsigned int aiPositions[4],
  774. PLY::EDataType aiTypes[4],
  775. aiColor4D* clrOut)
  776. {
  777. ai_assert(NULL != clrOut);
  778. if (0xFFFFFFFF == aiPositions[0])clrOut->r = 0.0f;
  779. else
  780. {
  781. clrOut->r = NormalizeColorValue(GetProperty(avList,
  782. aiPositions[0]).avList.front(),aiTypes[0]);
  783. }
  784. if (0xFFFFFFFF == aiPositions[1])clrOut->g = 0.0f;
  785. else
  786. {
  787. clrOut->g = NormalizeColorValue(GetProperty(avList,
  788. aiPositions[1]).avList.front(),aiTypes[1]);
  789. }
  790. if (0xFFFFFFFF == aiPositions[2])clrOut->b = 0.0f;
  791. else
  792. {
  793. clrOut->b = NormalizeColorValue(GetProperty(avList,
  794. aiPositions[2]).avList.front(),aiTypes[2]);
  795. }
  796. // assume 1.0 for the alpha channel ifit is not set
  797. if (0xFFFFFFFF == aiPositions[3])clrOut->a = 1.0f;
  798. else
  799. {
  800. clrOut->a = NormalizeColorValue(GetProperty(avList,
  801. aiPositions[3]).avList.front(),aiTypes[3]);
  802. }
  803. }
  804. // ------------------------------------------------------------------------------------------------
  805. // Extract a material from the PLY DOM
  806. void PLYImporter::LoadMaterial(std::vector<aiMaterial*>* pvOut)
  807. {
  808. ai_assert(NULL != pvOut);
  809. // diffuse[4], specular[4], ambient[4]
  810. // rgba order
  811. unsigned int aaiPositions[3][4] = {
  812. {0xFFFFFFFF,0xFFFFFFFF,0xFFFFFFFF,0xFFFFFFFF},
  813. {0xFFFFFFFF,0xFFFFFFFF,0xFFFFFFFF,0xFFFFFFFF},
  814. {0xFFFFFFFF,0xFFFFFFFF,0xFFFFFFFF,0xFFFFFFFF},
  815. };
  816. PLY::EDataType aaiTypes[3][4] = {
  817. {EDT_Char,EDT_Char,EDT_Char,EDT_Char},
  818. {EDT_Char,EDT_Char,EDT_Char,EDT_Char},
  819. {EDT_Char,EDT_Char,EDT_Char,EDT_Char}
  820. };
  821. PLY::ElementInstanceList* pcList = NULL;
  822. unsigned int iPhong = 0xFFFFFFFF;
  823. PLY::EDataType ePhong = EDT_Char;
  824. unsigned int iOpacity = 0xFFFFFFFF;
  825. PLY::EDataType eOpacity = EDT_Char;
  826. // serach in the DOM for a vertex entry
  827. unsigned int _i = 0;
  828. for (std::vector<PLY::Element>::const_iterator i = this->pcDOM->alElements.begin();
  829. i != this->pcDOM->alElements.end();++i,++_i)
  830. {
  831. if (PLY::EEST_Material == (*i).eSemantic)
  832. {
  833. pcList = &this->pcDOM->alElementData[_i];
  834. // now check whether which coordinate sets are available
  835. unsigned int _a = 0;
  836. for (std::vector<PLY::Property>::const_iterator
  837. a = (*i).alProperties.begin();
  838. a != (*i).alProperties.end();++a,++_a)
  839. {
  840. if ((*a).bIsList)continue;
  841. // pohng specularity -----------------------------------
  842. if (PLY::EST_PhongPower == (*a).Semantic)
  843. {
  844. iPhong = _a;
  845. ePhong = (*a).eType;
  846. }
  847. // general opacity -----------------------------------
  848. if (PLY::EST_Opacity == (*a).Semantic)
  849. {
  850. iOpacity = _a;
  851. eOpacity = (*a).eType;
  852. }
  853. // diffuse color channels -----------------------------------
  854. if (PLY::EST_DiffuseRed == (*a).Semantic)
  855. {
  856. aaiPositions[0][0] = _a;
  857. aaiTypes[0][0] = (*a).eType;
  858. }
  859. else if (PLY::EST_DiffuseGreen == (*a).Semantic)
  860. {
  861. aaiPositions[0][1] = _a;
  862. aaiTypes[0][1] = (*a).eType;
  863. }
  864. else if (PLY::EST_DiffuseBlue == (*a).Semantic)
  865. {
  866. aaiPositions[0][2] = _a;
  867. aaiTypes[0][2] = (*a).eType;
  868. }
  869. else if (PLY::EST_DiffuseAlpha == (*a).Semantic)
  870. {
  871. aaiPositions[0][3] = _a;
  872. aaiTypes[0][3] = (*a).eType;
  873. }
  874. // specular color channels -----------------------------------
  875. else if (PLY::EST_SpecularRed == (*a).Semantic)
  876. {
  877. aaiPositions[1][0] = _a;
  878. aaiTypes[1][0] = (*a).eType;
  879. }
  880. else if (PLY::EST_SpecularGreen == (*a).Semantic)
  881. {
  882. aaiPositions[1][1] = _a;
  883. aaiTypes[1][1] = (*a).eType;
  884. }
  885. else if (PLY::EST_SpecularBlue == (*a).Semantic)
  886. {
  887. aaiPositions[1][2] = _a;
  888. aaiTypes[1][2] = (*a).eType;
  889. }
  890. else if (PLY::EST_SpecularAlpha == (*a).Semantic)
  891. {
  892. aaiPositions[1][3] = _a;
  893. aaiTypes[1][3] = (*a).eType;
  894. }
  895. // ambient color channels -----------------------------------
  896. else if (PLY::EST_AmbientRed == (*a).Semantic)
  897. {
  898. aaiPositions[2][0] = _a;
  899. aaiTypes[2][0] = (*a).eType;
  900. }
  901. else if (PLY::EST_AmbientGreen == (*a).Semantic)
  902. {
  903. aaiPositions[2][1] = _a;
  904. aaiTypes[2][1] = (*a).eType;
  905. }
  906. else if (PLY::EST_AmbientBlue == (*a).Semantic)
  907. {
  908. aaiPositions[2][2] = _a;
  909. aaiTypes[2][2] = (*a).eType;
  910. }
  911. else if (PLY::EST_AmbientAlpha == (*a).Semantic)
  912. {
  913. aaiPositions[2][3] = _a;
  914. aaiTypes[2][3] = (*a).eType;
  915. }
  916. }
  917. break;
  918. }
  919. }
  920. // check whether we have a valid source for the material data
  921. if (NULL != pcList) {
  922. for (std::vector<ElementInstance>::const_iterator i = pcList->alInstances.begin();i != pcList->alInstances.end();++i) {
  923. aiColor4D clrOut;
  924. aiMaterial* pcHelper = new aiMaterial();
  925. // build the diffuse material color
  926. GetMaterialColor((*i).alProperties,aaiPositions[0],aaiTypes[0],&clrOut);
  927. pcHelper->AddProperty<aiColor4D>(&clrOut,1,AI_MATKEY_COLOR_DIFFUSE);
  928. // build the specular material color
  929. GetMaterialColor((*i).alProperties,aaiPositions[1],aaiTypes[1],&clrOut);
  930. pcHelper->AddProperty<aiColor4D>(&clrOut,1,AI_MATKEY_COLOR_SPECULAR);
  931. // build the ambient material color
  932. GetMaterialColor((*i).alProperties,aaiPositions[2],aaiTypes[2],&clrOut);
  933. pcHelper->AddProperty<aiColor4D>(&clrOut,1,AI_MATKEY_COLOR_AMBIENT);
  934. // handle phong power and shading mode
  935. int iMode;
  936. if (0xFFFFFFFF != iPhong) {
  937. float fSpec = PLY::PropertyInstance::ConvertTo<float>(GetProperty((*i).alProperties, iPhong).avList.front(),ePhong);
  938. // if shininess is 0 (and the pow() calculation would therefore always
  939. // become 1, not depending on the angle), use gouraud lighting
  940. if (fSpec) {
  941. // scale this with 15 ... hopefully this is correct
  942. fSpec *= 15;
  943. pcHelper->AddProperty<float>(&fSpec, 1, AI_MATKEY_SHININESS);
  944. iMode = (int)aiShadingMode_Phong;
  945. }
  946. else iMode = (int)aiShadingMode_Gouraud;
  947. }
  948. else iMode = (int)aiShadingMode_Gouraud;
  949. pcHelper->AddProperty<int>(&iMode, 1, AI_MATKEY_SHADING_MODEL);
  950. // handle opacity
  951. if (0xFFFFFFFF != iOpacity) {
  952. float fOpacity = PLY::PropertyInstance::ConvertTo<float>(GetProperty((*i).alProperties, iPhong).avList.front(),eOpacity);
  953. pcHelper->AddProperty<float>(&fOpacity, 1, AI_MATKEY_OPACITY);
  954. }
  955. // The face order is absolutely undefined for PLY, so we have to
  956. // use two-sided rendering to be sure it's ok.
  957. const int two_sided = 1;
  958. pcHelper->AddProperty(&two_sided,1,AI_MATKEY_TWOSIDED);
  959. // add the newly created material instance to the list
  960. pvOut->push_back(pcHelper);
  961. }
  962. }
  963. }
  964. #endif // !! ASSIMP_BUILD_NO_PLY_IMPORTER