PlyLoader.cpp 40 KB

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