ccCropTool.cpp 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468
  1. //##########################################################################
  2. //# #
  3. //# CLOUDCOMPARE #
  4. //# #
  5. //# This program is free software; you can redistribute it and/or modify #
  6. //# it under the terms of the GNU General Public License as published by #
  7. //# the Free Software Foundation; version 2 or later of the License. #
  8. //# #
  9. //# This program is distributed in the hope that it will be useful, #
  10. //# but WITHOUT ANY WARRANTY; without even the implied warranty of #
  11. //# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the #
  12. //# GNU General Public License for more details. #
  13. //# #
  14. //# COPYRIGHT: EDF R&D / TELECOM ParisTech (ENST-TSI) #
  15. //# #
  16. //##########################################################################
  17. #include "ccCropTool.h"
  18. //qCC_db
  19. #include <ccHObject.h>
  20. #include <ccPointCloud.h>
  21. #include <ccMesh.h>
  22. #include <ccLog.h>
  23. #include <ccScalarField.h>
  24. #include <ccMaterial.h>
  25. #include <ccMaterialSet.h>
  26. //CCCoreLib
  27. #include <ManualSegmentationTools.h>
  28. #include <SimpleMesh.h>
  29. ccHObject* ccCropTool::Crop(ccHObject* entity, const ccBBox& box, bool inside/*=true*/, const ccGLMatrix* meshRotation/*=nullptr*/)
  30. {
  31. assert(entity);
  32. if (!entity)
  33. {
  34. return nullptr;
  35. }
  36. if (entity->isA(CC_TYPES::POINT_CLOUD))
  37. {
  38. ccPointCloud* cloud = static_cast<ccPointCloud*>(entity);
  39. CCCoreLib::ReferenceCloud* selection = cloud->crop(box, inside);
  40. if (!selection)
  41. {
  42. //process failed!
  43. ccLog::Warning(QString("[Crop] Failed to crop cloud '%1'!").arg(cloud->getName()));
  44. return nullptr;
  45. }
  46. if (selection->size() == 0)
  47. {
  48. //no points fall inside selection!
  49. ccLog::Warning(QString("[Crop] No point of the cloud '%1' falls %2side the input box!").arg(cloud->getName(), (inside ? "in" : "out")));
  50. delete selection;
  51. return nullptr;
  52. }
  53. //crop
  54. ccPointCloud* croppedEnt = cloud->partialClone(selection);
  55. delete selection;
  56. selection = nullptr;
  57. return croppedEnt;
  58. }
  59. else if (entity->isKindOf(CC_TYPES::MESH))
  60. {
  61. ccGenericMesh* mesh = static_cast<ccGenericMesh*>(entity);
  62. CCCoreLib::ManualSegmentationTools::MeshCutterParams params;
  63. params.bbMin = box.minCorner();
  64. params.bbMax = box.maxCorner();
  65. params.generateOutsideMesh = !inside;
  66. params.trackOrigIndexes = mesh->hasColors() || mesh->hasScalarFields() || mesh->hasMaterials();
  67. ccGenericPointCloud* origVertices = mesh->getAssociatedCloud();
  68. assert(origVertices);
  69. ccGenericPointCloud* cropVertices = origVertices;
  70. if (meshRotation)
  71. {
  72. ccPointCloud* rotatedVertices = ccPointCloud::From(origVertices);
  73. if (!rotatedVertices)
  74. {
  75. ccLog::Warning(QString("[Crop] Failed to crop mesh '%1'! (not enough memory)").arg(mesh->getName()));
  76. return nullptr;
  77. }
  78. rotatedVertices->setGLTransformation(*meshRotation);
  79. rotatedVertices->applyGLTransformation_recursive();
  80. cropVertices = rotatedVertices;
  81. }
  82. if (!CCCoreLib::ManualSegmentationTools::segmentMeshWithAABox(mesh, cropVertices, params))
  83. {
  84. //process failed!
  85. ccLog::Warning(QString("[Crop] Failed to crop mesh '%1'!").arg(mesh->getName()));
  86. }
  87. if (cropVertices != origVertices)
  88. {
  89. //don't need those anymore
  90. delete cropVertices;
  91. cropVertices = origVertices;
  92. }
  93. CCCoreLib::SimpleMesh* tempMesh = inside ? params.insideMesh : params.outsideMesh;
  94. //output
  95. ccMesh* croppedMesh = nullptr;
  96. if (tempMesh)
  97. {
  98. ccPointCloud* croppedVertices = ccPointCloud::From(tempMesh->vertices());
  99. if (croppedVertices)
  100. {
  101. if (meshRotation)
  102. {
  103. //apply inverse transformation
  104. croppedVertices->setGLTransformation(meshRotation->inverse());
  105. croppedVertices->applyGLTransformation_recursive();
  106. }
  107. croppedMesh = new ccMesh(tempMesh, croppedVertices);
  108. croppedMesh->addChild(croppedVertices);
  109. croppedVertices->setEnabled(false);
  110. if (croppedMesh->size() == 0)
  111. {
  112. //no points fall inside selection!
  113. ccLog::Warning(QString("[Crop] No triangle of the mesh '%1' falls %2side the input box!").arg(mesh->getName(), (inside ? "in" : "out")));
  114. delete croppedMesh;
  115. croppedMesh = nullptr;
  116. }
  117. else
  118. {
  119. assert(origVertices);
  120. //import parameters
  121. croppedVertices->importParametersFrom(origVertices);
  122. croppedMesh->importParametersFrom(mesh);
  123. //compute normals if necessary
  124. if (mesh->hasNormals())
  125. {
  126. bool success = false;
  127. if (mesh->hasTriNormals())
  128. success = croppedMesh->computePerTriangleNormals();
  129. else
  130. success = croppedMesh->computePerVertexNormals();
  131. if (!success)
  132. {
  133. ccLog::Warning("[Crop] Failed to compute normals on the output mesh (not enough memory)");
  134. }
  135. croppedMesh->showNormals(success && mesh->normalsShown());
  136. }
  137. //import other features if necessary
  138. if (params.trackOrigIndexes)
  139. {
  140. const std::vector<unsigned>& origTriIndexes = inside ? params.origTriIndexesMapInside : params.origTriIndexesMapOutside;
  141. try
  142. {
  143. //per vertex features (RGB color & scalar fields)
  144. if (origVertices->hasColors() || origVertices->hasScalarFields())
  145. {
  146. //we use flags to avoid processing the same vertex multiple times
  147. std::vector<bool> vertProcessed(croppedVertices->size(), false);
  148. //colors
  149. bool importColors = false;
  150. if (origVertices->hasColors())
  151. {
  152. importColors = croppedVertices->resizeTheRGBTable();
  153. if (!importColors)
  154. ccLog::Warning("[Crop] Failed to transfer RGB colors on the output mesh (not enough memory)");
  155. }
  156. //scalar fields
  157. std::vector<ccScalarField*> importedSFs;
  158. ccPointCloud* origVertices_pc = nullptr;
  159. if (origVertices->hasScalarFields())
  160. {
  161. origVertices_pc = origVertices->isA(CC_TYPES::POINT_CLOUD) ? static_cast<ccPointCloud*>(origVertices) : nullptr;
  162. unsigned sfCount = origVertices_pc ? origVertices_pc->getNumberOfScalarFields() : 1;
  163. //now try to import each SF
  164. for (unsigned i = 0; i < sfCount; ++i)
  165. {
  166. int sfIdx = croppedVertices->addScalarField(origVertices_pc ? origVertices_pc->getScalarField(i)->getName() : "Scalar field");
  167. if (sfIdx >= 0)
  168. {
  169. ccScalarField* sf = static_cast<ccScalarField*>(croppedVertices->getScalarField(i));
  170. sf->fill(CCCoreLib::NAN_VALUE);
  171. if (origVertices_pc)
  172. {
  173. //import display parameters if possible
  174. ccScalarField* originSf = static_cast<ccScalarField*>(origVertices_pc->getScalarField(i));
  175. assert(originSf);
  176. //copy display parameters
  177. sf->importParametersFrom(originSf);
  178. }
  179. importedSFs.push_back(sf);
  180. }
  181. else
  182. {
  183. ccLog::Warning("[Crop] Failed to transfer one or several scalar fields on the output mesh (not enough memory)");
  184. //we can stop right now as all SFs have the same size!
  185. break;
  186. }
  187. }
  188. //default displayed SF
  189. if (origVertices_pc)
  190. croppedVertices->setCurrentDisplayedScalarField(std::max(static_cast<int>(croppedVertices->getNumberOfScalarFields())-1, origVertices_pc->getCurrentDisplayedScalarFieldIndex()));
  191. else
  192. croppedVertices->setCurrentDisplayedScalarField(0);
  193. }
  194. bool importSFs = !importedSFs.empty();
  195. if (importColors || importSFs)
  196. {
  197. //for each new triangle
  198. for (unsigned i = 0; i < croppedMesh->size(); ++i)
  199. {
  200. //get the origin triangle
  201. unsigned origTriIndex = origTriIndexes[i];
  202. const CCCoreLib::VerticesIndexes* tsio = mesh->getTriangleVertIndexes(origTriIndex);
  203. //get the new triangle
  204. const CCCoreLib::VerticesIndexes* tsic = croppedMesh->getTriangleVertIndexes(i);
  205. //we now have to test the 3 vertices of the new triangle
  206. for (unsigned j = 0; j < 3; ++j)
  207. {
  208. unsigned vertIndex = tsic->i[j];
  209. if (vertProcessed[vertIndex])
  210. {
  211. //vertex has already been process
  212. continue;
  213. }
  214. const CCVector3* Vcj = croppedVertices->getPoint(vertIndex);
  215. //we'll deduce its color and SFs values by triangulation
  216. if (importColors)
  217. {
  218. ccColor::Rgb col;
  219. if (mesh->interpolateColors(origTriIndex, *Vcj, col))
  220. {
  221. croppedVertices->setPointColor(vertIndex, col);
  222. }
  223. }
  224. if (importSFs)
  225. {
  226. CCVector3d w;
  227. mesh->computeInterpolationWeights(origTriIndex, *Vcj, w);
  228. //import SFs
  229. for (unsigned s = 0; s < static_cast<unsigned>(importedSFs.size()); ++s)
  230. {
  231. CCVector3d scalarValues(0, 0, 0);
  232. if (origVertices_pc)
  233. {
  234. const CCCoreLib::ScalarField* sf = origVertices_pc->getScalarField(s);
  235. scalarValues.x = sf->getValue(tsio->i1);
  236. scalarValues.y = sf->getValue(tsio->i2);
  237. scalarValues.z = sf->getValue(tsio->i3);
  238. }
  239. else
  240. {
  241. assert(s == 0);
  242. scalarValues.x = origVertices->getPointScalarValue(tsio->i1);
  243. scalarValues.y = origVertices->getPointScalarValue(tsio->i2);
  244. scalarValues.z = origVertices->getPointScalarValue(tsio->i3);
  245. }
  246. ScalarType sVal = static_cast<ScalarType>(scalarValues.dot(w));
  247. importedSFs[s]->setValue(vertIndex,sVal);
  248. }
  249. }
  250. //update 'processed' flag
  251. vertProcessed[vertIndex] = true;
  252. }
  253. }
  254. for (size_t s = 0; s < importedSFs.size(); ++s)
  255. {
  256. importedSFs[s]->computeMinAndMax();
  257. }
  258. croppedVertices->showColors(importColors && origVertices->colorsShown());
  259. croppedVertices->showSF(importSFs && origVertices->sfShown());
  260. croppedMesh->showColors(importColors && mesh->colorsShown());
  261. croppedMesh->showSF(importSFs && mesh->sfShown());
  262. }
  263. }
  264. //per-triangle features (materials)
  265. if (mesh->hasMaterials())
  266. {
  267. const ccMaterialSet* origMaterialSet = mesh->getMaterialSet();
  268. assert(origMaterialSet);
  269. if (origMaterialSet && !origMaterialSet->empty() && croppedMesh->reservePerTriangleMtlIndexes())
  270. {
  271. std::vector<int> materialUsed(origMaterialSet->size(),-1);
  272. //per-triangle materials
  273. for (unsigned i = 0; i < croppedMesh->size(); ++i)
  274. {
  275. //get the origin triangle
  276. unsigned origTriIndex = origTriIndexes[i];
  277. int mtlIndex = mesh->getTriangleMtlIndex(origTriIndex);
  278. croppedMesh->addTriangleMtlIndex(mtlIndex);
  279. if (mtlIndex >= 0)
  280. materialUsed[mtlIndex] = 1;
  281. }
  282. //import materials
  283. {
  284. size_t materialUsedCount = 0;
  285. {
  286. for (size_t i = 0; i < materialUsed.size(); ++i)
  287. if (materialUsed[i] == 1)
  288. ++materialUsedCount;
  289. }
  290. if (materialUsedCount == materialUsed.size())
  291. {
  292. //nothing to do, we use all input materials
  293. croppedMesh->setMaterialSet(origMaterialSet->clone());
  294. }
  295. else
  296. {
  297. //create a subset of the input materials
  298. ccMaterialSet* matSet = new ccMaterialSet(origMaterialSet->getName());
  299. {
  300. matSet->reserve(materialUsedCount);
  301. for (size_t i = 0; i < materialUsed.size(); ++i)
  302. {
  303. if (materialUsed[i] >= 0)
  304. {
  305. matSet->push_back(ccMaterial::Shared(new ccMaterial(*origMaterialSet->at(i))));
  306. //update index
  307. materialUsed[i] = static_cast<int>(matSet->size()) - 1;
  308. }
  309. }
  310. }
  311. croppedMesh->setMaterialSet(matSet);
  312. //and update the materials indexes!
  313. for (unsigned i = 0; i < croppedMesh->size(); ++i)
  314. {
  315. int mtlIndex = croppedMesh->getTriangleMtlIndex(i);
  316. if (mtlIndex >= 0)
  317. {
  318. assert(mtlIndex < static_cast<int>(materialUsed.size()));
  319. croppedMesh->setTriangleMtlIndex(i,materialUsed[mtlIndex]);
  320. }
  321. }
  322. }
  323. }
  324. croppedMesh->showMaterials(mesh->materialsShown());
  325. }
  326. else
  327. {
  328. ccLog::Warning("[Crop] Failed to transfer materials on the output mesh (not enough memory)");
  329. }
  330. //per-triangle texture coordinates
  331. if (mesh->hasPerTriangleTexCoordIndexes())
  332. {
  333. TextureCoordsContainer* texCoords = new TextureCoordsContainer;
  334. if ( croppedMesh->reservePerTriangleTexCoordIndexes()
  335. && texCoords->reserveSafe(croppedMesh->size()*3))
  336. {
  337. //for each new triangle
  338. for (unsigned i = 0; i < croppedMesh->size(); ++i)
  339. {
  340. //get the origin triangle
  341. unsigned origTriIndex = origTriIndexes[i];
  342. TexCoords2D* tx1 = nullptr;
  343. TexCoords2D* tx2 = nullptr;
  344. TexCoords2D* tx3 = nullptr;
  345. mesh->getTriangleTexCoordinates(origTriIndex, tx1, tx2, tx3);
  346. //get the new triangle
  347. const CCCoreLib::VerticesIndexes* tsic = croppedMesh->getTriangleVertIndexes(i);
  348. //for each vertex of the new triangle
  349. int texIndexes[3] = { -1, -1, -1 };
  350. for (unsigned j = 0; j < 3; ++j)
  351. {
  352. unsigned vertIndex = tsic->i[j];
  353. const CCVector3* Vcj = croppedVertices->getPoint(vertIndex);
  354. //intepolation weights
  355. CCVector3d w;
  356. mesh->computeInterpolationWeights(origTriIndex, *Vcj, w);
  357. if ( (tx1 || CCCoreLib::LessThanEpsilon( w.u[0] ) )
  358. && (tx2 || CCCoreLib::LessThanEpsilon( w.u[1] ) )
  359. && (tx3 || CCCoreLib::LessThanEpsilon( w.u[2] ) ) )
  360. {
  361. TexCoords2D t( static_cast<float>((tx1 ? tx1->tx*w.u[0] : 0.0) + (tx2 ? tx2->tx*w.u[1] : 0.0) + (tx3 ? tx3->tx*w.u[2] : 0.0)),
  362. static_cast<float>((tx1 ? tx1->ty*w.u[0] : 0.0) + (tx2 ? tx2->ty*w.u[1] : 0.0) + (tx3 ? tx3->ty*w.u[2] : 0.0)) );
  363. texCoords->addElement(t);
  364. texIndexes[j] = static_cast<int>(texCoords->currentSize()) - 1;
  365. }
  366. }
  367. croppedMesh->addTriangleTexCoordIndexes(texIndexes[0], texIndexes[1], texIndexes[2]);
  368. }
  369. croppedMesh->setTexCoordinatesTable(texCoords);
  370. }
  371. else
  372. {
  373. ccLog::Warning("[Crop] Failed to transfer texture coordinates on the output mesh (not enough memory)");
  374. delete texCoords;
  375. texCoords = nullptr;
  376. }
  377. }
  378. }
  379. }
  380. catch (const std::bad_alloc&)
  381. {
  382. ccLog::Warning("[Crop] Failed to transfer per-vertex features (color, SF values, etc.) on the output mesh (not enough memory)");
  383. croppedVertices->unallocateColors();
  384. croppedVertices->deleteAllScalarFields();
  385. }
  386. }
  387. }
  388. }
  389. else
  390. {
  391. ccLog::Warning("[Crop] Failed to create output mesh vertices (not enough memory)");
  392. }
  393. }
  394. //clean memory
  395. if (params.insideMesh)
  396. {
  397. delete params.insideMesh;
  398. params.insideMesh = nullptr;
  399. }
  400. if (params.outsideMesh)
  401. {
  402. delete params.outsideMesh;
  403. params.outsideMesh = nullptr;
  404. }
  405. if (croppedMesh)
  406. {
  407. croppedMesh->setDisplay_recursive(entity->getDisplay());
  408. }
  409. return croppedMesh;
  410. }
  411. //unhandled entity
  412. ccLog::Warning("[Crop] Unhandled entity type");
  413. return nullptr;
  414. }