PlyLoader.cpp 33 KB

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