ccRasterizeTool.cpp 72 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317
  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 "ccRasterizeTool.h"
  18. #include "ui_rasterizeDlg.h"
  19. //Local
  20. #include "ccCommon.h"
  21. #include "ccPersistentSettings.h"
  22. #include "ccContourLinesGenerator.h"
  23. #include "mainwindow.h"
  24. #include "ccKrigingParamsDialog.h"
  25. //qCC_db
  26. #include <ccColorScalesManager.h>
  27. #include <ccFileUtils.h>
  28. #include <ccGenericPointCloud.h>
  29. #include <ccMesh.h>
  30. #include <ccPointCloud.h>
  31. #include <ccPolyline.h>
  32. #include <ccProgressDialog.h>
  33. #include <ccScalarField.h>
  34. //qCC_gl
  35. #include <ccGLWindowInterface.h>
  36. //qCC_io
  37. #include <ImageFileFilter.h>
  38. //Qt
  39. #include <QFileDialog>
  40. #include <QMap>
  41. #include <QMessageBox>
  42. #include <QPushButton>
  43. #include <QSettings>
  44. #include <QStandardItemModel>
  45. #include <QInputDialog>
  46. #ifdef CC_GDAL_SUPPORT
  47. //GDAL
  48. #include <cpl_string.h>
  49. #include <gdal.h>
  50. #include <gdal_priv.h>
  51. #include <ogr_api.h>
  52. //local
  53. #include "ui_rasterExportOptionsDlg.h"
  54. #endif
  55. //System
  56. #include <cassert>
  57. constexpr char HILLSHADE_FIELD_NAME[] = "Hillshade";
  58. static void MakeComboBoxOptionInaccessible(QComboBox* comboBox, int index)
  59. {
  60. if (!comboBox)
  61. {
  62. assert(false);
  63. return;
  64. }
  65. const QStandardItemModel* model = qobject_cast<const QStandardItemModel*>(comboBox->model());
  66. QStandardItem* item = model ? model->item(index) : 0;
  67. if (item)
  68. {
  69. item->setFlags(item->flags() & ~(Qt::ItemIsSelectable | Qt::ItemIsEnabled));
  70. // visually disable by greying out - works only if combobox has been painted already and palette returns the wanted color
  71. item->setData(comboBox->palette().color(QPalette::Disabled, QPalette::Text), Qt::TextColorRole); // clear item data in order to use default color
  72. }
  73. }
  74. ccRasterizeTool::ccRasterizeTool(ccGenericPointCloud* cloud, QWidget* parent)
  75. : QDialog(parent, Qt::WindowMaximizeButtonHint | Qt::WindowCloseButtonHint)
  76. , cc2Point5DimEditor()
  77. , m_UI( new Ui::RasterizeToolDialog )
  78. , m_cloud(cloud)
  79. , m_cloudHasScalarFields(false)
  80. {
  81. m_UI->setupUi(this);
  82. #ifdef CC_GDAL_SUPPORT
  83. m_UI->ignoreContourBordersCheckBox->setVisible(false);
  84. #else
  85. m_UI->generateRasterPushButton->setDisabled(true);
  86. m_UI->generateRasterPushButton->setChecked(false);
  87. #endif
  88. //custom bbox editor (needs to be setup first)
  89. ccBBox gridBBox = m_cloud ? m_cloud->getOwnBB() : ccBBox();
  90. if (gridBBox.isValid())
  91. {
  92. createBoundingBoxEditor(gridBBox, this);
  93. connect(m_UI->editGridToolButton, &QAbstractButton::clicked, this, &ccRasterizeTool::showGridBoxEditor);
  94. }
  95. else
  96. {
  97. m_UI->editGridToolButton->setEnabled(false);
  98. }
  99. //force update
  100. resampleOptionToggled(m_UI->resampleCloudCheckBox->isChecked());
  101. fillEmptyCellStrategyChanged(0);
  102. connect(m_UI->buttonBox, &QDialogButtonBox::accepted, this, &ccRasterizeTool::testAndAccept);
  103. connect(m_UI->buttonBox, &QDialogButtonBox::rejected, this, &ccRasterizeTool::testAndReject);
  104. connect(m_UI->gridStepDoubleSpinBox, qOverload<double>(&QDoubleSpinBox::valueChanged), this, &ccRasterizeTool::updateGridInfo);
  105. connect(m_UI->gridStepDoubleSpinBox, qOverload<double>(&QDoubleSpinBox::valueChanged), this, &ccRasterizeTool::gridOptionChanged);
  106. connect(m_UI->emptyValueDoubleSpinBox, qOverload<double>(&QDoubleSpinBox::valueChanged), this, &ccRasterizeTool::gridOptionChanged);
  107. connect(m_UI->dimensionComboBox, qOverload<int>(&QComboBox::currentIndexChanged), this, &ccRasterizeTool::projectionDirChanged);
  108. connect(m_UI->heightProjectionComboBox, qOverload<int>(&QComboBox::currentIndexChanged), this, &ccRasterizeTool::projectionTypeChanged);
  109. connect(m_UI->scalarFieldProjection, qOverload<int>(&QComboBox::currentIndexChanged), this, &ccRasterizeTool::sfProjectionTypeChanged);
  110. connect(m_UI->fillEmptyCellsComboBox, qOverload<int>(&QComboBox::currentIndexChanged), this, &ccRasterizeTool::fillEmptyCellStrategyChanged);
  111. connect(m_UI->stdDevLayerComboBox, qOverload<int>(&QComboBox::currentIndexChanged), this, &ccRasterizeTool::stdDevLayerChanged);
  112. connect(m_UI->activeLayerComboBox, qOverload<int>(&QComboBox::currentIndexChanged), this, [this] (int index) { activeLayerChanged( index ); } );
  113. connect(m_UI->resampleCloudCheckBox, &QAbstractButton::toggled, this, &ccRasterizeTool::resampleOptionToggled);
  114. connect(m_UI->updateGridPushButton, &QAbstractButton::clicked, this, &ccRasterizeTool::updateGridAndDisplay);
  115. connect(m_UI->generateCloudPushButton, &QAbstractButton::clicked, this, [this] () { generateCloud(true); } );
  116. connect(m_UI->generateImagePushButton, &QAbstractButton::clicked, this, &ccRasterizeTool::generateImage);
  117. connect(m_UI->generateRasterPushButton, &QAbstractButton::clicked, this, &ccRasterizeTool::generateRaster);
  118. connect(m_UI->generateASCIIPushButton, &QAbstractButton::clicked, this, &ccRasterizeTool::generateASCIIMatrix);
  119. connect(m_UI->generateMeshPushButton, &QAbstractButton::clicked, this, &ccRasterizeTool::generateMesh);
  120. connect(m_UI->generateContoursPushButton, &QAbstractButton::clicked, this, &ccRasterizeTool::generateContours);
  121. connect(m_UI->exportContoursPushButton, &QAbstractButton::clicked, this, &ccRasterizeTool::exportContourLines);
  122. connect(m_UI->clearContoursPushButton, &QAbstractButton::clicked, this, &ccRasterizeTool::removeContourLines);
  123. connect(m_UI->generateHillshadePushButton, &QAbstractButton::clicked, this, &ccRasterizeTool::generateHillshade);
  124. connect(m_UI->interpParamsToolButton, &QAbstractButton::clicked, this, &ccRasterizeTool::showInterpolationParamsDialog);
  125. connect(m_UI->exportHeightStatsCheckBox, &QCheckBox::toggled, this, &ccRasterizeTool::onStatExportTargetChanged);
  126. connect(m_UI->exportSFStatsCheckBox, &QCheckBox::toggled, this, &ccRasterizeTool::onStatExportTargetChanged);
  127. if (m_cloud)
  128. {
  129. //populate layer box
  130. m_UI->activeLayerComboBox->addItem(ccRasterGrid::GetDefaultFieldName(ccRasterGrid::PER_CELL_VALUE), QVariant(LAYER_HEIGHT));
  131. if (m_cloud->hasColors())
  132. {
  133. m_UI->activeLayerComboBox->addItem("RGB", QVariant(LAYER_RGB));
  134. }
  135. if (cloud->isA(CC_TYPES::POINT_CLOUD) && cloud->hasScalarFields())
  136. {
  137. ccPointCloud* pc = static_cast<ccPointCloud*>(cloud);
  138. for (unsigned i = 0; i < pc->getNumberOfScalarFields(); ++i)
  139. {
  140. m_UI->activeLayerComboBox->addItem(QString::fromStdString(pc->getScalarField(i)->getName()), QVariant(LAYER_SF));
  141. //populate std. dev. layer box as well
  142. m_UI->stdDevLayerComboBox->addItem(QString::fromStdString(pc->getScalarField(i)->getName()));
  143. }
  144. m_cloudHasScalarFields = true;
  145. }
  146. //add window
  147. create2DView(m_UI->mapFrame);
  148. }
  149. if (!m_cloudHasScalarFields)
  150. {
  151. m_UI->projectSFCheckBox->setChecked(false);
  152. MakeComboBoxOptionInaccessible(m_UI->heightProjectionComboBox, ccRasterGrid::PROJ_INVERSE_VAR_VALUE);
  153. MakeComboBoxOptionInaccessible(m_UI->scalarFieldProjection, ccRasterGrid::PROJ_INVERSE_VAR_VALUE);
  154. }
  155. m_UI->projectSFCheckBox->setEnabled(m_cloudHasScalarFields);
  156. m_UI->scalarFieldProjection->setEnabled(m_cloudHasScalarFields);
  157. m_UI->stdDevLayerComboBox->setEnabled(m_cloudHasScalarFields); // real state will be set later (--> updateStdDevLayerComboBox)
  158. m_UI->exportSFStatsCheckBox->setEnabled(m_cloudHasScalarFields);
  159. loadSettings();
  160. updateStdDevLayerComboBox();
  161. gridIsUpToDate(false); // will call updateGridInfo
  162. resize(minimumSize());
  163. }
  164. ccRasterizeTool::~ccRasterizeTool()
  165. {
  166. removeContourLines();
  167. delete m_UI;
  168. m_UI = nullptr;
  169. }
  170. void ccRasterizeTool::removeContourLines()
  171. {
  172. while (!m_contourLines.empty())
  173. {
  174. ccPolyline* poly = m_contourLines.back();
  175. if (m_glWindow)
  176. m_glWindow->removeFromOwnDB(poly);
  177. delete poly;
  178. m_contourLines.pop_back();
  179. }
  180. m_UI->exportContoursPushButton->setEnabled(false);
  181. m_UI->clearContoursPushButton->setEnabled(false);
  182. if (m_glWindow)
  183. m_glWindow->redraw();
  184. }
  185. bool ccRasterizeTool::showGridBoxEditor()
  186. {
  187. return cc2Point5DimEditor::showGridBoxEditor();
  188. }
  189. void ccRasterizeTool::updateCloudName(bool withNonEmptyCells)
  190. {
  191. QString str;
  192. if (m_cloud)
  193. {
  194. str = QString("<b>%1</b> (%2 points").arg(m_cloud->getName(), QLocale::system().toString(m_cloud->size()));
  195. if (withNonEmptyCells)
  196. str += QString(" - %1 non-empty cells)").arg(QLocale::system().toString(m_grid.validCellCount));
  197. else
  198. str += ')';
  199. }
  200. else
  201. {
  202. str = "No cloud loaded";
  203. }
  204. m_UI->cloudNameLabel->setText(str);
  205. }
  206. void ccRasterizeTool::updateGridInfo(bool withNonEmptyCells/*=false*/)
  207. {
  208. m_UI->gridWidthLabel->setText(getGridSizeAsString());
  209. updateCloudName(withNonEmptyCells);
  210. }
  211. double ccRasterizeTool::getGridStep() const
  212. {
  213. return m_UI->gridStepDoubleSpinBox->value();
  214. }
  215. void ccRasterizeTool::getExportedStats(std::vector<ccRasterGrid::ExportableFields>& stats) const
  216. {
  217. stats.clear();
  218. stats.push_back(ccRasterGrid::PER_CELL_VALUE);
  219. if (m_UI->generateStatisticsPopulationCheckBox->isChecked())
  220. stats.push_back(ccRasterGrid::PER_CELL_COUNT);
  221. if (m_UI->generateStatisticsMinCheckBox->isChecked())
  222. stats.push_back(ccRasterGrid::PER_CELL_MIN_VALUE);
  223. if (m_UI->generateStatisticsMaxCheckBox->isChecked())
  224. stats.push_back(ccRasterGrid::PER_CELL_MAX_VALUE);
  225. if (m_UI->generateStatisticsAverageCheckBox->isChecked())
  226. stats.push_back(ccRasterGrid::PER_CELL_AVG_VALUE);
  227. if (m_UI->generateStatisticsStdDevCheckBox->isChecked())
  228. stats.push_back(ccRasterGrid::PER_CELL_VALUE_STD_DEV);
  229. if (m_UI->generateStatisticsRangeCheckBox->isChecked())
  230. stats.push_back(ccRasterGrid::PER_CELL_VALUE_RANGE);
  231. if (m_UI->generateStatisticsMedianCheckBox->isChecked())
  232. stats.push_back(ccRasterGrid::PER_CELL_MEDIAN_VALUE);
  233. if (m_UI->generateStatisticsUniqueCheckBox->isChecked())
  234. stats.push_back(ccRasterGrid::PER_CELL_UNIQUE_COUNT_VALUE);
  235. if (m_UI->generateStatisticsPercentileCheckBox->isChecked())
  236. stats.push_back(ccRasterGrid::PER_CELL_PERCENTILE_VALUE);
  237. }
  238. bool ccRasterizeTool::resampleOriginalCloud() const
  239. {
  240. return m_UI->resampleCloudCheckBox->isEnabled() && m_UI->resampleCloudCheckBox->isChecked();
  241. }
  242. unsigned char ccRasterizeTool::getProjectionDimension() const
  243. {
  244. int dim = m_UI->dimensionComboBox->currentIndex();
  245. assert(dim >= 0 && dim < 3);
  246. return static_cast<unsigned char>(dim);
  247. }
  248. int ccRasterizeTool::getStdDevLayerIndex() const
  249. {
  250. return m_UI->stdDevLayerComboBox->currentIndex();
  251. }
  252. void ccRasterizeTool::resampleOptionToggled(bool state)
  253. {
  254. m_UI->warningResampleWithAverageLabel->setVisible(m_UI->resampleCloudCheckBox->isChecked()
  255. && ( getTypeOfProjection() == ccRasterGrid::PROJ_AVERAGE_VALUE
  256. || getTypeOfProjection() == ccRasterGrid::PROJ_INVERSE_VAR_VALUE)
  257. );
  258. gridOptionChanged();
  259. }
  260. void ccRasterizeTool::updateStdDevLayerComboBox()
  261. {
  262. m_UI->stdDevLayerComboBox->setEnabled( m_UI->stdDevLayerComboBox->count() != 0
  263. && (m_UI->heightProjectionComboBox->currentIndex() == ccRasterGrid::PROJ_INVERSE_VAR_VALUE
  264. || m_UI->scalarFieldProjection->currentIndex() == ccRasterGrid::PROJ_INVERSE_VAR_VALUE) );
  265. }
  266. void ccRasterizeTool::projectionTypeChanged(int index)
  267. {
  268. //we can't use the 'resample origin cloud' option with 'average height' projection
  269. //resampleCloudCheckBox->setEnabled(index != PROJ_AVERAGE_VALUE && index != PROJ_INVERSE_VAR_VALUE);
  270. //DGM: now we can! We simply display a warning message
  271. m_UI->warningResampleWithAverageLabel->setVisible
  272. (
  273. m_UI->resampleCloudCheckBox->isChecked()
  274. && ( index == ccRasterGrid::PROJ_AVERAGE_VALUE
  275. || index == ccRasterGrid::PROJ_INVERSE_VAR_VALUE)
  276. );
  277. updateStdDevLayerComboBox();
  278. gridIsUpToDate(false);
  279. }
  280. void ccRasterizeTool::sfProjectionTypeChanged(int index)
  281. {
  282. updateStdDevLayerComboBox();
  283. gridIsUpToDate(false);
  284. }
  285. void ccRasterizeTool::projectionDirChanged(int dir)
  286. {
  287. gridIsUpToDate(false); // will call updateGridInfo
  288. }
  289. void ccRasterizeTool::stdDevLayerChanged(int index)
  290. {
  291. gridIsUpToDate(false);
  292. }
  293. void ccRasterizeTool::activeLayerChanged(int layerIndex, bool autoRedraw/*=true*/)
  294. {
  295. if (m_UI->activeLayerComboBox->itemData(layerIndex).toInt() == LAYER_SF)
  296. {
  297. if (m_UI->activeLayerComboBox->itemText(layerIndex) != HILLSHADE_FIELD_NAME)
  298. {
  299. m_UI->projectSFCheckBox->setChecked(true); //force the choice of a SF projection strategy
  300. m_UI->projectSFCheckBox->setEnabled(false);
  301. m_UI->generateImagePushButton->setEnabled(true);
  302. m_UI->generateASCIIPushButton->setEnabled(false);
  303. m_UI->projectContoursOnAltCheckBox->setEnabled(true);
  304. }
  305. else
  306. {
  307. //m_UI->projectSFCheckBox->setChecked(false); //we shouldn't change that as it only impacts the other fields
  308. //m_UI->projectSFCheckBox->setEnabled(false);
  309. m_UI->generateImagePushButton->setEnabled(false);
  310. m_UI->generateASCIIPushButton->setEnabled(false);
  311. m_UI->projectContoursOnAltCheckBox->setEnabled(false);
  312. }
  313. }
  314. else
  315. {
  316. //m_UI->projectSFCheckBox->setChecked(false); //DGM: we can't force that, just let the user decide
  317. m_UI->projectSFCheckBox->setEnabled(m_cloudHasScalarFields); //we need SF fields!
  318. m_UI->generateImagePushButton->setEnabled(true);
  319. m_UI->generateASCIIPushButton->setEnabled(true);
  320. m_UI->projectContoursOnAltCheckBox->setEnabled(false);
  321. }
  322. if (m_rasterCloud)
  323. {
  324. //active layer = RGB colors
  325. if (m_UI->activeLayerComboBox->currentData().toInt() == LAYER_RGB)
  326. {
  327. if (!m_rasterCloud->hasColors())
  328. {
  329. gridIsUpToDate(false);
  330. }
  331. m_UI->gridLayerRangeLabel->setText("[0 ; 255]");
  332. m_rasterCloud->showColors(true);
  333. m_rasterCloud->showSF(false);
  334. }
  335. else
  336. {
  337. //does the selected 'layer' exist?
  338. int sfIndex = m_rasterCloud->getScalarFieldIndexByName(m_UI->activeLayerComboBox->itemText(layerIndex).toStdString());
  339. m_rasterCloud->setCurrentDisplayedScalarField(sfIndex);
  340. m_rasterCloud->showSF(true);
  341. m_rasterCloud->showColors(false);
  342. if (sfIndex >= 0)
  343. {
  344. ccScalarField* activeLayer = m_rasterCloud->getCurrentDisplayedScalarField();
  345. if (activeLayer)
  346. {
  347. const ccScalarField::Range& layerValues = activeLayer->displayRange();
  348. m_UI->gridLayerRangeLabel->setText(QString("%1 [%2 ; %3]").arg(layerValues.range()).arg(layerValues.min()).arg(layerValues.max()));
  349. m_UI->contourStartDoubleSpinBox->setValue(layerValues.min());
  350. m_UI->contourStepDoubleSpinBox->setValue(layerValues.range() / 10.0);
  351. }
  352. else
  353. {
  354. assert(false);
  355. m_UI->gridLayerRangeLabel->setText("no active layer?!");
  356. }
  357. }
  358. else
  359. {
  360. m_UI->gridLayerRangeLabel->setText("Layer not computed");
  361. gridIsUpToDate(false);
  362. }
  363. }
  364. if (m_glWindow && autoRedraw)
  365. {
  366. m_glWindow->redraw();
  367. }
  368. }
  369. }
  370. void ccRasterizeTool::fillEmptyCellStrategyChanged(int)
  371. {
  372. ccRasterGrid::EmptyCellFillOption fillEmptyCellsStrategy = getFillEmptyCellsStrategy(m_UI->fillEmptyCellsComboBox);
  373. // empty cell value
  374. {
  375. bool active = (fillEmptyCellsStrategy == ccRasterGrid::FILL_CUSTOM_HEIGHT) || (fillEmptyCellsStrategy == ccRasterGrid::INTERPOLATE_DELAUNAY);
  376. m_UI->emptyValueDoubleSpinBox->setEnabled(active);
  377. m_UI->emptyValueDoubleSpinBox->setVisible(active);
  378. }
  379. // interpolation parameters button
  380. {
  381. m_UI->interpParamsToolButton->setEnabled(fillEmptyCellsStrategy == ccRasterGrid::INTERPOLATE_DELAUNAY || fillEmptyCellsStrategy == ccRasterGrid::KRIGING);
  382. }
  383. gridIsUpToDate(false);
  384. }
  385. void ccRasterizeTool::gridOptionChanged()
  386. {
  387. gridIsUpToDate(false);
  388. }
  389. double ccRasterizeTool::getCustomHeightForEmptyCells() const
  390. {
  391. return m_UI->emptyValueDoubleSpinBox->value();
  392. }
  393. double ccRasterizeTool::getStatisticsPercentileValue() const
  394. {
  395. return m_UI->generateStatisticsPercentileDoubleSpinBox->value();
  396. }
  397. ccRasterGrid::ProjectionType ccRasterizeTool::getTypeOfProjection() const
  398. {
  399. switch (m_UI->heightProjectionComboBox->currentIndex())
  400. {
  401. case 0:
  402. return ccRasterGrid::PROJ_MINIMUM_VALUE;
  403. case 1:
  404. return ccRasterGrid::PROJ_AVERAGE_VALUE;
  405. case 2:
  406. return ccRasterGrid::PROJ_MAXIMUM_VALUE;
  407. case 3:
  408. return ccRasterGrid::PROJ_MEDIAN_VALUE;
  409. case 4:
  410. return ccRasterGrid::PROJ_INVERSE_VAR_VALUE;
  411. default:
  412. //shouldn't be possible for this option!
  413. assert(false);
  414. }
  415. return ccRasterGrid::INVALID_PROJECTION_TYPE;
  416. }
  417. ccRasterGrid::ProjectionType ccRasterizeTool::getTypeOfSFProjection() const
  418. {
  419. if (/*!m_UI->projectSFCheckBox->isEnabled() || */!m_UI->projectSFCheckBox->isChecked()) //DGM: the check-box might be disabled to actually 'force' the user to choose a projection type
  420. {
  421. return ccRasterGrid::INVALID_PROJECTION_TYPE; //means that we don't want to project SF values
  422. }
  423. switch (m_UI->scalarFieldProjection->currentIndex())
  424. {
  425. case 0:
  426. return ccRasterGrid::PROJ_MINIMUM_VALUE;
  427. case 1:
  428. return ccRasterGrid::PROJ_AVERAGE_VALUE;
  429. case 2:
  430. return ccRasterGrid::PROJ_MAXIMUM_VALUE;
  431. case 3:
  432. return ccRasterGrid::PROJ_MEDIAN_VALUE;
  433. case 4:
  434. return ccRasterGrid::PROJ_INVERSE_VAR_VALUE;
  435. default:
  436. //shouldn't be possible for this option!
  437. assert(false);
  438. }
  439. return ccRasterGrid::INVALID_PROJECTION_TYPE;
  440. }
  441. void ccRasterizeTool::loadSettings()
  442. {
  443. QSettings settings;
  444. settings.beginGroup(ccPS::HeightGridGeneration());
  445. int projType = settings.value("ProjectionType", m_UI->heightProjectionComboBox->currentIndex()).toInt();
  446. int projDim = settings.value("ProjectionDim", m_UI->dimensionComboBox->currentIndex()).toInt();
  447. bool sfProj = settings.value("SfProjEnabled", m_UI->projectSFCheckBox->isChecked()).toBool();
  448. int sfProjStrategy = settings.value("SfProjStrategy", m_UI->scalarFieldProjection->currentIndex()).toInt();
  449. int fillStrategy = settings.value("FillStrategy", m_UI->fillEmptyCellsComboBox->currentIndex()).toInt();
  450. m_delaunayInterpParams.maxEdgeLength = settings.value("MaxEdgeLength", m_delaunayInterpParams.maxEdgeLength).toDouble();
  451. m_krigingParams.kNN = settings.value("KrigingKNN", m_krigingParams.kNN).toDouble();
  452. double step = settings.value("GridStep", m_UI->gridStepDoubleSpinBox->value()).toDouble();
  453. double emptyHeight = settings.value("EmptyCellsHeight", m_UI->emptyValueDoubleSpinBox->value()).toDouble();
  454. bool resampleCloud = settings.value("ResampleOrigCloud", m_UI->resampleCloudCheckBox->isChecked()).toBool();
  455. int minVertexCount = settings.value("MinVertexCount", m_UI->minVertexCountSpinBox->value()).toInt();
  456. bool ignoreBorders = settings.value("IgnoreBorders", m_UI->ignoreContourBordersCheckBox->isChecked()).toBool();
  457. bool projectContoursOnAlt = settings.value("projectContoursOnAlt", m_UI->projectContoursOnAltCheckBox->isChecked()).toBool();
  458. //Statistics checkboxes
  459. bool generateHeightStatistics = settings.value("GenerateHeightStatistics", m_UI->exportHeightStatsCheckBox->isChecked()).toBool();
  460. bool generateSFStatistics = settings.value("GenerateSFStatistics", m_UI->exportSFStatsCheckBox->isChecked()).toBool();
  461. bool generateStatisticsPopulation = settings.value("GenerateStatisticsPopulation", m_UI->generateStatisticsPopulationCheckBox->isChecked()).toBool();
  462. bool generateStatisticsMin = settings.value("GenerateStatisticsMin", m_UI->generateStatisticsMinCheckBox->isChecked()).toBool();
  463. bool generateStatisticsMax = settings.value("GenerateStatisticsMax", m_UI->generateStatisticsMaxCheckBox->isChecked()).toBool();
  464. bool generateStatisticsAverage = settings.value("GenerateStatisticsAverage", m_UI->generateStatisticsAverageCheckBox->isChecked()).toBool();
  465. bool generateStatisticsStdDev = settings.value("GenerateStatisticsStdDev", m_UI->generateStatisticsStdDevCheckBox->isChecked()).toBool();
  466. bool generateStatisticsRange = settings.value("GenerateStatisticsRange", m_UI->generateStatisticsRangeCheckBox->isChecked()).toBool();
  467. bool generateStatisticsMedian = settings.value("GenerateStatisticsMedian", m_UI->generateStatisticsMedianCheckBox->isChecked()).toBool();
  468. bool generateStatisticsUnique = settings.value("GenerateStatisticsUnique", m_UI->generateStatisticsUniqueCheckBox->isChecked()).toBool();
  469. bool generateStatisticsPercentile = settings.value("GenerateStatisticsPercentile", m_UI->generateStatisticsPercentileCheckBox->isChecked()).toBool();
  470. double generateStatisticsPercentileValue = settings.value("GenerateStatisticsPercentileValue", m_UI->generateStatisticsPercentileDoubleSpinBox->value()).toDouble();
  471. settings.endGroup();
  472. m_UI->gridStepDoubleSpinBox->setValue(step);
  473. m_UI->heightProjectionComboBox->setCurrentIndex(m_cloudHasScalarFields || projType != ccRasterGrid::PROJ_INVERSE_VAR_VALUE ? projType : 0);
  474. m_UI->fillEmptyCellsComboBox->setCurrentIndex(fillStrategy);
  475. m_UI->emptyValueDoubleSpinBox->setValue(emptyHeight);
  476. m_UI->dimensionComboBox->setCurrentIndex(projDim);
  477. m_UI->projectSFCheckBox->setChecked(m_cloudHasScalarFields && sfProj);
  478. m_UI->scalarFieldProjection->setCurrentIndex(m_cloudHasScalarFields || sfProjStrategy != ccRasterGrid::PROJ_INVERSE_VAR_VALUE ? sfProjStrategy : 0);
  479. m_UI->resampleCloudCheckBox->setChecked(resampleCloud);
  480. m_UI->minVertexCountSpinBox->setValue(minVertexCount);
  481. m_UI->ignoreContourBordersCheckBox->setChecked(ignoreBorders);
  482. m_UI->projectContoursOnAltCheckBox->setChecked(projectContoursOnAlt);
  483. //SF Statistics checkboxes
  484. m_UI->exportHeightStatsCheckBox->setChecked( generateHeightStatistics );
  485. m_UI->exportSFStatsCheckBox->setChecked( generateSFStatistics && m_cloudHasScalarFields );
  486. m_UI->generateStatisticsPopulationCheckBox->setChecked( generateStatisticsPopulation );
  487. m_UI->generateStatisticsMinCheckBox->setChecked( generateStatisticsMin );
  488. m_UI->generateStatisticsMaxCheckBox->setChecked( generateStatisticsMax );
  489. m_UI->generateStatisticsAverageCheckBox->setChecked( generateStatisticsAverage );
  490. m_UI->generateStatisticsStdDevCheckBox->setChecked( generateStatisticsStdDev );
  491. m_UI->generateStatisticsRangeCheckBox->setChecked( generateStatisticsRange );
  492. m_UI->generateStatisticsMedianCheckBox->setChecked( generateStatisticsMedian );
  493. m_UI->generateStatisticsUniqueCheckBox->setChecked( generateStatisticsUnique );
  494. m_UI->generateStatisticsPercentileCheckBox->setChecked( generateStatisticsPercentile );
  495. m_UI->generateStatisticsPercentileDoubleSpinBox->setValue( generateStatisticsPercentileValue );
  496. }
  497. bool ccRasterizeTool::canClose()
  498. {
  499. if (!m_contourLines.empty())
  500. {
  501. //ask the user to confirm before it's tool late!
  502. if (QMessageBox::question( this,
  503. "Unsaved contour lines",
  504. "Contour lines have not been exported! Do you really want to close the tool?",
  505. QMessageBox::Yes,
  506. QMessageBox::No) == QMessageBox::No)
  507. return false;
  508. }
  509. return true;
  510. }
  511. void ccRasterizeTool::testAndAccept()
  512. {
  513. if (!canClose())
  514. return;
  515. saveSettings();
  516. accept();
  517. }
  518. void ccRasterizeTool::testAndReject()
  519. {
  520. if (!canClose())
  521. return;
  522. reject();
  523. }
  524. void ccRasterizeTool::saveSettings()
  525. {
  526. QSettings settings;
  527. settings.beginGroup(ccPS::HeightGridGeneration());
  528. settings.setValue("ProjectionType", m_UI->heightProjectionComboBox->currentIndex());
  529. settings.setValue("ProjectionDim", m_UI->dimensionComboBox->currentIndex());
  530. settings.setValue("SfProjEnabled", m_UI->projectSFCheckBox->isChecked());
  531. settings.setValue("SfProjStrategy", m_UI->scalarFieldProjection->currentIndex());
  532. settings.setValue("FillStrategy", m_UI->fillEmptyCellsComboBox->currentIndex());
  533. settings.setValue("MaxEdgeLength", m_delaunayInterpParams.maxEdgeLength);
  534. settings.setValue("KrigingKNN", m_krigingParams.kNN);
  535. settings.setValue("GridStep", m_UI->gridStepDoubleSpinBox->value());
  536. settings.setValue("EmptyCellsHeight", m_UI->emptyValueDoubleSpinBox->value());
  537. settings.setValue("ResampleOrigCloud", m_UI->resampleCloudCheckBox->isChecked());
  538. settings.setValue("MinVertexCount", m_UI->minVertexCountSpinBox->value());
  539. settings.setValue("IgnoreBorders", m_UI->ignoreContourBordersCheckBox->isChecked());
  540. settings.setValue("projectContoursOnAlt", m_UI->projectContoursOnAltCheckBox->isChecked());
  541. //SF Statistics checkboxes
  542. settings.setValue("generateStatisticsPopulation", m_UI->generateStatisticsPopulationCheckBox->isChecked());
  543. settings.setValue("generateStatisticsMin", m_UI->generateStatisticsMinCheckBox->isChecked());
  544. settings.setValue("generateStatisticsMax", m_UI->generateStatisticsMaxCheckBox->isChecked());
  545. settings.setValue("generateStatisticsAverage", m_UI->generateStatisticsAverageCheckBox->isChecked());
  546. settings.setValue("generateStatisticsStdDev", m_UI->generateStatisticsStdDevCheckBox->isChecked());
  547. settings.setValue("generateStatisticsRange", m_UI->generateStatisticsRangeCheckBox->isChecked());
  548. settings.setValue("generateStatisticsMedian", m_UI->generateStatisticsMedianCheckBox->isChecked());
  549. settings.setValue("generateStatisticsUnique", m_UI->generateStatisticsUniqueCheckBox->isChecked());
  550. settings.setValue("generateStatisticsPercentile", m_UI->generateStatisticsPercentileCheckBox->isChecked());
  551. settings.setValue("generateStatisticsPercentileValue", m_UI->generateStatisticsPercentileDoubleSpinBox->value());
  552. settings.endGroup();
  553. }
  554. void ccRasterizeTool::gridIsUpToDate(bool state)
  555. {
  556. if (state)
  557. {
  558. //standard button
  559. m_UI->updateGridPushButton->setStyleSheet(QString());
  560. }
  561. else
  562. {
  563. //red button
  564. m_UI->updateGridPushButton->setStyleSheet("color: white; background-color:red;");
  565. }
  566. m_UI->updateGridPushButton->setDisabled(state);
  567. m_UI->tabWidget->setEnabled(state);
  568. updateGridInfo(state);
  569. }
  570. ccPointCloud* ccRasterizeTool::convertGridToCloud( bool exportHeightStats,
  571. bool exportSFStats,
  572. const std::vector<ccRasterGrid::ExportableFields>& exportedStatistics,
  573. bool projectSFs,
  574. bool projectColors,
  575. bool copyHillshadeSF,
  576. const QString& activeSFName,
  577. double percentileValue,
  578. bool exportToOriginalCS,
  579. bool appendGridSizeToSFNames,
  580. ccProgressDialog* progressDialog/*=nullptr*/ ) const
  581. {
  582. if (!m_cloud || !m_grid.isValid())
  583. return nullptr;
  584. //call parent method
  585. ccPointCloud* cloudGrid = cc2Point5DimEditor::convertGridToCloud( exportHeightStats,
  586. exportSFStats,
  587. exportedStatistics,
  588. projectSFs,
  589. projectColors,
  590. /*resampleInputCloudXY=*/resampleOriginalCloud(),
  591. /*resampleInputCloudZ=*/getTypeOfProjection() != ccRasterGrid::PROJ_AVERAGE_VALUE,
  592. /*inputCloud=*/m_cloud,
  593. percentileValue,
  594. exportToOriginalCS,
  595. appendGridSizeToSFNames,
  596. progressDialog );
  597. //success?
  598. if (cloudGrid)
  599. {
  600. //add the hillshade SF
  601. if (copyHillshadeSF)
  602. {
  603. int hillshadeSFIdx = m_rasterCloud->getScalarFieldIndexByName(HILLSHADE_FIELD_NAME);
  604. if (hillshadeSFIdx >= 0)
  605. {
  606. CCCoreLib::ScalarField* hillshadeField = m_rasterCloud->getScalarField(hillshadeSFIdx);
  607. if (hillshadeField->currentSize() == cloudGrid->size())
  608. {
  609. try
  610. {
  611. ccScalarField* hillshadeClone = new ccScalarField(*static_cast<ccScalarField*>(hillshadeField));
  612. cloudGrid->addScalarField(hillshadeClone);
  613. }
  614. catch (const std::bad_alloc&)
  615. {
  616. ccLog::Warning("[Rasterize] Not enough memory to export the hillshade field");
  617. }
  618. }
  619. }
  620. }
  621. //currently displayed SF
  622. int activeSFIndex = cloudGrid->getScalarFieldIndexByName(activeSFName.toStdString());
  623. if (activeSFIndex < 0 && cloudGrid->getNumberOfScalarFields() != 0)
  624. {
  625. //if no SF is displayed, we should at least set a valid one (for later)
  626. activeSFIndex = 0;
  627. }
  628. cloudGrid->setCurrentDisplayedScalarField(activeSFIndex);
  629. cloudGrid->showColors(projectColors && cloudGrid->hasColors());
  630. cloudGrid->showSF(activeSFIndex >= 0);
  631. //don't forget the original shift
  632. cloudGrid->copyGlobalShiftAndScale(*m_cloud);
  633. }
  634. return cloudGrid;
  635. }
  636. void ccRasterizeTool::updateGridAndDisplay()
  637. {
  638. //special case: remove the (temporary) hillshade field entry
  639. int hillshadeIndex = m_UI->activeLayerComboBox->findText(HILLSHADE_FIELD_NAME);
  640. if (hillshadeIndex >= 0)
  641. {
  642. if (m_UI->activeLayerComboBox->currentIndex() == hillshadeIndex && m_UI->activeLayerComboBox->count() > 1)
  643. {
  644. m_UI->activeLayerComboBox->setCurrentIndex(0);
  645. }
  646. m_UI->activeLayerComboBox->removeItem(hillshadeIndex);
  647. }
  648. //remove the previous cloud
  649. if (m_rasterCloud)
  650. {
  651. if (m_glWindow)
  652. {
  653. m_glWindow->removeFromOwnDB(m_rasterCloud);
  654. m_glWindow->redraw();
  655. }
  656. delete m_rasterCloud;
  657. m_rasterCloud = nullptr;
  658. }
  659. bool activeLayerIsSF = (m_UI->activeLayerComboBox->currentData().toInt() == LAYER_SF);
  660. bool projectSFs = (getTypeOfSFProjection() != ccRasterGrid::INVALID_PROJECTION_TYPE) || activeLayerIsSF;
  661. bool projectColors = m_cloud && m_cloud->hasColors();
  662. bool success = updateGrid(projectSFs);
  663. if (success && m_glWindow)
  664. {
  665. //convert grid to point cloud
  666. try
  667. {
  668. //we always compute the default 'height' layer
  669. std::vector<ccRasterGrid::ExportableFields> exportedStatistics(1);
  670. exportedStatistics.front() = ccRasterGrid::PER_CELL_VALUE;
  671. //but we may also have to compute the 'original SF(s)' layer(s)
  672. QString activeLayerName = m_UI->activeLayerComboBox->currentText();
  673. m_rasterCloud = convertGridToCloud( true,
  674. false,
  675. exportedStatistics,
  676. projectSFs,
  677. projectColors,
  678. /*copyHillshadeSF=*/false,
  679. activeLayerName,
  680. getStatisticsPercentileValue(),
  681. false,
  682. false,
  683. nullptr );
  684. // Special case: the 'LAYER_HEIGHT' field has now a dynamic name
  685. if (m_UI->activeLayerComboBox->currentIndex() == 0
  686. && m_rasterCloud
  687. && m_rasterCloud->getNumberOfScalarFields() != 0 )
  688. {
  689. assert(m_UI->activeLayerComboBox->itemData(0).toInt() == LAYER_HEIGHT);
  690. m_UI->activeLayerComboBox->setItemText(0, QString::fromStdString(m_rasterCloud->getScalarField(0)->getName()));
  691. }
  692. }
  693. catch (const std::bad_alloc&)
  694. {
  695. //see below
  696. }
  697. if (m_rasterCloud)
  698. {
  699. //just in case
  700. m_rasterCloud->setVisible(true);
  701. m_rasterCloud->setEnabled(true);
  702. m_glWindow->addToOwnDB(m_rasterCloud);
  703. ccBBox box = m_rasterCloud->getDisplayBB_recursive(false, m_glWindow);
  704. update2DDisplayZoom(box);
  705. //update
  706. activeLayerChanged(m_UI->activeLayerComboBox->currentIndex(), false);
  707. }
  708. else
  709. {
  710. ccLog::Error("Not enough memory!");
  711. m_glWindow->redraw();
  712. }
  713. }
  714. gridIsUpToDate(success);
  715. }
  716. bool ccRasterizeTool::updateGrid(bool projectSFs/*=false*/)
  717. {
  718. if (!m_cloud)
  719. {
  720. assert(false);
  721. return false;
  722. }
  723. //main parameters
  724. ccRasterGrid::ProjectionType projectionType = getTypeOfProjection();
  725. ccRasterGrid::ProjectionType sfProjectionType = projectSFs ? getTypeOfSFProjection() : ccRasterGrid::INVALID_PROJECTION_TYPE;
  726. ccRasterGrid::InterpolationType interpolationType = ccRasterGrid::InterpolationTypeFromEmptyCellFillOption(getFillEmptyCellsStrategy(m_UI->fillEmptyCellsComboBox));
  727. void* interpolationParams = nullptr;
  728. switch (interpolationType)
  729. {
  730. case ccRasterGrid::InterpolationType::DELAUNAY:
  731. interpolationParams = (void*)&m_delaunayInterpParams;
  732. break;
  733. case ccRasterGrid::InterpolationType::KRIGING:
  734. interpolationParams = (void*)&m_krigingParams;
  735. break;
  736. default:
  737. // do nothing
  738. break;
  739. }
  740. //cloud bounding-box --> grid size
  741. ccBBox box = getCustomBBox();
  742. if (!box.isValid())
  743. {
  744. return false;
  745. }
  746. //clear volume info
  747. {
  748. m_UI->volumeLabel->setText("0");
  749. m_UI->filledCellsPercentageLabel->setText("0 %");
  750. }
  751. unsigned gridWidth = 0;
  752. unsigned gridHeight = 0;
  753. if (!getGridSize(gridWidth, gridHeight))
  754. {
  755. return false;
  756. }
  757. //grid size
  758. unsigned gridTotalSize = gridWidth * gridHeight;
  759. if (gridTotalSize == 1)
  760. {
  761. if (QMessageBox::question( this,
  762. "Unexpected grid size",
  763. "The generated grid will only have 1 cell! Do you want to proceed anyway?",
  764. QMessageBox::Yes,
  765. QMessageBox::No) == QMessageBox::No)
  766. return false;
  767. }
  768. else if (gridTotalSize > 10000000)
  769. {
  770. if (QMessageBox::question( this,
  771. "Big grid size",
  772. "The generated grid will have more than 10.000.000 cells! Do you want to proceed anyway?",
  773. QMessageBox::Yes,
  774. QMessageBox::No) == QMessageBox::No)
  775. return false;
  776. }
  777. removeContourLines();
  778. //grid step
  779. double gridStep = getGridStep();
  780. assert(gridStep != 0);
  781. //memory allocation
  782. CCVector3d minCorner = box.minCorner();
  783. if (!m_grid.init(gridWidth, gridHeight, gridStep, minCorner))
  784. {
  785. //not enough memory
  786. ccLog::Error("Not enough memory");
  787. return false;
  788. }
  789. //vertical dimension
  790. const unsigned char Z = getProjectionDimension();
  791. assert(Z <= 2);
  792. int zStdDevSfIndex = getStdDevLayerIndex();
  793. ccProgressDialog pDlg(true, this);
  794. if (!m_grid.fillWith( m_cloud,
  795. Z,
  796. projectionType,
  797. interpolationType,
  798. interpolationParams,
  799. sfProjectionType,
  800. &pDlg,
  801. zStdDevSfIndex))
  802. {
  803. return false;
  804. }
  805. //fill empty cells (if necessary)
  806. ccRasterGrid::EmptyCellFillOption fillEmptyCellsStrategy = getFillEmptyCellsStrategy(m_UI->fillEmptyCellsComboBox);
  807. double customEmptyCellsHeight = getCustomHeightForEmptyCells();
  808. m_grid.fillEmptyCells(fillEmptyCellsStrategy, customEmptyCellsHeight);
  809. //update volume estimate
  810. {
  811. double hSum = 0;
  812. unsigned filledCellCount = 0;
  813. for (unsigned j = 0; j < m_grid.height; ++j)
  814. {
  815. const ccRasterGrid::Row& row = m_grid.rows[j];
  816. for (unsigned i = 0; i < m_grid.width; ++i)
  817. {
  818. if (std::isfinite(row[i].h))
  819. {
  820. hSum += row[i].h;
  821. ++filledCellCount;
  822. }
  823. }
  824. }
  825. if (filledCellCount)
  826. {
  827. double cellArea = m_grid.gridStep * m_grid.gridStep;
  828. m_UI->volumeLabel->setText(QString::number(hSum * cellArea));
  829. m_UI->filledCellsPercentageLabel->setText(QString::number(static_cast<double>(100 * filledCellCount) / (m_grid.width * m_grid.height), 'f', 2) + " %");
  830. }
  831. }
  832. ccLog::Print(QString("[Rasterize] Current raster grid:\n\tSize: %1 x %2\n\tHeight values: [%3 ; %4]").arg(m_grid.width).arg(m_grid.height).arg(m_grid.minHeight).arg(m_grid.maxHeight));
  833. return true;
  834. }
  835. ccPointCloud* ccRasterizeTool::generateCloud(bool autoExport/*=true*/)
  836. {
  837. if (!m_cloud || !m_grid.isValid())
  838. {
  839. return nullptr;
  840. }
  841. //look for statistics fields (min,max,median,etc) fields to be exported
  842. std::vector<ccRasterGrid::ExportableFields> exportedStatistics;
  843. bool exportHeightStats = m_UI->exportHeightStatsCheckBox->isChecked();
  844. bool exportSFStats = m_UI->exportSFStatsCheckBox->isEnabled() && m_UI->exportSFStatsCheckBox->isChecked();
  845. if (exportHeightStats || exportSFStats)
  846. {
  847. try
  848. {
  849. getExportedStats(exportedStatistics);
  850. }
  851. catch (const std::bad_alloc&)
  852. {
  853. ccLog::Error("Not enough memory!");
  854. return nullptr;
  855. }
  856. }
  857. QString activeLayerName = m_UI->activeLayerComboBox->currentText();
  858. bool activeLayerIsSF = (m_UI->activeLayerComboBox->currentData().toInt() == LAYER_SF);
  859. bool projectSFs = (getTypeOfSFProjection() != ccRasterGrid::INVALID_PROJECTION_TYPE) || activeLayerIsSF;
  860. //bool activeLayerIsRGB = (activeLayerComboBox->currentData().toInt() == LAYER_RGB);
  861. bool projectColors = m_cloud->hasColors();
  862. ccProgressDialog pDlg(true, this);
  863. ccPointCloud* rasterCloud = convertGridToCloud( exportHeightStats,
  864. exportSFStats,
  865. exportedStatistics,
  866. projectSFs,
  867. projectColors,
  868. /*copyHillshadeSF=*/true,
  869. activeLayerName,
  870. getStatisticsPercentileValue(),
  871. true,
  872. true, // we want nicer SF names
  873. &pDlg );
  874. if (rasterCloud && autoExport)
  875. {
  876. if (m_cloud->getParent())
  877. {
  878. m_cloud->getParent()->addChild(rasterCloud);
  879. }
  880. rasterCloud->setDisplay(m_cloud->getDisplay());
  881. if (m_cloud->isEnabled())
  882. {
  883. m_cloud->setEnabled(false);
  884. ccLog::Warning("[Rasterize] Previously selected entity (source cloud) has been hidden!");
  885. }
  886. MainWindow* mainWindow = MainWindow::TheInstance();
  887. if (mainWindow)
  888. {
  889. mainWindow->addToDB(rasterCloud);
  890. ccLog::Print(QString("[Rasterize] Cloud '%1' successfully exported").arg(rasterCloud->getName()));
  891. }
  892. else
  893. {
  894. assert(false);
  895. delete rasterCloud;
  896. }
  897. }
  898. return rasterCloud;
  899. }
  900. void ccRasterizeTool::generateMesh()
  901. {
  902. if (!m_cloud)
  903. {
  904. assert(false);
  905. return;
  906. }
  907. ccPointCloud* rasterCloud = generateCloud(false);
  908. if (rasterCloud)
  909. {
  910. std::string errorStr;
  911. CCCoreLib::GenericIndexedMesh* baseMesh = CCCoreLib::PointProjectionTools::computeTriangulation(rasterCloud,
  912. CCCoreLib::DELAUNAY_2D_AXIS_ALIGNED,
  913. CCCoreLib::PointProjectionTools::IGNORE_MAX_EDGE_LENGTH,
  914. getProjectionDimension(),
  915. errorStr);
  916. ccMesh* rasterMesh = nullptr;
  917. if (baseMesh)
  918. {
  919. rasterMesh = new ccMesh(baseMesh, rasterCloud);
  920. delete baseMesh;
  921. baseMesh = nullptr;
  922. }
  923. if (rasterMesh)
  924. {
  925. if (m_cloud->getParent())
  926. m_cloud->getParent()->addChild(rasterMesh);
  927. rasterCloud->setEnabled(false);
  928. rasterCloud->setVisible(true);
  929. rasterCloud->setName("vertices");
  930. rasterMesh->addChild(rasterCloud);
  931. rasterMesh->setDisplay_recursive(m_cloud->getDisplay());
  932. rasterMesh->setName(m_cloud->getName() + ".mesh");
  933. rasterMesh->showSF(rasterCloud->sfShown());
  934. rasterMesh->showColors(rasterCloud->colorsShown());
  935. MainWindow* mainWindow = MainWindow::TheInstance();
  936. if (mainWindow)
  937. MainWindow::TheInstance()->addToDB(rasterMesh);
  938. ccLog::Print(QString("[Rasterize] Mesh '%1' successfully exported").arg(rasterMesh->getName()));
  939. }
  940. else
  941. {
  942. ccLog::Error( QStringLiteral("Failed to create mesh ('%1')")
  943. .arg( QString::fromStdString( errorStr ) ) );
  944. }
  945. }
  946. }
  947. #ifdef CC_GDAL_SUPPORT
  948. class RasterExportOptionsDlg
  949. : public QDialog
  950. , public Ui::RasterExportOptionsDialog
  951. {
  952. public:
  953. explicit RasterExportOptionsDlg(QWidget* parent = nullptr)
  954. : QDialog(parent, Qt::Tool)
  955. , Ui::RasterExportOptionsDialog()
  956. {
  957. setupUi(this);
  958. }
  959. };
  960. #endif
  961. void ccRasterizeTool::generateRaster() const
  962. {
  963. #ifdef CC_GDAL_SUPPORT
  964. if (!m_cloud || !m_grid.isValid())
  965. {
  966. return;
  967. }
  968. bool hasScalarFields = !m_grid.scalarFields.empty();
  969. int visibleSfIndex = -1;
  970. if (m_UI->activeLayerComboBox->currentData().toInt() == LAYER_SF && m_cloud->isA(CC_TYPES::POINT_CLOUD))
  971. {
  972. //the indexes in the 'm_grid.scalarFields' are the same as in the cloud
  973. visibleSfIndex = static_cast<ccPointCloud*>(m_cloud)->getScalarFieldIndexByName(m_UI->activeLayerComboBox->currentText().toStdString());
  974. }
  975. //which (and how many) bands shall we create?
  976. ExportBands exportBands;
  977. exportBands.height = true; //height by default
  978. exportBands.rgb = false; //not a good idea to mix RGB and height values!
  979. RasterExportOptionsDlg reoDlg;
  980. reoDlg.dimensionsLabel->setText(QString("%1 x %2").arg(m_grid.width).arg(m_grid.height));
  981. reoDlg.exportRGBCheckBox->setEnabled(m_grid.hasColors);
  982. reoDlg.exportRGBCheckBox->setChecked(exportBands.rgb);
  983. reoDlg.exportHeightsCheckBox->setChecked(exportBands.height);
  984. reoDlg.exportDensityCheckBox->setChecked(exportBands.density);
  985. reoDlg.exportActiveLayerCheckBox->setChecked(exportBands.visibleSF);
  986. reoDlg.exportActiveLayerCheckBox->setEnabled(visibleSfIndex >= 0);
  987. reoDlg.exportAllSFCheckBox->setEnabled(hasScalarFields);
  988. reoDlg.exportAllSFCheckBox->setChecked(exportBands.allSFs);
  989. while (true)
  990. {
  991. if (!reoDlg.exec())
  992. {
  993. //cancelled by user
  994. return;
  995. }
  996. //check the selection
  997. if ( reoDlg.exportRGBCheckBox->isEnabled()
  998. && reoDlg.exportRGBCheckBox->isChecked()
  999. && ( reoDlg.exportHeightsCheckBox->isChecked()
  1000. || reoDlg.exportDensityCheckBox->isChecked()
  1001. || reoDlg.exportActiveLayerCheckBox->isChecked()
  1002. || reoDlg.exportAllSFCheckBox->isChecked())
  1003. )
  1004. {
  1005. if (QMessageBox::warning( nullptr,
  1006. "Mixed raster",
  1007. "Mixing colors and other layers will result in\na strange raster file with 64 bits color bands\n(some applications won't handle them properly)",
  1008. QMessageBox::Ignore,
  1009. QMessageBox::Retry) == QMessageBox::Ignore)
  1010. {
  1011. //the user ignored the warning
  1012. break;
  1013. }
  1014. }
  1015. else
  1016. {
  1017. //nothing to worry about :D
  1018. break;
  1019. }
  1020. }
  1021. //we ask the output filename AFTER displaying the export parameters ;)
  1022. QString outputFilename;
  1023. {
  1024. QSettings settings;
  1025. settings.beginGroup(ccPS::HeightGridGeneration());
  1026. QString imageSavePath = settings.value("savePathImage", ccFileUtils::defaultDocPath()).toString();
  1027. outputFilename = QFileDialog::getSaveFileName( const_cast<ccRasterizeTool*>(this),
  1028. "Save height grid raster",
  1029. imageSavePath + QString("/raster.tif"),
  1030. "geotiff (*.tif)");
  1031. if (outputFilename.isNull())
  1032. {
  1033. return;
  1034. }
  1035. //save current export path to persistent settings
  1036. settings.setValue("savePathImage", QFileInfo(outputFilename).absolutePath());
  1037. }
  1038. exportBands.height = reoDlg.exportHeightsCheckBox->isChecked();
  1039. exportBands.rgb = reoDlg.exportRGBCheckBox->isChecked();
  1040. exportBands.density = reoDlg.exportDensityCheckBox->isChecked();
  1041. exportBands.allSFs = reoDlg.exportAllSFCheckBox->isChecked();
  1042. exportBands.visibleSF = reoDlg.exportActiveLayerCheckBox->isChecked();
  1043. ExportGeoTiff
  1044. (
  1045. outputFilename,
  1046. exportBands,
  1047. getFillEmptyCellsStrategy(m_UI->fillEmptyCellsComboBox),
  1048. m_grid,
  1049. getCustomBBox(),
  1050. getProjectionDimension(),
  1051. getCustomHeightForEmptyCells(),
  1052. m_cloud,
  1053. visibleSfIndex
  1054. );
  1055. #else
  1056. assert(false);
  1057. ccLog::Error("[Rasterize] GDAL not supported by this version! Can't generate a raster...");
  1058. #endif
  1059. }
  1060. bool ccRasterizeTool::ExportGeoTiff(const QString& outputFilename,
  1061. const ExportBands& exportBands,
  1062. ccRasterGrid::EmptyCellFillOption fillEmptyCellsStrategy,
  1063. const ccRasterGrid& grid,
  1064. const ccBBox& gridBBox,
  1065. unsigned char Z,
  1066. double customHeightForEmptyCells/*=std::numeric_limits<double>::quiet_NaN()*/,
  1067. ccGenericPointCloud* originCloud/*=nullptr*/,
  1068. int visibleSfIndex/*=-1*/)
  1069. {
  1070. #ifdef CC_GDAL_SUPPORT
  1071. if (exportBands.visibleSF && visibleSfIndex < 0)
  1072. {
  1073. assert(false);
  1074. return false;
  1075. }
  1076. //vertical dimension
  1077. assert(Z <= 2);
  1078. const unsigned char X = (Z == 2 ? 0 : Z + 1);
  1079. const unsigned char Y = (X == 2 ? 0 : X + 1);
  1080. double stepX = grid.gridStep;
  1081. double stepY = grid.gridStep;
  1082. //global shift
  1083. assert(gridBBox.isValid());
  1084. double shiftX = gridBBox.minCorner().u[X] - stepX / 2; //we will declare the raster grid as 'Pixel-is-area'!
  1085. double shiftY = gridBBox.maxCorner().u[Y] + stepY / 2; //we will declare the raster grid as 'Pixel-is-area'!
  1086. double shiftZ = 0.0;
  1087. if (originCloud)
  1088. {
  1089. const CCVector3d& shift = originCloud->getGlobalShift();
  1090. shiftX -= shift.u[X];
  1091. shiftY -= shift.u[Y];
  1092. shiftZ -= shift.u[Z];
  1093. double scale = originCloud->getGlobalScale();
  1094. assert(scale != 0);
  1095. stepX /= scale;
  1096. stepY /= scale;
  1097. }
  1098. int totalBands = 0;
  1099. bool onlyRGBA = true;
  1100. if (exportBands.height)
  1101. {
  1102. ++totalBands;
  1103. onlyRGBA = false;
  1104. }
  1105. bool rgbaMode = false;
  1106. if (exportBands.rgb)
  1107. {
  1108. totalBands += 3; //one per component
  1109. if (fillEmptyCellsStrategy == ccRasterGrid::LEAVE_EMPTY && grid.validCellCount < grid.height * grid.width)
  1110. {
  1111. rgbaMode = true;
  1112. ++totalBands; //alpha
  1113. }
  1114. }
  1115. else
  1116. {
  1117. onlyRGBA = false;
  1118. }
  1119. if (exportBands.density)
  1120. {
  1121. ++totalBands;
  1122. onlyRGBA = false;
  1123. }
  1124. if (exportBands.allSFs)
  1125. {
  1126. for (const auto & scalarField : grid.scalarFields)
  1127. {
  1128. if (!scalarField.empty())
  1129. {
  1130. ++totalBands;
  1131. onlyRGBA = false;
  1132. }
  1133. }
  1134. }
  1135. else if (exportBands.visibleSF && visibleSfIndex >= 0)
  1136. {
  1137. ++totalBands;
  1138. onlyRGBA = false;
  1139. }
  1140. if (totalBands == 0)
  1141. {
  1142. ccLog::Error("Can't output a raster with no band! (check export parameters)");
  1143. return false;
  1144. }
  1145. GDALAllRegister();
  1146. ccLog::PrintDebug("(GDAL drivers: %i)", GetGDALDriverManager()->GetDriverCount());
  1147. const char pszFormat[] = "GTiff";
  1148. GDALDriver* poDriver = GetGDALDriverManager()->GetDriverByName(pszFormat);
  1149. if (!poDriver)
  1150. {
  1151. ccLog::Error("[GDAL] Driver %s is not supported", pszFormat);
  1152. return false;
  1153. }
  1154. char** papszMetadata = poDriver->GetMetadata();
  1155. if (!CSLFetchBoolean(papszMetadata, GDAL_DCAP_CREATE, FALSE))
  1156. {
  1157. ccLog::Error("[GDAL] Driver %s doesn't support Create() method", pszFormat);
  1158. return false;
  1159. }
  1160. char **papszOptions = nullptr;
  1161. GDALDataset* poDstDS = poDriver->Create(qUtf8Printable(outputFilename),
  1162. static_cast<int>(grid.width),
  1163. static_cast<int>(grid.height),
  1164. totalBands,
  1165. onlyRGBA ? GDT_Byte : GDT_Float64,
  1166. papszOptions);
  1167. if (!poDstDS)
  1168. {
  1169. ccLog::Error("[GDAL] Failed to create output raster (not enough memory?)");
  1170. return false;
  1171. }
  1172. poDstDS->SetMetadataItem("AREA_OR_POINT", "AREA");
  1173. double adfGeoTransform[6] { shiftX, //top left x
  1174. stepX, //w-e pixel resolution (can be negative)
  1175. 0, //0
  1176. shiftY, //top left y
  1177. 0, //0
  1178. -stepY //n-s pixel resolution (can be negative)
  1179. };
  1180. poDstDS->SetGeoTransform( adfGeoTransform );
  1181. //OGRSpatialReference oSRS;
  1182. //oSRS.SetUTM( 11, TRUE );
  1183. //oSRS.SetWellKnownGeogCS( "NAD27" );
  1184. //char *pszSRS_WKT = nullptr;
  1185. //oSRS.exportToWkt( &pszSRS_WKT );
  1186. //poDstDS->SetProjection( pszSRS_WKT );
  1187. //CPLFree( pszSRS_WKT );
  1188. int currentBand = 0;
  1189. //exort RGB band?
  1190. if (exportBands.rgb)
  1191. {
  1192. GDALRasterBand* rgbBands[3] { poDstDS->GetRasterBand(++currentBand),
  1193. poDstDS->GetRasterBand(++currentBand),
  1194. poDstDS->GetRasterBand(++currentBand) };
  1195. rgbBands[0]->SetColorInterpretation(GCI_RedBand);
  1196. rgbBands[1]->SetColorInterpretation(GCI_GreenBand);
  1197. rgbBands[2]->SetColorInterpretation(GCI_BlueBand);
  1198. unsigned char* cLine = static_cast<unsigned char*>(CPLMalloc(sizeof(unsigned char)*grid.width));
  1199. if (!cLine)
  1200. {
  1201. ccLog::Error("[GDAL] Not enough memory");
  1202. GDALClose(poDstDS);
  1203. return false;
  1204. }
  1205. bool error = false;
  1206. //export the R, G and B components
  1207. for (unsigned k = 0; k < 3; ++k)
  1208. {
  1209. rgbBands[k]->SetStatistics(0, 255, 128, 0); //warning: arbitrary average and std. dev. values
  1210. for (unsigned j = 0; j < grid.height; ++j)
  1211. {
  1212. const ccRasterGrid::Row& row = grid.rows[grid.height - 1 - j]; //the first row is the northest one (i.e. Ymax)
  1213. for (unsigned i = 0; i < grid.width; ++i)
  1214. {
  1215. cLine[i] = (std::isfinite(row[i].h) ? static_cast<unsigned char>(std::max(0.0, std::min(255.0, row[i].color.u[k]))) : 0);
  1216. }
  1217. if (rgbBands[k]->RasterIO(GF_Write, 0, static_cast<int>(j), static_cast<int>(grid.width), 1, cLine, static_cast<int>(grid.width), 1, GDT_Byte, 0, 0) != CE_None)
  1218. {
  1219. error = true;
  1220. k = 3; //early stop
  1221. break;
  1222. }
  1223. }
  1224. }
  1225. //export the alpha band (if necessary)
  1226. if (!error && rgbaMode)
  1227. {
  1228. GDALRasterBand* aBand = poDstDS->GetRasterBand(++currentBand);
  1229. aBand->SetColorInterpretation(GCI_AlphaBand);
  1230. aBand->SetStatistics(0, 255, 255, 0); //warning: arbitrary average and std. dev. values
  1231. for (unsigned j = 0; j < grid.height; ++j)
  1232. {
  1233. const ccRasterGrid::Row& row = grid.rows[grid.height - 1 - j];
  1234. for (unsigned i = 0; i < grid.width; ++i)
  1235. {
  1236. cLine[i] = (std::isfinite(row[i].h) ? 255 : 0);
  1237. }
  1238. if (aBand->RasterIO(GF_Write, 0, static_cast<int>(j), static_cast<int>(grid.width), 1, cLine, static_cast<int>(grid.width), 1, GDT_Byte, 0, 0) != CE_None)
  1239. {
  1240. error = true;
  1241. break;
  1242. }
  1243. }
  1244. }
  1245. CPLFree(cLine);
  1246. if (error)
  1247. {
  1248. ccLog::Error("[GDAL] An error occurred while writing the color bands!");
  1249. GDALClose(poDstDS);
  1250. return false;
  1251. }
  1252. }
  1253. double* scanline = static_cast<double*>(CPLMalloc(sizeof(double)*grid.width));
  1254. if (!scanline)
  1255. {
  1256. ccLog::Error("[GDAL] Not enough memory");
  1257. GDALClose(poDstDS);
  1258. return false;
  1259. }
  1260. //exort height band?
  1261. if (exportBands.height)
  1262. {
  1263. GDALRasterBand* poBand = poDstDS->GetRasterBand(++currentBand);
  1264. assert(poBand);
  1265. poBand->SetColorInterpretation(GCI_Undefined);
  1266. double emptyCellHeight = 0.0;
  1267. switch (fillEmptyCellsStrategy)
  1268. {
  1269. case ccRasterGrid::LEAVE_EMPTY:
  1270. {
  1271. emptyCellHeight = std::numeric_limits<double>::quiet_NaN();
  1272. if (CE_None != poBand->SetNoDataValue(emptyCellHeight))
  1273. {
  1274. ccLog::Warning("[GDAL] Failed to set the No Data value");
  1275. }
  1276. break;
  1277. }
  1278. case ccRasterGrid::FILL_MINIMUM_HEIGHT:
  1279. emptyCellHeight = grid.minHeight;
  1280. break;
  1281. case ccRasterGrid::FILL_MAXIMUM_HEIGHT:
  1282. emptyCellHeight = grid.maxHeight;
  1283. break;
  1284. case ccRasterGrid::FILL_CUSTOM_HEIGHT:
  1285. case ccRasterGrid::INTERPOLATE_DELAUNAY:
  1286. emptyCellHeight = customHeightForEmptyCells;
  1287. break;
  1288. case ccRasterGrid::FILL_AVERAGE_HEIGHT:
  1289. emptyCellHeight = grid.meanHeight;
  1290. break;
  1291. default:
  1292. assert(false);
  1293. }
  1294. if (fillEmptyCellsStrategy != ccRasterGrid::LEAVE_EMPTY)
  1295. {
  1296. emptyCellHeight += shiftZ;
  1297. }
  1298. for (unsigned j = 0; j < grid.height; ++j)
  1299. {
  1300. const ccRasterGrid::Row& row = grid.rows[grid.height - 1 - j];
  1301. for (unsigned i = 0; i < grid.width; ++i)
  1302. {
  1303. scanline[i] = std::isfinite(row[i].h) ? row[i].h + shiftZ : emptyCellHeight;
  1304. }
  1305. if (poBand->RasterIO( GF_Write,
  1306. 0,
  1307. static_cast<int>(j),
  1308. static_cast<int>(grid.width),
  1309. 1,
  1310. scanline,
  1311. static_cast<int>(grid.width),
  1312. 1,
  1313. GDT_Float64,
  1314. 0,
  1315. 0) != CE_None)
  1316. {
  1317. ccLog::Error("[GDAL] An error occurred while writing the height band!");
  1318. if (scanline)
  1319. {
  1320. CPLFree(scanline);
  1321. }
  1322. GDALClose(poDstDS);
  1323. return false;
  1324. }
  1325. }
  1326. }
  1327. //export density band
  1328. if (exportBands.density)
  1329. {
  1330. GDALRasterBand* poBand = poDstDS->GetRasterBand(++currentBand);
  1331. assert(poBand);
  1332. poBand->SetColorInterpretation(GCI_Undefined);
  1333. for (unsigned j = 0; j < grid.height; ++j)
  1334. {
  1335. const ccRasterGrid::Row& row = grid.rows[grid.height - 1 - j];
  1336. for (unsigned i = 0; i < grid.width; ++i)
  1337. {
  1338. scanline[i] = row[i].nbPoints;
  1339. }
  1340. if (poBand->RasterIO( GF_Write,
  1341. 0,
  1342. static_cast<int>(j),
  1343. static_cast<int>(grid.width),
  1344. 1,
  1345. scanline,
  1346. static_cast<int>(grid.width),
  1347. 1,
  1348. GDT_Float64,
  1349. 0,
  1350. 0) != CE_None)
  1351. {
  1352. ccLog::Error("[GDAL] An error occurred while writing the density band!");
  1353. if (scanline)
  1354. {
  1355. CPLFree(scanline);
  1356. }
  1357. GDALClose(poDstDS);
  1358. return false;
  1359. }
  1360. }
  1361. }
  1362. //export SF bands
  1363. if (exportBands.allSFs || (exportBands.visibleSF && visibleSfIndex >= 0))
  1364. {
  1365. for (size_t k = 0; k < grid.scalarFields.size(); ++k)
  1366. {
  1367. assert(!grid.scalarFields[k].empty());
  1368. if (exportBands.allSFs || (exportBands.visibleSF && visibleSfIndex == static_cast<int>(k)))
  1369. {
  1370. const double* sfGrid = grid.scalarFields[k].data();
  1371. GDALRasterBand* poBand = poDstDS->GetRasterBand(++currentBand);
  1372. double sfNanValue = std::numeric_limits<ccRasterGrid::SF::value_type>::quiet_NaN();
  1373. poBand->SetNoDataValue(sfNanValue); //should be transparent!
  1374. assert(poBand);
  1375. poBand->SetColorInterpretation(GCI_Undefined);
  1376. for (unsigned j = 0; j < grid.height; ++j)
  1377. {
  1378. const ccRasterGrid::Row& row = grid.rows[grid.height - 1 - j];
  1379. const double* sfRow = sfGrid + (grid.height - 1 - j) * grid.width;
  1380. for (unsigned i = 0; i < grid.width; ++i)
  1381. {
  1382. scanline[i] = std::isfinite(sfRow[i]) ? sfRow[i] : sfNanValue;
  1383. }
  1384. if (poBand->RasterIO( GF_Write,
  1385. 0,
  1386. static_cast<int>(j),
  1387. static_cast<int>(grid.width),
  1388. 1,
  1389. scanline,
  1390. static_cast<int>(grid.width),
  1391. 1,
  1392. GDT_Float64,
  1393. 0,
  1394. 0 ) != CE_None)
  1395. {
  1396. //the corresponding SF should exist on the input cloud
  1397. ccLog::Error(QString("[GDAL] An error occurred while writing a scalar field band!"));
  1398. k = grid.scalarFields.size(); //quick stop
  1399. break;
  1400. }
  1401. }
  1402. }
  1403. }
  1404. }
  1405. if (scanline)
  1406. {
  1407. CPLFree(scanline);
  1408. }
  1409. scanline = nullptr;
  1410. /* Once we're done, close properly the dataset */
  1411. GDALClose(poDstDS);
  1412. ccLog::Print(QString("[Rasterize] Raster '%1' successfully saved").arg(outputFilename));
  1413. return true;
  1414. #else
  1415. assert(false);
  1416. ccLog::Error("[Rasterize] GDAL not supported by this version! Can't generate a raster...");
  1417. return false;
  1418. #endif
  1419. }
  1420. //See http://edndoc.esri.com/arcobjects/9.2/net/shared/geoprocessing/spatial_analyst_tools/how_hillshade_works.htm
  1421. void ccRasterizeTool::generateHillshade()
  1422. {
  1423. if (!m_grid.isValid() || !m_rasterCloud)
  1424. {
  1425. ccLog::Error("Need a valid raster/cloud to generate hillshade!");
  1426. return;
  1427. }
  1428. if (m_grid.height < 3 || m_grid.width < 3)
  1429. {
  1430. ccLog::Error("Grid is too small");
  1431. return;
  1432. }
  1433. //get/create layer
  1434. ccScalarField* hillshadeLayer = nullptr;
  1435. int sfIdx = m_rasterCloud->getScalarFieldIndexByName(HILLSHADE_FIELD_NAME);
  1436. if (sfIdx >= 0)
  1437. {
  1438. hillshadeLayer = static_cast<ccScalarField*>(m_rasterCloud->getScalarField(sfIdx));
  1439. }
  1440. else
  1441. {
  1442. hillshadeLayer = new ccScalarField(HILLSHADE_FIELD_NAME);
  1443. if (!hillshadeLayer->reserveSafe(m_rasterCloud->size()))
  1444. {
  1445. ccLog::Error("Not enough memory!");
  1446. hillshadeLayer->release();
  1447. hillshadeLayer = nullptr;
  1448. return;
  1449. }
  1450. sfIdx = m_rasterCloud->addScalarField(hillshadeLayer);
  1451. m_UI->activeLayerComboBox->addItem(HILLSHADE_FIELD_NAME, QVariant(LAYER_SF));
  1452. m_UI->activeLayerComboBox->setEnabled(true);
  1453. }
  1454. assert(hillshadeLayer && hillshadeLayer->currentSize() == m_rasterCloud->size());
  1455. hillshadeLayer->fill(CCCoreLib::NAN_VALUE);
  1456. bool sparseSF = (hillshadeLayer->currentSize() != m_grid.height * m_grid.width);
  1457. bool resampleInputCloudXY = resampleOriginalCloud();
  1458. //now we can compute the hillshade
  1459. int zenith_deg = m_UI->sunZenithSpinBox->value();
  1460. double zenith_rad = CCCoreLib::DegreesToRadians(static_cast<double>(zenith_deg));
  1461. double cos_zenith_rad = cos(zenith_rad);
  1462. double sin_zenith_rad = sin(zenith_rad);
  1463. int azimuth_deg = m_UI->sunAzimuthSpinBox->value();
  1464. int azimuth_math = 360 - azimuth_deg + 90;
  1465. double azimuth_rad = CCCoreLib::DegreesToRadians(static_cast<double>(azimuth_math));
  1466. //for all cells
  1467. unsigned nonEmptyCellIndex = 0;
  1468. unsigned validButEmptyCellIndex = 0;
  1469. for (unsigned j = 0; j < m_grid.height - 1; ++j)
  1470. {
  1471. const ccRasterGrid::Row& row = m_grid.rows[j];
  1472. for (unsigned i = 0; i < m_grid.width; ++i)
  1473. {
  1474. //valid height value
  1475. const ccRasterCell& cell = row[i];
  1476. if (std::isfinite(cell.h))
  1477. {
  1478. if (j != 0 && i != 0 && i + 1 != m_grid.width)
  1479. {
  1480. double dz_dx = 0.0;
  1481. int dz_dx_count = 0;
  1482. double dz_dy = 0.0;
  1483. int dz_dy_count = 0;
  1484. for (int di = -1; di <= 1; ++di)
  1485. {
  1486. for (int dj = -1; dj <= 1; ++dj)
  1487. {
  1488. const ccRasterCell& n = m_grid.rows[j - dj][i + di]; //-dj (instead of + dj) because we scan the grid in the reverse orientation! (from bottom to top)
  1489. if (std::isfinite(n.h))
  1490. {
  1491. if (di != 0)
  1492. {
  1493. int dx_weight = (dj == 0 ? 2 : 1);
  1494. dz_dx += (di < 0 ? -1.0 : 1.0) * dx_weight * n.h;
  1495. dz_dx_count += dx_weight;
  1496. }
  1497. if (dj != 0)
  1498. {
  1499. int dy_weight = (di == 0 ? 2 : 1);
  1500. dz_dy += (dj < 0 ? -1.0 : 1.0) * dy_weight * n.h;
  1501. dz_dy_count += dy_weight;
  1502. }
  1503. }
  1504. }
  1505. }
  1506. //for now we only handle the cell that have 8 valid neighbors!
  1507. if (dz_dx_count == 8 && dz_dy_count == 8)
  1508. {
  1509. dz_dx /= (8 * m_grid.gridStep);
  1510. dz_dy /= (8 * m_grid.gridStep);
  1511. double slope_rad = atan( /*z_factor **/sqrt(dz_dx*dz_dx + dz_dy * dz_dy));
  1512. double aspect_rad = 0;
  1513. static const double s_Zero = 1.0e-8;
  1514. if (std::abs(dz_dx) > s_Zero)
  1515. {
  1516. aspect_rad = atan2(dz_dy, -dz_dx);
  1517. if (aspect_rad < 0)
  1518. {
  1519. aspect_rad += 2.0 * M_PI;
  1520. }
  1521. }
  1522. else // dz_dx == 0
  1523. {
  1524. if (dz_dy > s_Zero)
  1525. {
  1526. aspect_rad = 0.5 * M_PI;
  1527. }
  1528. else if (dz_dy < s_Zero)
  1529. {
  1530. aspect_rad = 1.5 * M_PI;
  1531. }
  1532. }
  1533. ScalarType hillshade = static_cast<ScalarType>(std::max(0.0, cos_zenith_rad * cos(slope_rad) + sin_zenith_rad * sin(slope_rad) * cos(azimuth_rad - aspect_rad)));
  1534. if (!resampleInputCloudXY)
  1535. {
  1536. hillshadeLayer->setValue(sparseSF ? nonEmptyCellIndex : i + j * m_grid.width, hillshade);
  1537. }
  1538. else // resampling mode
  1539. {
  1540. if (cell.nbPoints != 0)
  1541. {
  1542. // non-empty cells are at the beginning
  1543. hillshadeLayer->setValue(nonEmptyCellIndex, hillshade);
  1544. }
  1545. else
  1546. {
  1547. // filled or interpolated cells are appended at the end
  1548. hillshadeLayer->setValue(m_grid.nonEmptyCellCount + validButEmptyCellIndex, hillshade);
  1549. }
  1550. }
  1551. }
  1552. }
  1553. if (!resampleInputCloudXY || cell.nbPoints != 0)
  1554. {
  1555. ++nonEmptyCellIndex;
  1556. }
  1557. else
  1558. {
  1559. ++validButEmptyCellIndex;
  1560. }
  1561. }
  1562. else
  1563. {
  1564. if (cell.nbPoints)
  1565. {
  1566. // with inv. var. projection mode, it's possible to have a non empty cell with NaN height!
  1567. ++nonEmptyCellIndex;
  1568. }
  1569. }
  1570. }
  1571. }
  1572. hillshadeLayer->computeMinAndMax();
  1573. hillshadeLayer->setColorScale(ccColorScalesManager::GetDefaultScale(ccColorScalesManager::GREY));
  1574. m_rasterCloud->setCurrentDisplayedScalarField(sfIdx);
  1575. m_rasterCloud->showSF(true);
  1576. m_UI->activeLayerComboBox->setCurrentIndex(m_UI->activeLayerComboBox->findText(HILLSHADE_FIELD_NAME));
  1577. if (m_glWindow)
  1578. {
  1579. m_glWindow->redraw();
  1580. }
  1581. }
  1582. void ccRasterizeTool::addNewContour(ccPolyline* poly, double height)
  1583. {
  1584. if (!m_cloud || !poly)
  1585. {
  1586. assert(false);
  1587. return;
  1588. }
  1589. if (poly->size() > 1)
  1590. {
  1591. poly->setGlobalScale(m_cloud->getGlobalScale());
  1592. poly->setGlobalShift(m_cloud->getGlobalShift());
  1593. poly->setWidth(m_UI->contourWidthSpinBox->value() < 2 ? 0 : m_UI->contourWidthSpinBox->value()); //size 1 is equivalent to the default size
  1594. poly->setColor(ccColor::darkGrey);
  1595. //poly->setClosed(isClosed);
  1596. if (m_UI->colorizeContoursCheckBox->isChecked())
  1597. {
  1598. ccScalarField* activeLayer = m_rasterCloud->getCurrentDisplayedScalarField();
  1599. if (activeLayer)
  1600. {
  1601. const ccColor::Rgb* col = activeLayer->getColor(height);
  1602. if (col)
  1603. {
  1604. poly->setColor(*col);
  1605. }
  1606. }
  1607. }
  1608. poly->showColors(true);
  1609. //vertices->setEnabled(false);
  1610. if (m_glWindow)
  1611. m_glWindow->addToOwnDB(poly);
  1612. m_contourLines.push_back(poly);
  1613. }
  1614. }
  1615. void ccRasterizeTool::generateContours()
  1616. {
  1617. if (!m_grid.isValid() || !m_rasterCloud)
  1618. {
  1619. ccLog::Error("Need a valid raster/cloud to compute contours!");
  1620. return;
  1621. }
  1622. //initialize parameters
  1623. ccContourLinesGenerator::Parameters params;
  1624. {
  1625. params.projectContourOnAltitudes = false;
  1626. {
  1627. switch (m_UI->activeLayerComboBox->currentData().toInt())
  1628. {
  1629. case LAYER_HEIGHT:
  1630. //nothing to do
  1631. break;
  1632. case LAYER_RGB:
  1633. ccLog::Error("Can't generate contours from RGB colors");
  1634. return;
  1635. default:
  1636. params.projectContourOnAltitudes = m_UI->projectContoursOnAltCheckBox->isChecked();
  1637. break;
  1638. }
  1639. }
  1640. //use current layer for 'altitudes'
  1641. params.altitudes = m_rasterCloud->getCurrentDisplayedScalarField();
  1642. if (!params.altitudes)
  1643. {
  1644. ccLog::Error("No valid/active layer!");
  1645. return;
  1646. }
  1647. params.emptyCellsValue = params.altitudes->getMin() - 1.0;
  1648. //min and max 'altitudes'
  1649. params.startAltitude = m_UI->contourStartDoubleSpinBox->value();
  1650. params.maxAltitude = params.altitudes->getMax();
  1651. assert(params.startAltitude <= params.maxAltitude);
  1652. //gap between levels
  1653. params.step = m_UI->contourStepDoubleSpinBox->value();
  1654. assert(params.step > 0);
  1655. //minimum number of vertices per contour line
  1656. params.minVertexCount = m_UI->minVertexCountSpinBox->value();
  1657. assert(params.minVertexCount >= 3);
  1658. //the parameters below are only required if GDAL is not supported (but we can set them anyway)
  1659. params.ignoreBorders = m_UI->ignoreContourBordersCheckBox->isChecked();
  1660. params.parentWidget = this;
  1661. }
  1662. removeContourLines();
  1663. //compute the grid min corner (2D)
  1664. CCVector2d gridMinCorner;
  1665. {
  1666. const unsigned char Z = getProjectionDimension();
  1667. assert(Z <= 2);
  1668. const unsigned char X = Z == 2 ? 0 : Z + 1;
  1669. const unsigned char Y = X == 2 ? 0 : X + 1;
  1670. gridMinCorner = CCVector2d(m_grid.minCorner.u[X], m_grid.minCorner.u[Y]);
  1671. }
  1672. //generate the contour lines
  1673. std::vector<ccPolyline*> contourLines;
  1674. if (!ccContourLinesGenerator::GenerateContourLines( &m_grid,
  1675. gridMinCorner,
  1676. params,
  1677. contourLines))
  1678. {
  1679. ccLog::Error("Process failed (see console)");
  1680. return;
  1681. }
  1682. for (ccPolyline* poly : contourLines)
  1683. {
  1684. addNewContour(poly, poly->getMetaData(ccPolyline::MetaKeyConstAltitude()).toUInt());
  1685. }
  1686. if (!m_contourLines.empty())
  1687. {
  1688. m_UI->exportContoursPushButton->setEnabled(true);
  1689. m_UI->clearContoursPushButton->setEnabled(true);
  1690. }
  1691. if (m_glWindow)
  1692. {
  1693. m_glWindow->redraw();
  1694. }
  1695. }
  1696. void ccRasterizeTool::exportContourLines()
  1697. {
  1698. MainWindow* mainWindow = MainWindow::TheInstance();
  1699. if (!mainWindow || !m_cloud || m_contourLines.empty())
  1700. {
  1701. assert(false);
  1702. return;
  1703. }
  1704. bool colorize = m_UI->colorizeContoursCheckBox->isChecked();
  1705. //vertical dimension
  1706. const unsigned char Z = getProjectionDimension();
  1707. assert(Z <= 2);
  1708. const unsigned char X = (Z == 2 ? 0 : Z + 1);
  1709. const unsigned char Y = (X == 2 ? 0 : X + 1);
  1710. ccHObject* group = new ccHObject(QString("Contour plot(%1) [step=%2]").arg(m_cloud->getName()).arg(m_UI->contourStepDoubleSpinBox->value()));
  1711. for (auto poly : m_contourLines)
  1712. {
  1713. //now is the time to map the polyline coordinates to the right dimensions!
  1714. ccPointCloud* vertices = dynamic_cast<ccPointCloud*>(poly->getAssociatedCloud());
  1715. assert(vertices);
  1716. if (vertices && Z != 2)
  1717. {
  1718. for (unsigned j = 0; j < vertices->size(); ++j)
  1719. {
  1720. CCVector3* P = const_cast<CCVector3*>(vertices->getPoint(j));
  1721. CCVector3 Q = *P;
  1722. P->u[X] = Q.x;
  1723. P->u[Y] = Q.y;
  1724. P->u[Z] = Q.z;
  1725. }
  1726. vertices->invalidateBoundingBox();
  1727. poly->invalidateBoundingBox();
  1728. }
  1729. if (!colorize)
  1730. poly->showColors(false);
  1731. group->addChild(poly);
  1732. if (m_glWindow)
  1733. m_glWindow->removeFromOwnDB(poly);
  1734. }
  1735. m_contourLines.resize(0);
  1736. m_UI->exportContoursPushButton->setEnabled(false);
  1737. group->setDisplay_recursive(m_cloud->getDisplay());
  1738. mainWindow->addToDB(group);
  1739. ccLog::Print(QString("Contour lines have been successfully exported to DB (group name: %1)").arg(group->getName()));
  1740. }
  1741. ccRasterGrid::EmptyCellFillOption ccRasterizeTool::getFillEmptyCellsStrategyExt(double& emptyCellsHeight,
  1742. double& minHeight,
  1743. double& maxHeight) const
  1744. {
  1745. ccRasterGrid::EmptyCellFillOption fillEmptyCellsStrategy = getFillEmptyCellsStrategy(m_UI->fillEmptyCellsComboBox);
  1746. emptyCellsHeight = 0.0;
  1747. minHeight = m_grid.minHeight;
  1748. maxHeight = m_grid.maxHeight;
  1749. switch (fillEmptyCellsStrategy)
  1750. {
  1751. case ccRasterGrid::LEAVE_EMPTY:
  1752. //nothing to do
  1753. break;
  1754. case ccRasterGrid::FILL_MINIMUM_HEIGHT:
  1755. emptyCellsHeight = m_grid.minHeight;
  1756. break;
  1757. case ccRasterGrid::FILL_MAXIMUM_HEIGHT:
  1758. emptyCellsHeight = m_grid.maxHeight;
  1759. break;
  1760. case ccRasterGrid::FILL_CUSTOM_HEIGHT:
  1761. case ccRasterGrid::INTERPOLATE_DELAUNAY:
  1762. {
  1763. double customEmptyCellsHeight = getCustomHeightForEmptyCells();
  1764. //update min and max height by the way (only if there are invalid cells ;)
  1765. if (m_grid.validCellCount != m_grid.width * m_grid.height)
  1766. {
  1767. if (customEmptyCellsHeight <= m_grid.minHeight)
  1768. minHeight = customEmptyCellsHeight;
  1769. else if (customEmptyCellsHeight >= m_grid.maxHeight)
  1770. maxHeight = customEmptyCellsHeight;
  1771. emptyCellsHeight = customEmptyCellsHeight;
  1772. }
  1773. }
  1774. break;
  1775. case ccRasterGrid::FILL_AVERAGE_HEIGHT:
  1776. //'average height' is a kind of 'custom height' so we can fall back to this mode!
  1777. fillEmptyCellsStrategy = ccRasterGrid::FILL_CUSTOM_HEIGHT;
  1778. emptyCellsHeight = m_grid.meanHeight;
  1779. break;
  1780. default:
  1781. assert(false);
  1782. }
  1783. return fillEmptyCellsStrategy;
  1784. }
  1785. void ccRasterizeTool::generateImage() const
  1786. {
  1787. if (!m_cloud || !m_grid.isValid())
  1788. {
  1789. assert(false);
  1790. return;
  1791. }
  1792. bool exportRGB = (m_UI->activeLayerComboBox->currentData().toInt() == LAYER_RGB);
  1793. const ccRasterGrid::SF* gridSF = nullptr;
  1794. const CCCoreLib::ScalarField* cloudSF = nullptr;
  1795. if (!exportRGB && m_UI->activeLayerComboBox->currentData().toInt() == LAYER_SF && m_cloud->isA(CC_TYPES::POINT_CLOUD))
  1796. {
  1797. //the indexes in the 'm_grid.scalarFields' are the same as in the cloud
  1798. ccPointCloud* pc = static_cast<ccPointCloud*>(m_cloud);
  1799. int visibleSfIndex = pc->getScalarFieldIndexByName(m_UI->activeLayerComboBox->currentText().toStdString());
  1800. if (visibleSfIndex >= 0 && static_cast<size_t>(visibleSfIndex) < m_grid.scalarFields.size())
  1801. {
  1802. cloudSF = pc->getScalarField(visibleSfIndex);
  1803. gridSF = &(m_grid.scalarFields[visibleSfIndex]);
  1804. }
  1805. else
  1806. {
  1807. ccLog::Error("Internal error: can't find the selected field");
  1808. return;
  1809. }
  1810. }
  1811. ccRasterGrid::EmptyCellFillOption fillEmptyCellsStrategy = ccRasterGrid::LEAVE_EMPTY;
  1812. // exported field extreme values
  1813. double emptyCellsValue = std::numeric_limits<double>::quiet_NaN();
  1814. double minValue = 0.0;
  1815. double maxValue = 0.0;
  1816. if (cloudSF)
  1817. {
  1818. // override the default min and max values (based on the height values)
  1819. minValue = cloudSF->getMin();
  1820. maxValue = cloudSF->getMax();
  1821. }
  1822. else if (!exportRGB)
  1823. {
  1824. // retrieve height values
  1825. fillEmptyCellsStrategy = getFillEmptyCellsStrategyExt( emptyCellsValue,
  1826. minValue,
  1827. maxValue);
  1828. }
  1829. double valueRange = maxValue - minValue;
  1830. if (!exportRGB && CCCoreLib::LessThanEpsilon(valueRange))
  1831. {
  1832. ccLog::Warning("[Rasterize::generateImage] Exported field has a flat range");
  1833. valueRange = 1.0; // to simplify tests below
  1834. }
  1835. QImage outputImage(m_grid.width, m_grid.height, exportRGB ? QImage::Format_ARGB32 : QImage::Format_Indexed8);
  1836. if (!outputImage.isNull())
  1837. {
  1838. unsigned emptyCellColorIndex = 0;
  1839. double maxColorComp = 255.99; //.99 --> to avoid round-off issues later!
  1840. if (!exportRGB)
  1841. {
  1842. bool addTransparentColor = (cloudSF || fillEmptyCellsStrategy == ccRasterGrid::LEAVE_EMPTY);
  1843. //build a custom palette
  1844. QVector<QRgb> palette(256);
  1845. if ( m_rasterCloud
  1846. && m_rasterCloud->getCurrentDisplayedScalarField()
  1847. && m_rasterCloud->getCurrentDisplayedScalarField()->getColorScale())
  1848. {
  1849. const ccColorScale::Shared& colorScale = m_rasterCloud->getCurrentDisplayedScalarField()->getColorScale();
  1850. unsigned steps = (addTransparentColor ? 255 : 256);
  1851. for (unsigned i = 0; i < steps; i++)
  1852. {
  1853. const ccColor::Rgb* col = colorScale->getColorByRelativePos(i / static_cast<double>(steps - 1), steps, &ccColor::lightGreyRGB);
  1854. palette[i] = qRgba(col->r, col->g, col->b, 255);
  1855. }
  1856. }
  1857. else
  1858. {
  1859. for (unsigned i = 0; i < 256; i++)
  1860. {
  1861. palette[i] = qRgba(i, i, i, 255);
  1862. }
  1863. }
  1864. if (addTransparentColor)
  1865. {
  1866. palette[255] = qRgba(255, 0, 255, 0); //magenta/transparent color for empty cells (in place of pure white)
  1867. maxColorComp = 254.99;
  1868. }
  1869. outputImage.setColorTable(palette);
  1870. if (!cloudSF) //we are using height values
  1871. {
  1872. switch (fillEmptyCellsStrategy)
  1873. {
  1874. case ccRasterGrid::LEAVE_EMPTY:
  1875. emptyCellColorIndex = 255; //should be transparent!
  1876. break;
  1877. case ccRasterGrid::FILL_MINIMUM_HEIGHT:
  1878. emptyCellColorIndex = 0;
  1879. break;
  1880. case ccRasterGrid::FILL_MAXIMUM_HEIGHT:
  1881. emptyCellColorIndex = 255;
  1882. break;
  1883. case ccRasterGrid::FILL_CUSTOM_HEIGHT:
  1884. {
  1885. double normalizedHeight = (emptyCellsValue - minValue) / valueRange;
  1886. assert(normalizedHeight >= 0.0 && normalizedHeight <= 1.0);
  1887. emptyCellColorIndex = static_cast<unsigned>(normalizedHeight*maxColorComp); //static_cast is equivalent to floor if value >= 0
  1888. }
  1889. break;
  1890. case ccRasterGrid::FILL_AVERAGE_HEIGHT:
  1891. default:
  1892. assert(false);
  1893. }
  1894. }
  1895. else
  1896. {
  1897. emptyCellColorIndex = 255;
  1898. }
  1899. //outputImage.fill(emptyCellColorIndex);
  1900. }
  1901. // Filling the image with grid values
  1902. for (unsigned j = 0; j < m_grid.height; ++j)
  1903. {
  1904. const ccRasterGrid::Row& row = m_grid.rows[j];
  1905. const double* sfRow = (gridSF ? gridSF->data() + j * m_grid.width : nullptr);
  1906. for (unsigned i = 0; i < m_grid.width; ++i)
  1907. {
  1908. if (std::isfinite(row[i].h))
  1909. {
  1910. if (exportRGB)
  1911. {
  1912. int r = static_cast<int>(std::max(0.0, std::min(255.0, row[i].color.u[0])));
  1913. int g = static_cast<int>(std::max(0.0, std::min(255.0, row[i].color.u[1])));
  1914. int b = static_cast<int>(std::max(0.0, std::min(255.0, row[i].color.u[2])));
  1915. outputImage.setPixel(i, m_grid.height - 1 - j, qRgba(r, g, b, 255));
  1916. }
  1917. else
  1918. {
  1919. double value = sfRow ? sfRow[i] : row[i].h;
  1920. double normalizedHeight = (value - minValue) / valueRange;
  1921. assert(normalizedHeight >= 0.0 && normalizedHeight <= 1.0);
  1922. unsigned char val = static_cast<unsigned char>(normalizedHeight*maxColorComp); //static_cast is equivalent to floor if value >= 0
  1923. outputImage.setPixel(i, m_grid.height - 1 - j, val);
  1924. }
  1925. }
  1926. else //NaN
  1927. {
  1928. outputImage.setPixel(i, m_grid.height - 1 - j, emptyCellColorIndex); //in RGBA mode, it should be 0
  1929. }
  1930. }
  1931. }
  1932. //open file saving dialog
  1933. {
  1934. QSettings settings;
  1935. settings.beginGroup(ccPS::HeightGridGeneration());
  1936. QString imageSavePath = settings.value("savePathImage", ccFileUtils::defaultDocPath()).toString();
  1937. QString outputFilename = ImageFileFilter::GetSaveFilename( "Save raster as image",
  1938. "image",
  1939. imageSavePath,
  1940. const_cast<ccRasterizeTool*>(this));
  1941. if (!outputFilename.isNull())
  1942. {
  1943. //save current export path to persistent settings
  1944. settings.setValue("savePathImage", QFileInfo(outputFilename).absolutePath());
  1945. settings.endGroup();
  1946. if (outputImage.save(outputFilename))
  1947. {
  1948. ccLog::Print(QString("[Rasterize] Image '%1' successfully saved").arg(outputFilename));
  1949. }
  1950. else
  1951. {
  1952. ccLog::Error("Failed to save image file!");
  1953. }
  1954. }
  1955. }
  1956. }
  1957. else
  1958. {
  1959. ccLog::Error("Failed to create output image! (not enough memory?)");
  1960. }
  1961. }
  1962. void ccRasterizeTool::generateASCIIMatrix() const
  1963. {
  1964. if (!m_grid.isValid())
  1965. return;
  1966. QSettings settings;
  1967. settings.beginGroup(ccPS::HeightGridGeneration());
  1968. QString asciiGridSavePath = settings.value("savePathASCIIGrid", ccFileUtils::defaultDocPath()).toString();
  1969. //open file saving dialog
  1970. QString filter("ASCII file (*.txt)");
  1971. QString outputFilename = QFileDialog::getSaveFileName(nullptr, "Save grid as ASCII file", asciiGridSavePath + QString("/raster_matrix.txt"), filter);
  1972. if (outputFilename.isNull())
  1973. return;
  1974. QFile fp(outputFilename);
  1975. if (!fp.open(QFile::WriteOnly))
  1976. {
  1977. ccLog::Warning(QString("[ccHeightGridGeneration] Failed to write '%1' file!").arg(outputFilename));
  1978. }
  1979. //default values
  1980. double emptyCellsHeight = 0;
  1981. double minHeight = m_grid.minHeight;
  1982. double maxHeight = m_grid.maxHeight;
  1983. //get real values
  1984. getFillEmptyCellsStrategyExt(emptyCellsHeight, minHeight, maxHeight);
  1985. QTextStream stream(&fp);
  1986. stream.setRealNumberPrecision(8);
  1987. for (unsigned j = 0; j < m_grid.height; ++j)
  1988. {
  1989. const ccRasterGrid::Row& row = m_grid.rows[m_grid.height - 1 - j];
  1990. for (unsigned i = 0; i < m_grid.width; ++i)
  1991. {
  1992. stream << (std::isfinite(row[i].h) ? row[i].h : emptyCellsHeight) << ' ';
  1993. }
  1994. stream << endl;
  1995. }
  1996. //save current export path to persistent settings
  1997. settings.setValue("savePathASCIIGrid", QFileInfo(outputFilename).absolutePath());
  1998. ccLog::Print(QString("[Rasterize] Raster matrix '%1' successfully saved").arg(outputFilename));
  1999. }
  2000. void ccRasterizeTool::onStatExportTargetChanged(bool)
  2001. {
  2002. m_UI->exportStatisticsFrame->setEnabled( m_UI->exportHeightStatsCheckBox->isChecked()
  2003. || (m_UI->exportSFStatsCheckBox->isEnabled() && m_UI->exportSFStatsCheckBox->isChecked()));
  2004. }
  2005. void ccRasterizeTool::showInterpolationParamsDialog()
  2006. {
  2007. switch (getFillEmptyCellsStrategy(m_UI->fillEmptyCellsComboBox))
  2008. {
  2009. case ccRasterGrid::EmptyCellFillOption::INTERPOLATE_DELAUNAY:
  2010. {
  2011. bool ok = false;
  2012. double value = QInputDialog::getDouble(this, tr("Delaunay triangulation"), tr("Triangles max edge length (0 = no limit)"), m_delaunayInterpParams.maxEdgeLength , 0, 1.0e6, 6, &ok);
  2013. if (ok)
  2014. {
  2015. m_delaunayInterpParams.maxEdgeLength = value;
  2016. gridIsUpToDate(false);
  2017. }
  2018. }
  2019. break;
  2020. case ccRasterGrid::EmptyCellFillOption::KRIGING:
  2021. {
  2022. ccKrigingParamsDialog dlg(this);
  2023. dlg.setParameters(m_krigingParams);
  2024. if (dlg.exec())
  2025. {
  2026. dlg.getParameters(m_krigingParams);
  2027. gridIsUpToDate(false);
  2028. }
  2029. }
  2030. break;
  2031. default:
  2032. assert(false);
  2033. break;
  2034. }
  2035. }