PlyLoader.cpp 34 KB

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