PlyLoader.cpp 35 KB

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