Debian Codegraph @

plugins/core/Standard/qSRA/src/distanceMapGenerationTool.cpp

raw
1 //##########################################################################
2 //# #
3 //# CLOUDCOMPARE PLUGIN: qSRA #
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 #
15 //# #
16 //##########################################################################
17
18 #include "distanceMapGenerationTool.h"
19
20 //qCC
21 #include <ccMainAppInterface.h>
22
23 //qCC_db
24 #include <ccPointCloud.h>
25 #include <ccMesh.h>
26 #include <ccMaterialSet.h>
27 #include <ccPolyline.h>
28 #include <ccScalarField.h>
29 #include <ccProgressDialog.h>
30
31 //CCCoreLib
32 #include <Delaunay2dMesh.h>
33
34 //Qt
35 #include <QFile>
36 #include <QTextStream>
37 #include <QMainWindow>
38
39 //Meta-data key for profile (polyline) origin
40 const char PROFILE_ORIGIN_KEY[] = "ProfileOrigin";
41 //Meta-data key for profile (polyline) axis
42 const char REVOLUTION_AXIS_KEY[] = "RevolutionAxis";
43 //Meta-data key for the profile (polyline) height shift
44 const char PROFILE_HEIGHT_SHIFT_KEY[] = "ProfileHeightShift";
45
46 //shortcuts
47 static const double M_PI_DIV_2 = M_PI / 2;
48 static const double M_PI_DIV_4 = M_PI / 4;
49
50 //helper
51 static inline double ComputeLatitude_rad( PointCoordinateType x,
52 PointCoordinateType y,
53 PointCoordinateType z )
54 {
55 double r = static_cast<double>(x*x + y * y);
56
57 if (r < 1.0e-8)
58 {
59 return z < 0.0 ? -M_PI_DIV_2 : M_PI_DIV_2;
60 }
61
62 return atan(z / sqrt(static_cast<double>(r)));
63 }
64
65 //helper
66 static bool GetPolylineMetaVector(const ccPolyline* polyline, const QString& key, CCVector3& P)
67 {
68 assert(polyline);
69 if (polyline)
70 {
71 //we try to get the right meta-data 'vector'
72 QVariant x = polyline->getMetaData(key + QString(".x"));
73 QVariant y = polyline->getMetaData(key + QString(".y"));
74 QVariant z = polyline->getMetaData(key + QString(".z"));
75 if (x.isValid() && y.isValid() && z.isValid())
76 {
77 bool ok[3] = { true, true, true };
78 P.x = static_cast<PointCoordinateType>(x.toDouble(ok));
79 P.y = static_cast<PointCoordinateType>(y.toDouble(ok + 1));
80 P.z = static_cast<PointCoordinateType>(z.toDouble(ok + 2));
81 return (ok[0] && ok[1] && ok[2]);
82 }
83 }
84
85 return false;
86 }
87
88 //helper
89 static void SetPoylineMetaVector(ccPolyline* polyline, const QString& key, const CCVector3& P)
90 {
91 assert(polyline);
92 if (polyline)
93 {
94 //add revolution axis as meta-data
95 polyline->setMetaData(key + QString(".x"), QVariant(P.x));
96 polyline->setMetaData(key + QString(".y"), QVariant(P.y));
97 polyline->setMetaData(key + QString(".z"), QVariant(P.z));
98 }
99 }
100
101 //helper
102 ccGLMatrix DistanceMapGenerationTool::ProfileMetaData::computeCloudToSurfaceOriginTrans() const
103 {
104 ccGLMatrix cloudToSurfaceOrigin;
105 cloudToSurfaceOrigin.setTranslation(-origin);
106
107 //we must take the axis of the Surface of Revolution into account (if any and if it is not colinear with X, Y or Z)
108 if (hasAxis && axis.u[revolDim] + std::numeric_limits<PointCoordinateType>::epsilon() < 1.0)
109 {
110 ccGLMatrix rotation;
111 CCVector3 Z(0, 0, 0);
112 Z.u[revolDim] = CCCoreLib::PC_ONE;
113 rotation = ccGLMatrix::FromToRotation(axis, Z);
114 cloudToSurfaceOrigin = rotation * cloudToSurfaceOrigin;
115 }
116
117 return cloudToSurfaceOrigin;
118 }
119
120 //helper
121 ccGLMatrix DistanceMapGenerationTool::ProfileMetaData::computeCloudToProfileOriginTrans() const
122 {
123 ccGLMatrix cloudToPolylineOrigin = computeCloudToSurfaceOriginTrans();
124
125 //add the height shift along the revolution axis (if any)
126 cloudToPolylineOrigin.getTranslation()[revolDim] -= heightShift;
127
128 return cloudToPolylineOrigin;
129 }
130
131 void DistanceMapGenerationTool::SetPoylineRevolDim(ccPolyline* polyline, int revolDim)
132 {
133 assert(polyline);
134 if (polyline)
135 {
136 //add revolution dimension as meta-data
137 QVariant dim(revolDim);
138 polyline->setMetaData(REVOLUTION_AXIS_KEY, dim);
139 }
140 }
141
142 int DistanceMapGenerationTool::GetPoylineRevolDim(const ccPolyline* polyline)
143 {
144 assert(polyline);
145 if (polyline)
146 {
147 //we try to get the revolution dimension from the polyline meta-data
148 QVariant axis = polyline->getMetaData(REVOLUTION_AXIS_KEY);
149 if (axis.isValid())
150 {
151 bool ok = true;
152 int dim = axis.toInt(&ok);
153 if (ok && dim >= 0 && dim <= 2)
154 return dim;
155 }
156 }
157
158 return -1;
159 }
160
161 void DistanceMapGenerationTool::SetPoylineOrigin(ccPolyline* polyline, const CCVector3& origin)
162 {
163 SetPoylineMetaVector(polyline, PROFILE_ORIGIN_KEY, origin);
164 }
165
166 bool DistanceMapGenerationTool::GetPoylineOrigin(const ccPolyline* polyline, CCVector3& origin)
167 {
168 //we try to get the profile origin from the polyline meta-data
169 return GetPolylineMetaVector(polyline, PROFILE_ORIGIN_KEY, origin);
170 }
171
172 void DistanceMapGenerationTool::SetPoylineAxis(ccPolyline* polyline, const CCVector3& axis)
173 {
174 SetPoylineMetaVector(polyline, REVOLUTION_AXIS_KEY, axis);
175 }
176
177 bool DistanceMapGenerationTool::GetPoylineAxis(const ccPolyline* polyline, CCVector3& axis)
178 {
179 //we try to get the profile origin from the polyline meta-data
180 return GetPolylineMetaVector(polyline, REVOLUTION_AXIS_KEY, axis);
181 }
182
183 void DistanceMapGenerationTool::SetPolylineHeightShift(ccPolyline* polyline, PointCoordinateType heightShift)
184 {
185 assert(polyline);
186 if (polyline)
187 {
188 //add 'height shift' as meta-data
189 polyline->setMetaData(PROFILE_HEIGHT_SHIFT_KEY, QVariant(heightShift));
190 }
191 }
192
193 bool DistanceMapGenerationTool::GetPolylineHeightShift(const ccPolyline* polyline, PointCoordinateType& heightShift)
194 {
195 assert(polyline);
196 if (polyline)
197 {
198 //retrieve the right meta-data
199 QVariant shift = polyline->getMetaData(PROFILE_HEIGHT_SHIFT_KEY);
200 if (shift.isValid())
201 {
202 bool ok;
203 heightShift = static_cast<PointCoordinateType>(shift.toDouble(&ok));
204 return ok;
205 }
206 }
207
208 return false;
209 }
210
211 bool DistanceMapGenerationTool::GetPoylineMetaData(const ccPolyline* polyline, ProfileMetaData& data)
212 {
213 if (!polyline)
214 {
215 assert(false);
216 return false;
217 }
218
219 data.revolDim = GetPoylineRevolDim(polyline);
220 if (data.revolDim < 0 || data.revolDim > 2)
221 {
222 return false;
223 }
224
225 if (!GetPoylineOrigin(polyline, data.origin))
226 {
227 return false;
228 }
229
230 if (!GetPolylineHeightShift(polyline, data.heightShift))
231 {
232 data.heightShift = 0;
233 }
234
235 data.hasAxis = GetPoylineAxis(polyline, data.axis);
236
237 return true;
238 }
239
240 bool DistanceMapGenerationTool::ComputeRadialDist( ccPointCloud* cloud,
241 ccPolyline* profile,
242 bool storeRadiiAsSF/*=false*/,
243 ccMainAppInterface* app/*=nullptr*/)
244 {
245 //check input cloud and profile/polyline
246 if (!cloud || !profile)
247 {
248 if (app)
249 app->dispToConsole(QString("Internal error: invalid input parameters"), ccMainAppInterface::ERR_CONSOLE_MESSAGE);
250 return false;
251 }
252 assert(cloud && profile);
253
254 //number of vertices for the profile
255 CCCoreLib::GenericIndexedCloudPersist* vertices = profile->getAssociatedCloud();
256 unsigned vertexCount = vertices->size();
257 if (vertexCount < 2)
258 {
259 if (app)
260 app->dispToConsole(QString("Invalid polyline (not enough vertices)"), ccMainAppInterface::ERR_CONSOLE_MESSAGE);
261 return false;
262 }
263
264 //profile meta-data
265 ProfileMetaData profileDesc;
266 if (!GetPoylineMetaData(profile, profileDesc))
267 {
268 if (app)
269 app->dispToConsole(QString("Invalid polyline (bad or missing meta-data)"), ccMainAppInterface::ERR_CONSOLE_MESSAGE);
270 return false;
271 }
272
273 //reserve a new scalar field (or take the old one if it already exists)
274 int sfIdx = cloud->getScalarFieldIndexByName(RADIAL_DIST_SF_NAME);
275 if (sfIdx < 0)
276 sfIdx = cloud->addScalarField(RADIAL_DIST_SF_NAME);
277 if (sfIdx < 0)
278 {
279 if (app)
280 app->dispToConsole(QString("Failed to allocate a new scalar field for computing distances! Try to free some memory ..."), ccMainAppInterface::ERR_CONSOLE_MESSAGE);
281 return false;
282 }
283 ccScalarField* sf = static_cast<ccScalarField*>(cloud->getScalarField(sfIdx));
284 unsigned pointCount = cloud->size();
285 sf->resize(pointCount); //should always be ok
286 assert(sf);
287
288 ccScalarField* radiiSf = nullptr;
289 if (storeRadiiAsSF)
290 {
291 int sfIdxRadii = cloud->getScalarFieldIndexByName(RADII_SF_NAME);
292 if (sfIdxRadii < 0)
293 sfIdxRadii = cloud->addScalarField(RADII_SF_NAME);
294 if (sfIdxRadii < 0)
295 {
296 if (app)
297 app->dispToConsole(QString("Failed to allocate a new scalar field for storing radii! You should try to free some memory ..."), ccMainAppInterface::WRN_CONSOLE_MESSAGE);
298 //return false;
299 }
300 else
301 {
302 radiiSf = static_cast<ccScalarField*>(cloud->getScalarField(sfIdxRadii));
303 radiiSf->resize(pointCount); //should always be ok
304 }
305 }
306
307 bool success = true;
308
309 //now compute the distance between the cloud and the (implicit) surface of revolution
310 {
311 ccGLMatrix cloudToProfile = profileDesc.computeCloudToProfileOriginTrans();
312
313 //we deduce the horizontal dimensions from the revolution axis
314 const unsigned char dim1 = static_cast<unsigned char>(profileDesc.revolDim < 2 ? profileDesc.revolDim + 1 : 0);
315 const unsigned char dim2 = (dim1 < 2 ? dim1 + 1 : 0);
316
317 ccProgressDialog dlg(true, app ? app->getMainWindow() : nullptr);
318 dlg.setMethodTitle(QObject::tr("Cloud to profile radial distance"));
319 dlg.setInfo(QObject::tr("Polyline: %1 vertices\nCloud: %2 points").arg(vertexCount).arg(pointCount));
320 dlg.start();
321 CCCoreLib::NormalizedProgress nProgress(static_cast<CCCoreLib::GenericProgressCallback*>(&dlg), pointCount);
322
323 for (unsigned i = 0; i < pointCount; ++i)
324 {
325 const CCVector3* P = cloud->getPoint(i);
326
327 //relative point position
328 CCVector3 Prel = cloudToProfile * (*P);
329
330 //deduce point height and radius (i.e. in profile 2D coordinate system)
331 double height = Prel.u[profileDesc.revolDim];
332 //TODO FIXME: we assume the surface of revolution is smooth!
333 double radius = sqrt(Prel.u[dim1] * Prel.u[dim1] + Prel.u[dim2] * Prel.u[dim2]);
334
335 if (radiiSf)
336 {
337 ScalarType radiusVal = static_cast<ScalarType>(radius);
338 radiiSf->setValue(i, radiusVal);
339 }
340
341 //search nearest "segment" in polyline
342 ScalarType minDist = CCCoreLib::NAN_VALUE;
343 for (unsigned j = 1; j < vertexCount; ++j)
344 {
345 const CCVector3* A = vertices->getPoint(j - 1);
346 const CCVector3* B = vertices->getPoint(j);
347
348 double alpha = (height - A->y) / (B->y - A->y);
349 if (alpha >= 0.0 && alpha <= 1.0)
350 {
351 //we deduce the right radius by linear interpolation
352 double radius_th = A->x + alpha * (B->x - A->x);
353 double dist = radius - radius_th;
354
355 //we look at the closest segment (if the polyline is concave!)
356 if ( !CCCoreLib::ScalarField::ValidValue(minDist)
357 || (dist * dist) < (static_cast<double>(minDist) * minDist) )
358 {
359 minDist = static_cast<ScalarType>(dist);
360 }
361 }
362 }
363
364 sf->setValue(i, minDist);
365
366 if (!nProgress.oneStep())
367 {
368 //cancelled by user
369 for (unsigned j = i; j < pointCount; ++j)
370 sf->setValue(j, CCCoreLib::NAN_VALUE);
371
372 success = false;
373 break;
374 }
375
376 //TEST
377 //*const_cast<CCVector3*>(P) = Prel;
378 }
379
380 //TEST
381 //cloud->invalidateBoundingBox();
382 }
383
384 sf->computeMinAndMax();
385 cloud->setCurrentDisplayedScalarField(sfIdx);
386 cloud->showSF(true);
387
388 return success;
389 }
390
391 bool DistanceMapGenerationTool::ComputeMinAndMaxLatitude_rad( ccPointCloud* cloud,
392 double& minLat_rad,
393 double& maxLat_rad,
394 const ccGLMatrix& cloudToSurfaceOrigin, //e.g. translation to the revolution origin
395 unsigned char revolutionAxisDim)
396 {
397 minLat_rad = maxLat_rad = 0.0;
398
399 assert(cloud);
400 //invalid parameters?
401 if (!cloud || revolutionAxisDim > 2)
402 return false;
403
404 unsigned count = cloud->size();
405 if (count == 0)
406 return true;
407
408 //revolution axis
409 const unsigned char Z = revolutionAxisDim;
410 //we deduce the 2 other ('horizontal') dimensions from the revolution axis
411 const unsigned char X = (Z < 2 ? Z + 1 : 0);
412 const unsigned char Y = (X < 2 ? X + 1 : 0);
413
414 for (unsigned n = 0; n < count; ++n)
415 {
416 const CCVector3* P = cloud->getPoint(n);
417 CCVector3 relativePos = cloudToSurfaceOrigin * (*P);
418
419 //latitude between 0 and pi/2
420 double lat_rad = ComputeLatitude_rad(relativePos.u[X], relativePos.u[Y], relativePos.u[Z]);
421
422 if (n)
423 {
424 if (lat_rad < minLat_rad)
425 minLat_rad = lat_rad;
426 else if (lat_rad > maxLat_rad)
427 maxLat_rad = lat_rad;
428 }
429 else
430 {
431 minLat_rad = maxLat_rad = lat_rad;
432 }
433 }
434
435 return true;
436 }
437
438 double DistanceMapGenerationTool::ConicalProjectN(double phi1, double phi2)
439 {
440 if (phi1 >= phi2)
441 return 1.0;
442
443 assert(std::abs(phi1) < M_PI_DIV_2);
444 assert(std::abs(phi2) < M_PI_DIV_2);
445
446 double tan_pl1 = tan(M_PI_DIV_4 - phi1 / 2);
447 double tan_pl2 = tan(M_PI_DIV_4 - phi2 / 2);
448
449 return (log(cos(phi1)) - log(cos(phi2))) / (log(tan_pl1) - log(tan_pl2));
450 }
451
452 double DistanceMapGenerationTool::ConicalProject(double phi, double phi1, double n)
453 {
454 assert(phi1 >= -M_PI_DIV_2 && phi1 < M_PI_DIV_2);
455
456 double tan_pl1 = tan(M_PI_DIV_4 - phi1 / 2);
457 double tan_pl = tan(M_PI_DIV_4 - phi / 2);
458
459 return cos(phi1) * pow(tan_pl / tan_pl1, n) / n;
460 }
461
462 QSharedPointer<DistanceMapGenerationTool::Map> DistanceMapGenerationTool::CreateMap(ccPointCloud* cloud,
463 ccScalarField* sf,
464 const ccGLMatrix& cloudToSurface,
465 unsigned char revolutionAxisDim,
466 double xStep_rad,
467 double yStep,
468 double yMin,
469 double yMax,
470 bool conical,
471 bool counterclockwise,
472 FillStrategyType fillStrategy,
473 EmptyCellFillOption emptyCellfillOption,
474 ccMainAppInterface* app/*=nullptr*/)
475 {
476 assert(cloud && sf);
477 if (!cloud || !sf)
478 {
479 if (app)
480 app->dispToConsole(QString("[DistanceMapGenerationTool] Internal error: invalid input structures!"), ccMainAppInterface::ERR_CONSOLE_MESSAGE);
481 return QSharedPointer<Map>(nullptr);
482 }
483
484 //invalid parameters?
485 if (xStep_rad <= 0.0 || yStep <= 0.0 || yMax <= yMin || revolutionAxisDim > 2)
486 {
487 if (app)
488 app->dispToConsole(QString("[DistanceMapGenerationTool] Internal error: invalid grid parameters!"), ccMainAppInterface::ERR_CONSOLE_MESSAGE);
489 return QSharedPointer<Map>(nullptr);
490 }
491
492 unsigned count = cloud->size();
493 if (count == 0)
494 {
495 if (app)
496 app->dispToConsole(QString("[DistanceMapGenerationTool] Cloud is empty! Nothing to do!"), ccMainAppInterface::ERR_CONSOLE_MESSAGE);
497 return QSharedPointer<Map>(nullptr);
498 }
499
500 //revolution axis
501 const unsigned char Z = revolutionAxisDim;
502 //we deduce the 2 other ('horizontal') dimensions from the revolution axis
503 const unsigned char X = (Z < 2 ? Z + 1 : 0);
504 const unsigned char Y = (X < 2 ? X + 1 : 0);
505
506 //grid dimensions
507 unsigned xSteps = 0;
508 {
509 if (xStep_rad > 0)
510 xSteps = static_cast<unsigned>(ceil((2 * M_PI) / xStep_rad));
511 if (xSteps == 0)
512 {
513 if (app)
514 app->dispToConsole(QString("[DistanceMapGenerationTool] Invalid longitude step/boundaries! Can't generate a proper map!"), ccMainAppInterface::ERR_CONSOLE_MESSAGE);
515 return QSharedPointer<Map>(nullptr);
516 }
517 }
518
519 unsigned ySteps = 0;
520 {
521 if (yStep > 0)
522 ySteps = static_cast<unsigned>(ceil((yMax - yMin) / yStep));
523 if (ySteps == 0)
524 {
525 if (app)
526 app->dispToConsole(QString("[DistanceMapGenerationTool] Invalid latitude step/boundaries! Can't generate a proper map!"), ccMainAppInterface::ERR_CONSOLE_MESSAGE);
527 return QSharedPointer<Map>(nullptr);
528 }
529 }
530
531 unsigned cellCount = xSteps * ySteps;
532 if (app)
533 app->dispToConsole(QString("[DistanceMapGenerationTool] Projected map size: %1 x %2 (%3 cells)").arg(xSteps).arg(ySteps).arg(cellCount), ccMainAppInterface::STD_CONSOLE_MESSAGE);
534
535 //reserve memory for the output matrix
536 QSharedPointer<Map> grid(new Map);
537 try
538 {
539 grid->resize(cellCount);
540 }
541 catch (const std::bad_alloc&)
542 {
543 if (app)
544 app->dispToConsole(QString("[DistanceMapGenerationTool] Not enough memory!"), ccMainAppInterface::ERR_CONSOLE_MESSAGE);
545 return QSharedPointer<Map>(nullptr);
546 }
547
548 //update grid info ("for the records")
549 grid->xSteps = xSteps;
550 grid->xMin = 0.0;
551 grid->xMax = 2 * M_PI;
552 grid->xStep = xStep_rad;
553 grid->ySteps = ySteps;
554 grid->yMin = yMin;
555 grid->yMax = yMax;
556 grid->yStep = yStep;
557 grid->conical = conical;
558
559 //motion direction
560 grid->counterclockwise = counterclockwise;
561 double ccw = (counterclockwise ? -1.0 : 1.0);
562
563 for (unsigned n = 0; n < count; ++n)
564 {
565 //we skip invalid values
566 const ScalarType& val = sf->getValue(n);
567 if (!CCCoreLib::ScalarField::ValidValue(val))
568 continue;
569
570 const CCVector3* P = cloud->getPoint(n);
571 CCVector3 relativePos = cloudToSurface * (*P);
572
573 //convert to cylindrical or conical (spherical) coordinates
574 double x = ccw * atan2(relativePos.u[X], relativePos.u[Y]); //longitude
575 if (x < 0.0)
576 {
577 x += 2 * M_PI;
578 }
579
580 double y = 0.0;
581 if (conical)
582 {
583 y = ComputeLatitude_rad(relativePos.u[X], relativePos.u[Y], relativePos.u[Z]); //latitude between 0 and pi/2
584 }
585 else
586 {
587 y = relativePos.u[Z]; //height
588 }
589
590 int i = static_cast<int>((x - grid->xMin) / grid->xStep);
591 int j = static_cast<int>((y - grid->yMin) / grid->yStep);
592
593 //if we fall exactly on the max corner of the grid box
594 if (i == static_cast<int>(grid->xSteps))
595 --i;
596 if (j == static_cast<int>(grid->ySteps))
597 --j;
598
599 //we skip points outside the box!
600 if ( i < 0 || i >= static_cast<int>(grid->xSteps)
601 || j < 0 || j >= static_cast<int>(grid->ySteps) )
602 {
603 continue;
604 }
605 assert(i >= 0 && j >= 0);
606
607 MapCell& cell = (*grid)[j*static_cast<int>(grid->xSteps) + i];
608 if (cell.count) //if there's already values projected in this cell
609 {
610 switch (fillStrategy)
611 {
612 case FILL_STRAT_MIN_DIST:
613 // Set the minimum SF value
614 if (val < cell.value)
615 cell.value = val;
616 break;
617 case FILL_STRAT_AVG_DIST:
618 // Sum the values
619 cell.value += static_cast<double>(val);
620 break;
621 case FILL_STRAT_MAX_DIST:
622 // Set the maximum SF value
623 if (val > cell.value)
624 cell.value = val;
625 break;
626 default:
627 assert(false);
628 break;
629 }
630 }
631 else
632 {
633 //for the first point, we simply have to store its associated value (whatever the case)
634 cell.value = val;
635 }
636 ++cell.count;
637
638 //if (progressCb)
639 // progressCb->update(30.0 * (float)n / (float)cloud->size());
640 }
641
642 //we need to finish the average values computation
643 if (fillStrategy == FILL_STRAT_AVG_DIST)
644 {
645 MapCell* cell = &grid->at(0);
646 for (unsigned i = 0; i < cellCount; ++i, ++cell)
647 if (cell->count > 1)
648 cell->value /= static_cast<double>(cell->count);
649 }
650
651 //fill empty cells with zero?
652 if (emptyCellfillOption == FILL_WITH_ZERO)
653 {
654 MapCell* cell = &grid->at(0);
655 for (unsigned i = 0; i < cellCount; ++i, ++cell)
656 {
657 if (cell->count == 0)
658 {
659 cell->value = 0.0;
660 cell->count = 1;
661 }
662 }
663 }
664 else if (emptyCellfillOption == FILL_INTERPOLATE)
665 {
666 //convert the non-empty cells to a 2D point cloud
667 unsigned fillCount = 0;
668 {
669 MapCell* cell = &grid->at(0);
670 for (unsigned i = 0; i < cellCount; ++i, ++cell)
671 if (cell->count != 0)
672 ++fillCount;
673 }
674
675 //do we really need to interpolate empty grid cells?
676 if (fillCount)
677 {
678 std::vector<CCVector2> the2DPoints;
679 try
680 {
681 the2DPoints.reserve(fillCount);
682 }
683 catch (...)
684 {
685 //out of memory
686 if (app)
687 app->dispToConsole(QString("[DistanceMapGenerationTool] Not enough memory to interpolate!"), ccMainAppInterface::ERR_CONSOLE_MESSAGE);
688 }
689
690 if (the2DPoints.capacity() == fillCount)
691 {
692 //fill 2D vector with non-empty cell indexes
693 {
694 const MapCell* cell = &grid->at(0);
695 for (unsigned j = 0; j < grid->ySteps; ++j)
696 for (unsigned i = 0; i < grid->xSteps; ++i, ++cell)
697 if (cell->count)
698 the2DPoints.push_back(CCVector2(static_cast<PointCoordinateType>(i), static_cast<PointCoordinateType>(j)));
699 }
700
701 //mesh the '2D' points
702 CCCoreLib::Delaunay2dMesh* dm = new CCCoreLib::Delaunay2dMesh();
703 std::string errorStr;
704 if (!dm->buildMesh(the2DPoints, CCCoreLib::Delaunay2dMesh::USE_ALL_POINTS, errorStr))
705 {
706 if (app)
707 {
708 app->dispToConsole( QStringLiteral("[DistanceMapGenerationTool] Interpolation failed: Triangle lib. said '%1'")
709 .arg(QString::fromStdString(errorStr)),
710 ccMainAppInterface::ERR_CONSOLE_MESSAGE);
711 }
712 }
713 else
714 {
715 unsigned triNum = dm->size();
716 MapCell* cells = &grid->at(0);
717 //now we are going to 'project' all triangles on the grid
718 dm->placeIteratorAtBeginning();
719 for (unsigned k = 0; k < triNum; ++k)
720 {
721 const CCCoreLib::VerticesIndexes* tsi = dm->getNextTriangleVertIndexes();
722 //get the triangle bounding box (in grid coordinates)
723 int P[3][2];
724 int xMin = 0;
725 int yMin = 0;
726 int xMax = 0;
727 int yMax = 0;
728 {
729 for (unsigned j = 0; j < 3; ++j)
730 {
731 const CCVector2& P2D = the2DPoints[tsi->i[j]];
732 P[j][0] = static_cast<int>(P2D.x);
733 P[j][1] = static_cast<int>(P2D.y);
734 }
735 xMin = std::min(std::min(P[0][0], P[1][0]), P[2][0]);
736 yMin = std::min(std::min(P[0][1], P[1][1]), P[2][1]);
737 xMax = std::max(std::max(P[0][0], P[1][0]), P[2][0]);
738 yMax = std::max(std::max(P[0][1], P[1][1]), P[2][1]);
739 }
740 //now scan the cells
741 {
742 //pre-computation for barycentric coordinates
743 const double& valA = cells[P[0][0] + P[0][1] * grid->xSteps].value;
744 const double& valB = cells[P[1][0] + P[1][1] * grid->xSteps].value;
745 const double& valC = cells[P[2][0] + P[2][1] * grid->xSteps].value;
746 int det = (P[1][1] - P[2][1])*(P[0][0] - P[2][0]) + (P[2][0] - P[1][0])*(P[0][1] - P[2][1]);
747
748 for (int j = yMin; j <= yMax; ++j)
749 {
750 MapCell* cell = cells + static_cast<unsigned>(j)*grid->xSteps;
751
752 for (int i = xMin; i <= xMax; ++i)
753 {
754 //if the cell is empty
755 if (!cell[i].count)
756 {
757 //we test if it's included or not in the current triangle
758 //Point Inclusion in Polygon Test (inspired from W. Randolph Franklin - WRF)
759 bool inside = false;
760 for (int ti = 0; ti < 3; ++ti)
761 {
762 const int* P1 = P[ti];
763 const int* P2 = P[(ti + 1) % 3];
764 if ((P2[1] <= j && j < P1[1]) || (P1[1] <= j && j < P2[1]))
765 {
766 int t = (i - P2[0])*(P1[1] - P2[1]) - (P1[0] - P2[0])*(j - P2[1]);
767 if (P1[1] < P2[1])
768 t = -t;
769 if (t < 0)
770 inside = !inside;
771 }
772 }
773 //can we interpolate?
774 if (inside)
775 {
776 double l1 = static_cast<double>((P[1][1] - P[2][1])*(i - P[2][0]) + (P[2][0] - P[1][0])*(j - P[2][1])) / det;
777 double l2 = static_cast<double>((P[2][1] - P[0][1])*(i - P[2][0]) + (P[0][0] - P[2][0])*(j - P[2][1])) / det;
778 double l3 = 1.0 - l1 - l2;
779
780 cell[i].count = 1;
781 cell[i].value = l1 * valA + l2 * valB + l3 * valC;
782 }
783 }
784 }
785 }
786 }
787 }
788 }
789
790 delete dm;
791 dm = nullptr;
792 }
793 }
794 }
795
796 //update min and max values
797 {
798 const MapCell* cell = &grid->at(0);
799 grid->minVal = grid->maxVal = cell->value;
800 ++cell;
801 for (unsigned i = 1; i < cellCount; ++i, ++cell)
802 {
803 if (cell->value < grid->minVal)
804 grid->minVal = cell->value;
805 else if (cell->value > grid->maxVal)
806 grid->maxVal = cell->value;
807 }
808 }
809
810 //end of process
811 return grid;
812 }
813
814 CCVector3 DistanceMapGenerationTool::ProjectPointOnCone( double lon_rad,
815 double lat_rad,
816 double latMin_rad,
817 double nProj,
818 bool counterclockwise)
819 {
820 double theta = nProj * (lon_rad - M_PI);
821 double r = ConicalProject(lat_rad, latMin_rad, nProj);
822
823 CCVector3 P(static_cast<PointCoordinateType>((counterclockwise ? -r : r)* sin(theta)),
824 static_cast<PointCoordinateType>(-r * cos(theta)),
825 0);
826
827 return P;
828 }
829
830 ccMesh* DistanceMapGenerationTool::ConvertConicalMapToMesh(const QSharedPointer<Map>& map,
831 bool counterclockwise,
832 QImage mapTexture/*=QImage()*/)
833 {
834 if (!map)
835 return nullptr;
836
837 unsigned meshVertCount = map->xSteps * map->ySteps;
838 unsigned meshFaceCount = (map->xSteps - 1) * (map->ySteps - 1) * 2;
839 ccPointCloud* cloud = new ccPointCloud();
840 ccMesh* mesh = new ccMesh(cloud);
841 mesh->addChild(cloud);
842 if (!cloud->reserve(meshVertCount) || !mesh->reserve(meshFaceCount))
843 {
844 //not enough memory
845 delete mesh;
846 return nullptr;
847 }
848
849 //compute projection constant
850 double nProj = ConicalProjectN(map->yMin, map->yMax) * map->conicalSpanRatio;
851 assert(nProj >= -1.0 && nProj <= 1.0);
852
853 //create vertices
854 {
855 double cwSign = (counterclockwise ? -1.0 : 1.0);
856 for (unsigned j = 0; j < map->xSteps; ++j)
857 {
858 //longitude
859 double lon_rad = static_cast<double>(j) / map->xSteps * (2.0 * M_PI);
860
861 double theta = nProj * (lon_rad - M_PI); //-Pi shift so that the map is well centered
862 double sin_theta = sin(theta);
863 double cos_theta = cos(theta);
864
865 for (unsigned i = 0; i < map->ySteps; ++i)
866 {
867 double lat_rad = map->yMin + static_cast<double>(i)* map->yStep;
868 double r = ConicalProject(lat_rad, map->yMin, nProj);
869
870 CCVector3 Pxyz( static_cast<PointCoordinateType>(cwSign * r * sin_theta),
871 static_cast<PointCoordinateType>(-r * cos_theta),
872 0);
873 cloud->addPoint(Pxyz);
874 }
875 }
876 }
877
878 //create facets
879 {
880 for (unsigned j = 0; j + 1 < map->xSteps; ++j)
881 {
882 for (unsigned i = 0; i + 1 < map->ySteps; ++i)
883 {
884 unsigned vertA = j * map->ySteps + i;
885 unsigned vertB = vertA + map->ySteps;
886 unsigned vertC = vertB + 1;
887 unsigned vertD = vertA + 1;
888
889 mesh->addTriangle(vertB, vertC, vertD);
890 mesh->addTriangle(vertB, vertD, vertA);
891 }
892 }
893 }
894
895 //do we have a texture as well?
896 if (true/*!mapTexture.isNull()*/) //we force tex. coordinates and indexes creation!
897 {
898 //texture coordinates
899 TextureCoordsContainer* texCoords = new TextureCoordsContainer();
900 if (!texCoords->reserveSafe(meshVertCount))
901 {
902 //not enough memory to finish the job!
903 delete texCoords;
904 return mesh;
905 }
906
907 //create default texture coordinates
908 for (unsigned j = 0; j < map->xSteps; ++j)
909 {
910 TexCoords2D T(static_cast<float>(j) / (map->xSteps - 1), 0.0f);
911 for (unsigned i = 0; i < map->ySteps; ++i)
912 {
913 T.ty = static_cast<float>(i) / (map->ySteps - 1);
914 texCoords->addElement(T);
915 }
916 }
917
918 if (!mesh->reservePerTriangleTexCoordIndexes())
919 {
920 //not enough memory to finish the job!
921 delete texCoords;
922 return mesh;
923 }
924
925 //set texture indexes
926 {
927 for (unsigned j = 0; j + 1 < map->xSteps; ++j)
928 {
929 for (unsigned i = 0; i + 1 < map->ySteps; ++i)
930 {
931 unsigned vertA = j * map->ySteps + i;
932 unsigned vertB = vertA + map->ySteps;
933 unsigned vertC = vertB + 1;
934 unsigned vertD = vertA + 1;
935
936 mesh->addTriangleTexCoordIndexes(vertB, vertC, vertD);
937 mesh->addTriangleTexCoordIndexes(vertB, vertD, vertA);
938 }
939 }
940 }
941
942 //set material indexes
943 if (!mesh->reservePerTriangleMtlIndexes())
944 {
945 //not enough memory to finish the job!
946 delete texCoords;
947 mesh->removePerTriangleTexCoordIndexes();
948 return mesh;
949 }
950 for (unsigned i = 0; i < meshFaceCount; ++i)
951 {
952 mesh->addTriangleMtlIndex(0);
953 }
954
955 //set material
956 {
957 ccMaterial::Shared material(new ccMaterial("texture"));
958 material->setTexture(mapTexture, QString(), false);
959
960 ccMaterialSet* materialSet = new ccMaterialSet();
961 materialSet->addMaterial(material);
962
963 mesh->setMaterialSet(materialSet);
964 }
965
966 mesh->setTexCoordinatesTable(texCoords);
967 mesh->showMaterials(true);
968 mesh->setVisible(true);
969 }
970
971 return mesh;
972 }
973
974 bool DistanceMapGenerationTool::ComputeSurfacesAndVolumes( const QSharedPointer<Map>& map,
975 ccPolyline* profile,
976 Measures& surface,
977 Measures& volume)
978 {
979 if (!map || !profile)
980 //invalid input!
981 return false;
982
983 CCCoreLib::GenericIndexedCloudPersist* vertices = profile->getAssociatedCloud();
984 unsigned vertexCount = vertices ? vertices->size() : 0;
985 if (vertexCount < 2)
986 {
987 //invalid profile!
988 return false;
989 }
990
991 const ccPointCloud* pcVertices = dynamic_cast<ccPointCloud*>(profile->getAssociatedCloud());
992 if (!pcVertices)
993 {
994 return false;
995 }
996
997 //surface measures
998 surface = Measures();
999 //volume measures
1000 volume = Measures();
1001
1002 //theoretical surface and volumes
1003 {
1004 double surfaceProd = 0.0;
1005 double volumeProd = 0.0;
1006 const double yMax = map->yMin + map->yStep * map->ySteps;
1007 for (unsigned i = 1; i < pcVertices->size(); ++i)
1008 {
1009 const CCVector3* P0 = pcVertices->getPoint(i - 1);
1010 const CCVector3* P1 = pcVertices->getPoint(i);
1011
1012 //polyline: X = radius, Y = height
1013 double r0 = P0->x;
1014 double y0 = P0->y;
1015 double r1 = P1->x;
1016 double y1 = P1->y;
1017
1018 //without loss of generality ;)
1019 if (y0 > y1)
1020 {
1021 std::swap(y0, y1);
1022 std::swap(r0, r1);
1023 }
1024
1025 //segment is totally outside the map?
1026 if (y1 < map->yMin || y0 > yMax)
1027 {
1028 //we skip it
1029 continue;
1030 }
1031
1032 if (y0 < map->yMin)
1033 {
1034 //interpolate r0 @ map->yMin
1035 double alpha = (map->yMin - y0) / (y1 - y0);
1036 assert(alpha >= 0.0 && alpha <= 1.0);
1037 r0 = r0 + alpha * (r1 - r0);
1038 y0 = map->yMin;
1039 }
1040 else if (y1 > yMax)
1041 {
1042 //interpolate r1 @ map->yMax
1043 double alpha = (yMax - y0)/(y1 - y0);
1044 assert(alpha >= 0.0 && alpha <= 1.0);
1045 r1 = r0 + alpha * (r1 - r0);
1046 y1 = yMax;
1047 }
1048
1049 //product for truncated cone surface (see http://en.wikipedia.org/wiki/Frustum)
1050 double segmentLength = sqrt((r1 - r0)*(r1 - r0) + (y1 - y0)*(y1 - y0));
1051 surfaceProd += (r0 + r1) * segmentLength;
1052
1053 //product for truncated cone volume (see http://en.wikipedia.org/wiki/Frustum)
1054 volumeProd += (y1 - y0) * (r0*r0 + r1*r1 + r0*r1);
1055 }
1056
1057 surface.theoretical = M_PI * surfaceProd;
1058 volume.theoretical = M_PI / 3.0 * volumeProd;
1059 }
1060
1061 int revolDim = GetPoylineRevolDim(profile);
1062 if (revolDim < 0)
1063 return false;
1064
1065 //constant factors
1066 const double surfPart = map->xStep / 2.0; //perimeter of a portion of circle of angle alpha = alpha * r (* height to get the external surface)
1067 const double volPart = map->yStep * map->xStep / 6.0; //area of a portion of circle of angle alpha = alpha/2 * r^2 (* height to get the volume)
1068
1069 const MapCell* cell = &map->at(0);
1070 //for each row
1071 for (unsigned j = 0; j < map->ySteps; ++j)
1072 {
1073 //corresponding heights
1074 double height1 = map->yMin + j * map->yStep;
1075 double height2 = height1 + map->yStep;
1076 double r_th1 = -1.0;
1077 double r_th2 = -1.0;
1078
1079 //search nearest "segment" in polyline
1080 double height_middle = (height1 + height2) / 2.0;
1081 for (unsigned k = 1; k < vertexCount; ++k)
1082 {
1083 const CCVector3* A = vertices->getPoint(k - 1);
1084 const CCVector3* B = vertices->getPoint(k);
1085
1086 double alpha = (height_middle - A->y) / (B->y - A->y);
1087 if (alpha >= 0.0 && alpha <= 1.0)
1088 {
1089 r_th1 = A->x + (height1 - A->y) / (B->y - A->y) * (B->x - A->x);
1090 r_th2 = A->x + (height2 - A->y) / (B->y - A->y) * (B->x - A->x);
1091 break; //FIXME: we hope that there's only one segment facing this particular height?!
1092 }
1093 }
1094
1095 if (r_th1 >= 0.0 /* && r_th2 >= 0.0*/)
1096 {
1097 //for each column
1098 for (unsigned i = 0; i < map->xSteps; ++i, ++cell)
1099 {
1100 //deviation from theory
1101 double d = (cell->count != 0 ? cell->value : 0.0);
1102
1103 //"real" radius
1104 double r1 = r_th1 + d; //see ComputeRadialDist --> << double dist = radius - radius_th; >>
1105 double r2 = r_th2 + d; //FIXME: works only if the "scalar field" used for map creation was radial distances!!!
1106
1107 //surface of the element (truncated cone external face)
1108 {
1109 double s = sqrt((r2 - r1) * (r2 - r1) + map->yStep * map->yStep);
1110 double externalSurface = /*surfPart * */(r1 + r2) * s;
1111 surface.total += externalSurface;
1112 //dispatch in 'positive' and 'negative' surface
1113 if (d >= 0.0)
1114 surface.positive += externalSurface;
1115 else
1116 surface.negative += externalSurface;
1117 }
1118
1119 //volume of the element
1120 {
1121 volume.total += /*volPart * */(r1*r1 + r2*r2 + r1*r2);
1122 //volume of the gain (or loss) of matter
1123 double diffVolume = /*volPart * */std::abs(3.0*d * (r_th1 + r_th2 + d)); // = (r*r) * part - (r_th*r_th) * part = [(r_th+d)*(r_th+d)-r_th*r_th] * part
1124 if (d >= 0.0)
1125 volume.positive += diffVolume;
1126 else
1127 volume.negative += diffVolume;
1128 }
1129 }
1130 }
1131 else
1132 {
1133 cell += map->xSteps;
1134 }
1135 }
1136
1137 //don't forget to mult. by constants
1138 surface.total *= surfPart;
1139 surface.positive *= surfPart;
1140 surface.negative *= surfPart;
1141
1142 volume.total *= volPart;
1143 volume.positive *= volPart;
1144 volume.negative *= volPart;
1145
1146 return true;
1147 }
1148
1149 bool DistanceMapGenerationTool::ConvertCloudToCylindrical( ccPointCloud* cloud,
1150 const ccGLMatrix& cloudToSurface, //e.g. translation to the revolution origin
1151 unsigned char revolutionAxisDim,
1152 bool counterclockwise/*=false*/)
1153 {
1154 assert(cloud);
1155 if (!cloud || cloud->size() == 0)
1156 return false;
1157
1158 //revolution axis
1159 const unsigned char Z = revolutionAxisDim;
1160 //we deduce the 2 other ('horizontal') dimensions from the revolution axis
1161 const unsigned char X = (Z < 2 ? Z + 1 : 0);
1162 const unsigned char Y = (X < 2 ? X + 1 : 0);
1163
1164 //motion direction
1165 PointCoordinateType ccw = (counterclockwise ? -CCCoreLib::PC_ONE : CCCoreLib::PC_ONE);
1166
1167 //get projection height
1168 for (unsigned n = 0; n < cloud->size(); ++n)
1169 {
1170 CCVector3* P = const_cast<CCVector3*>(cloud->getPoint(n));
1171 CCVector3 relativePos = cloudToSurface * (*P);
1172
1173 //convert to cylindrical coordinates
1174 double lon_rad = ccw * atan2(relativePos.u[X], relativePos.u[Y]); //longitude
1175 if (lon_rad < 0.0)
1176 {
1177 lon_rad += 2 * M_PI;
1178 }
1179
1180 PointCoordinateType height = relativePos.u[Z];
1181
1182 P->x = static_cast<PointCoordinateType>(lon_rad);
1183 P->y = height;
1184 P->z = 0;
1185 }
1186
1187 cloud->refreshBB();
1188 if (cloud->getOctree())
1189 {
1190 cloud->deleteOctree();
1191 }
1192 //TODO FIXME: and kd-trees? etc. We need a better way to handle those cases...
1193
1194 return true;
1195 }
1196
1197 bool DistanceMapGenerationTool::ConvertCloudToConical( ccPointCloud* cloud,
1198 const ccGLMatrix& cloudToSurface, //e.g. translation to the revolution origin
1199 unsigned char revolutionAxisDim,
1200 double latMin_rad,
1201 double latMax_rad,
1202 double conicalSpanRatio/*=1.0*/,
1203 bool counterclockwise/*=false*/)
1204 {
1205 assert(cloud);
1206 if (!cloud || cloud->size() == 0)
1207 return false;
1208
1209 //revolution axis
1210 const unsigned char Z = revolutionAxisDim;
1211 //we deduce the 2 other ('horizontal') dimensions from the revolution axis
1212 const unsigned char X = (Z < 2 ? Z + 1 : 0);
1213 const unsigned char Y = (X < 2 ? X + 1 : 0);
1214
1215 //motion direction
1216 PointCoordinateType ccw = (counterclockwise ? -CCCoreLib::PC_ONE : CCCoreLib::PC_ONE);
1217 //projection factor
1218 double nProj = ConicalProjectN(latMin_rad, latMax_rad) * conicalSpanRatio;
1219
1220 //get projection height
1221 for (unsigned n = 0; n < cloud->size(); ++n)
1222 {
1223 CCVector3* P = const_cast<CCVector3*>(cloud->getPoint(n));
1224 CCVector3 relativePos = cloudToSurface * (*P);
1225
1226 //convert to cylindrical coordinates
1227 PointCoordinateType ang_rad = ccw * atan2(relativePos.u[X], relativePos.u[Y]);
1228 if (ang_rad < 0.0)
1229 ang_rad += static_cast<PointCoordinateType>(2 * M_PI);
1230
1231 double lat_rad = ComputeLatitude_rad( relativePos.u[X],
1232 relativePos.u[Y],
1233 relativePos.u[Z] ); //between 0 and pi/2
1234
1235 *P = ProjectPointOnCone(ang_rad, lat_rad, latMin_rad, nProj, counterclockwise);
1236 }
1237
1238 cloud->refreshBB();
1239 if (cloud->getOctree())
1240 {
1241 cloud->deleteOctree();
1242 }
1243 //TODO FIXME: and kd-trees? etc. We need a better way to handle those cases...
1244
1245 return true;
1246 }
1247
1248 bool DistanceMapGenerationTool::SaveMapAsCSVMatrix( const QSharedPointer<Map>& map,
1249 QString filename,
1250 QString xUnit,
1251 QString yUnit,
1252 double xConversionFactor/*=1.0*/,
1253 double yConversionFactor/*=1.0*/,
1254 ccMainAppInterface* app/*=nullptr*/)
1255 {
1256 if (!map)
1257 {
1258 if (app)
1259 app->dispToConsole(QString("[SaveMapAsCSVMatrix] Internal error: invalid input map!"), ccMainAppInterface::ERR_CONSOLE_MESSAGE);
1260 return false;
1261 }
1262
1263 //write file
1264 QFile file(filename);
1265 if (!file.open(QFile::WriteOnly | QFile::Text))
1266 {
1267 if (app)
1268 app->dispToConsole(QString("[SaveMapAsCSVMatrix] Failed to open file for writing! Check access rights"), ccMainAppInterface::ERR_CONSOLE_MESSAGE);
1269 return false;
1270 }
1271 QTextStream stream(&file);
1272
1273 //write CSV header
1274 {
1275 //min and max height (for all lines)
1276 stream << QString("Height min (%1);").arg(yUnit);
1277 stream << QString("Height max (%1);").arg(yUnit);
1278
1279 //for each column
1280 for (unsigned i=0; i<map->xSteps; ++i)
1281 {
1282 //min and max angle for the current column
1283 double minX = xConversionFactor * (map->xMin + i*map->xStep);
1284 double maxX = xConversionFactor * (map->xMin + (i + 1)*map->xStep);
1285 stream << QString("%1-%2 (%3);").arg(minX).arg(maxX).arg(xUnit);
1286 }
1287
1288 //eol
1289 stream << QString("\n");
1290 }
1291
1292 //for each line
1293 for (unsigned j = 0; j < map->ySteps; ++j)
1294 {
1295 //min and max height (for the current line)
1296 double minY = yConversionFactor * (map->yMin + (map->ySteps - 1 - j)*map->yStep);
1297 double maxY = yConversionFactor * (map->yMin + (map->ySteps - j)*map->yStep);
1298 stream << QString::number(minY) << QString(";");
1299 stream << QString::number(maxY) << QString(";");
1300
1301 //for each column
1302 for (unsigned i = 0; i < map->xSteps; ++i)
1303 {
1304 //write the grid value
1305 stream << QString::number(map->at(i + j*map->xSteps).value) << QString(";");
1306 }
1307 //eol
1308 stream << QString("\n");
1309 }
1310
1311 file.close();
1312
1313 return true;
1314 }
1315
1316 ccMesh* DistanceMapGenerationTool::ConvertProfileToMesh(ccPolyline* profile,
1317 const ccGLMatrix& cloudToProfile,
1318 bool counterclockwise,
1319 unsigned angularSteps/*=36*/,
1320 QImage mapTexture/*=QImage()*/)
1321 {
1322 if (!profile || angularSteps < 3)
1323 {
1324 return nullptr;
1325 }
1326
1327 //profile vertices
1328 CCCoreLib::GenericIndexedCloudPersist* profileVertices = profile->getAssociatedCloud();
1329 unsigned profVertCount = profileVertices->size();
1330 if (profVertCount < 2)
1331 {
1332 return nullptr;
1333 }
1334
1335 //profile meta-data
1336 ProfileMetaData profileDesc;
1337 if (!GetPoylineMetaData(profile, profileDesc))
1338 {
1339 assert(false);
1340 return nullptr;
1341 }
1342
1343 unsigned char Z = static_cast<unsigned char>(profileDesc.revolDim);
1344 //we deduce the 2 other ('horizontal') dimensions
1345 const unsigned char X = (Z < 2 ? Z + 1 : 0);
1346 const unsigned char Y = (X < 2 ? X + 1 : 0);
1347
1348 unsigned meshVertCount = profVertCount * angularSteps;
1349 unsigned meshFaceCount = (profVertCount - 1) * angularSteps * 2;
1350 ccPointCloud* cloud = new ccPointCloud("vertices");
1351 ccMesh* mesh = new ccMesh(cloud);
1352 if (!cloud->reserve(meshVertCount) || !mesh->reserve(meshFaceCount))
1353 {
1354 //not enough memory
1355 delete cloud;
1356 delete mesh;
1357 return nullptr;
1358 }
1359
1360 ccGLMatrix profileToCloud = cloudToProfile.inverse();
1361
1362 //create vertices
1363 {
1364 double cwSign = (counterclockwise ? -1.0 : 1.0);
1365 for (unsigned j = 0; j < angularSteps; ++j)
1366 {
1367 double angle_rad = static_cast<double>(j) / angularSteps * (2 * M_PI);
1368
1369 CCVector3d N(sin(angle_rad) * cwSign,
1370 cos(angle_rad),
1371 0);
1372
1373 for (unsigned i=0; i<profVertCount; ++i)
1374 {
1375 const CCVector3* P = profileVertices->getPoint(i);
1376 double radius = static_cast<double>(P->x);
1377
1378 CCVector3 Pxyz;
1379 Pxyz.u[X] = static_cast<PointCoordinateType>(radius * N.x);
1380 Pxyz.u[Y] = static_cast<PointCoordinateType>(radius * N.y);
1381 Pxyz.u[Z] = P->y;
1382
1383 profileToCloud.apply(Pxyz);
1384
1385 cloud->addPoint(Pxyz);
1386 }
1387 }
1388 mesh->addChild(cloud);
1389 }
1390
1391 PointCoordinateType h0 = profileVertices->getPoint(0)->y;
1392 PointCoordinateType dH = profileVertices->getPoint(profVertCount-1)->y - h0;
1393 bool invertedHeight = (dH < 0);
1394
1395 //create facets
1396 {
1397 for (unsigned j = 0; j < angularSteps; ++j)
1398 {
1399 unsigned nextJ = ((j + 1) % angularSteps);
1400 for (unsigned i = 0; i + 1 < profVertCount; ++i)
1401 {
1402 unsigned vertA = j*profVertCount + i;
1403 unsigned vertB = nextJ*profVertCount + i;
1404 unsigned vertC = vertB + 1;
1405 unsigned vertD = vertA + 1;
1406
1407 if (invertedHeight)
1408 {
1409 mesh->addTriangle(vertB, vertC, vertD);
1410 mesh->addTriangle(vertB, vertD, vertA);
1411 }
1412 else
1413 {
1414 mesh->addTriangle(vertB, vertD, vertC);
1415 mesh->addTriangle(vertB, vertA, vertD);
1416 }
1417 }
1418 }
1419 }
1420
1421 //do we have a texture as well?
1422 if (!mapTexture.isNull())
1423 {
1424 //texture coordinates
1425 TextureCoordsContainer* texCoords = new TextureCoordsContainer();
1426 mesh->addChild(texCoords);
1427 if (!texCoords->reserveSafe(meshVertCount+profVertCount)) //we add a column for correct wrapping!
1428 {
1429 //not enough memory to finish the job!
1430 return mesh;
1431 }
1432
1433 //create default texture coordinates
1434 for (unsigned j = 0; j <= angularSteps; ++j)
1435 {
1436 TexCoords2D T(static_cast<float>(j) / angularSteps, 0.0f);
1437 for (unsigned i = 0; i < profVertCount; ++i)
1438 {
1439 T.ty = (profileVertices->getPoint(i)->y - h0) / dH;
1440 if (invertedHeight)
1441 T.ty = 1.0f - T.ty;
1442 texCoords->addElement(T);
1443 }
1444 }
1445
1446 if (!mesh->reservePerTriangleTexCoordIndexes())
1447 {
1448 //not enough memory to finish the job!
1449 return mesh;
1450 }
1451
1452 //set texture indexes
1453 {
1454 for (unsigned j = 0; j < angularSteps; ++j)
1455 {
1456 unsigned nextJ = ((j + 1)/*% angularSteps*/);
1457 for (unsigned i = 0; i + 1 < profVertCount; ++i)
1458 {
1459 unsigned vertA = j*profVertCount + i;
1460 unsigned vertB = nextJ*profVertCount + i;
1461 unsigned vertC = vertB + 1;
1462 unsigned vertD = vertA + 1;
1463
1464 if (invertedHeight)
1465 {
1466 mesh->addTriangleTexCoordIndexes(vertB, vertC, vertD);
1467 mesh->addTriangleTexCoordIndexes(vertB, vertD, vertA);
1468 }
1469 else
1470 {
1471 mesh->addTriangleTexCoordIndexes(vertB, vertD, vertC);
1472 mesh->addTriangleTexCoordIndexes(vertB, vertA, vertD);
1473 }
1474 }
1475 }
1476 }
1477
1478 //set material indexes
1479 if (!mesh->reservePerTriangleMtlIndexes())
1480 {
1481 //not enough memory to finish the job!
1482 mesh->removeChild(texCoords);
1483 mesh->removePerTriangleTexCoordIndexes();
1484 return mesh;
1485 }
1486 for (unsigned i = 0; i < meshFaceCount; ++i)
1487 {
1488 mesh->addTriangleMtlIndex(0);
1489 }
1490
1491 //set material
1492 {
1493 ccMaterial::Shared material(new ccMaterial("texture"));
1494 material->setTexture(mapTexture, QString(), false);
1495
1496 ccMaterialSet* materialSet = new ccMaterialSet();
1497 materialSet->addMaterial(material);
1498
1499 mesh->setMaterialSet(materialSet);
1500 }
1501
1502 mesh->setTexCoordinatesTable(texCoords);
1503 mesh->showMaterials(true);
1504 mesh->setVisible(true);
1505 cloud->setVisible(false);
1506 }
1507
1508 return mesh;
1509 }
1510
1511 ccPointCloud* DistanceMapGenerationTool::ConvertMapToCloud( const QSharedPointer<Map>& map,
1512 ccPolyline* profile,
1513 double baseRadius/*=1.0*/,
1514 bool keepNaNPoints/*=true*/)
1515 {
1516 if (!map || !profile)
1517 return nullptr;
1518
1519 unsigned count = map->ySteps * map->xSteps;
1520
1521 ccPointCloud* cloud = new ccPointCloud("map");
1522 ccScalarField* sf = new ccScalarField("values");
1523 if (!cloud->reserve(count) || !sf->reserveSafe(count))
1524 {
1525 //not enough memory
1526 delete cloud;
1527 sf->release();
1528 return nullptr;
1529 }
1530
1531 //number of vertices
1532 CCCoreLib::GenericIndexedCloudPersist* polyVertices = profile->getAssociatedCloud();
1533 unsigned polyVertCount = polyVertices->size();
1534 if (polyVertCount < 2)
1535 {
1536 delete cloud;
1537 sf->release();
1538 return nullptr;
1539 }
1540
1541 //profile meta-data
1542 ProfileMetaData profileDesc;
1543 if (!GetPoylineMetaData(profile, profileDesc))
1544 {
1545 delete cloud;
1546 sf->release();
1547 return nullptr;
1548 }
1549
1550 unsigned char Z = static_cast<unsigned char>(profileDesc.revolDim);
1551 //we deduce the 2 other ('horizontal') dimensions
1552 const unsigned char X = (Z < 2 ? Z + 1 : 0);
1553 const unsigned char Y = (X < 2 ? X + 1 : 0);
1554
1555 const double xStep = baseRadius * (2 * M_PI) / static_cast<double>(map->xSteps);
1556
1557 const MapCell* cell = &map->at(0);
1558 for (unsigned j = 0; j < map->ySteps; ++j)
1559 {
1560 CCVector3 P(0, 0, 0);
1561 P.u[Z] = static_cast<PointCoordinateType>(map->yMin + (j + 0.5) * map->yStep);
1562
1563 //for each column
1564 for (unsigned i=0; i<map->xSteps; ++i, ++cell)
1565 {
1566 if (keepNaNPoints || cell->count != 0)
1567 {
1568 P.u[X] = static_cast<PointCoordinateType>(map->xMin + (i + 0.5) * xStep);
1569
1570 //search nearest "segment" in polyline
1571 for (unsigned k = 1; k < polyVertCount; ++k)
1572 {
1573 const CCVector3* A = polyVertices->getPoint(k - 1);
1574 const CCVector3* B = polyVertices->getPoint(k);
1575
1576 double alpha = (P.u[Z] - profileDesc.heightShift - A->y) / (B->y - A->y);
1577 if (alpha >= 0.0 && alpha <= 1.0)
1578 {
1579 //we deduce the right radius by linear interpolation
1580 double radius_th = A->x + alpha * (B->x - A->x);
1581 //TODO: we take the first radius (even if there are other segments at
1582 //this particular height, because we can't guess which one is the 'right' one!
1583 P.u[Y] = static_cast<PointCoordinateType>(radius_th);
1584 break;
1585 }
1586 }
1587
1588 cloud->addPoint(profileDesc.origin + P);
1589
1590 ScalarType val = cell->count ? static_cast<ScalarType>(cell->value) : CCCoreLib::NAN_VALUE;
1591 sf->addElement(val);
1592 }
1593 }
1594 }
1595
1596 sf->computeMinAndMax();
1597 int sfIdx = cloud->addScalarField(sf);
1598 cloud->setCurrentDisplayedScalarField(sfIdx);
1599 cloud->showSF(true);
1600 cloud->resize(cloud->size()); //if we have skipped NaN values!
1601
1602 return cloud;
1603 }
1604
1605 QImage DistanceMapGenerationTool::ConvertMapToImage(const QSharedPointer<Map>& map,
1606 ccColorScale::Shared colorScale,
1607 unsigned colorScaleSteps/*=ccColorScale::MAX_STEPS*/)
1608 {
1609 if (!map || !colorScale)
1610 return QImage();
1611
1612 //create image
1613 QImage image(QSize(map->xSteps, map->ySteps), QImage::Format_ARGB32);
1614 if (image.isNull())
1615 {
1616 //not enough memory!
1617 return QImage();
1618 }
1619
1620 //convert map cells to pixels
1621 {
1622 bool csIsRelative = colorScale->isRelative();
1623
1624 const MapCell* cell = &map->at(0);
1625 for (unsigned j = 0; j < map->ySteps; ++j)
1626 {
1627 //for each column
1628 for (unsigned i = 0; i < map->xSteps; ++i, ++cell)
1629 {
1630 const ccColor::Rgb* rgb = &ccColor::lightGreyRGB;
1631
1632 if (cell->count != 0)
1633 {
1634 double relativePos = csIsRelative ? (cell->value - map->minVal) / (map->maxVal - map->minVal) : colorScale->getRelativePosition(cell->value);
1635 if (relativePos < 0.0)
1636 relativePos = 0.0;
1637 else if (relativePos > 1.0)
1638 relativePos = 1.0;
1639 rgb = colorScale->getColorByRelativePos(relativePos, colorScaleSteps, &ccColor::lightGreyRGB);
1640 }
1641
1642 //DGM FIXME: QImage::sePixel is quite slow!
1643 image.setPixel( static_cast<int>(i),
1644 static_cast<int>(j),
1645 qRgb(rgb->r, rgb->g, rgb->b));
1646 }
1647 }
1648 }
1649
1650 return image;
1651 }