QGroundControl
Ground Control Station for MAVLink Drones
Loading...
Searching...
No Matches
SurveyComplexItem.cc
Go to the documentation of this file.
1#include "SurveyComplexItem.h"
2
3#include <algorithm>
4
5#include <QtCore/QJsonArray>
6#include <QtCore/QLineF>
7#include <QtGui/QPolygonF>
8
9#include "AppMessages.h"
10#include "AppSettings.h"
11#include "JsonParsing.h"
12#include "MissionItem.h"
14#include "QGCApplication.h"
15#include "QGCGeo.h"
16#include "QGCLoggingCategory.h"
17#include "QGCPlanarGeometry.h"
18#include "QGCQGeoCoordinate.h"
19#include "SettingsManager.h"
20#include "Vehicle.h"
21
22QGC_LOGGING_CATEGORY(SurveyComplexItemLog, "Plan.SurveyComplexItem")
23
24namespace {
25
26using GeoTransect = QList<QGeoCoordinate>;
27using GeoTransectGroup = QList<GeoTransect>;
28using GeoTransectGroups = QList<GeoTransectGroup>;
29
30constexpr int maxSplitSpacingAttempts = 8;
31constexpr double splitSpacingGrowthMargin = 1.01;
32
33void reverseGroupDirection(GeoTransectGroup& group)
34{
35 std::reverse(group.begin(), group.end());
36 for (GeoTransect& transect : group) {
37 std::reverse(transect.begin(), transect.end());
38 }
39}
40
41void reverseAllGroupDirections(GeoTransectGroups& groups)
42{
43 for (GeoTransectGroup& group : groups) {
44 reverseGroupDirection(group);
45 }
46}
47
49void optimizeGroupsForShortestDistance(const QGeoCoordinate& distanceCoordinate, GeoTransectGroups& groups)
50{
51 if (groups.isEmpty()) {
52 return;
53 }
54
55 const GeoTransectGroup& firstGroup = groups.first();
56 const GeoTransectGroup& lastGroup = groups.last();
57 const double groupDistances[] = {
58 firstGroup.first().first().distanceTo(distanceCoordinate),
59 firstGroup.last().last().distanceTo(distanceCoordinate),
60 lastGroup.first().first().distanceTo(distanceCoordinate),
61 lastGroup.last().last().distanceTo(distanceCoordinate),
62 };
63
64 int shortestIndex = 0;
65 for (int index = 1; index < 4; ++index) {
66 if (groupDistances[index] < groupDistances[shortestIndex]) {
67 shortestIndex = index;
68 }
69 }
70
71 if (shortestIndex > 1) {
72 std::reverse(groups.begin(), groups.end());
73 }
74 if (shortestIndex & 1) {
75 reverseAllGroupDirections(groups);
76 }
77}
78
79qsizetype transectCount(const QList<QList<QLineF>>& lineGroups)
80{
81 qsizetype count = 0;
82 for (const QList<QLineF>& group : lineGroups) {
83 count += group.size();
84 }
85 return count;
86}
87
88void joinLineFragments(QList<QList<QLineF>>& lineGroups)
89{
90 for (QList<QLineF>& group : lineGroups) {
91 if (group.size() > 1) {
92 group = {QLineF(group.first().p1(), group.last().p2())};
93 }
94 }
95}
96
97} // namespace
98
101 , _metaDataMap (FactMetaData::createMapFromJsonFile(QStringLiteral(":/json/Survey.SettingsGroup.json"), this))
102 , _gridAngleFact (settingsGroup, _metaDataMap[gridAngleName])
103 , _flyAlternateTransectsFact(settingsGroup, _metaDataMap[flyAlternateTransectsName])
104 , _splitConcavePolygonsFact (settingsGroup, _metaDataMap[splitConcavePolygonsName])
105 , _entryPoint (EntryLocationTopLeft)
106{
107 _editorQml = "qrc:/qml/QGroundControl/PlanView/SurveyItemEditor.qml";
108
109 if (_controllerVehicle && !(_controllerVehicle->fixedWing() || _controllerVehicle->vtol())) {
110 // Only fixed wing flight paths support alternate transects
111 _flyAlternateTransectsFact.setRawValue(false);
112 }
113
114 // We override the altitude to the mission default
115 if (_cameraCalc.isManualCamera() || !_cameraCalc.valueSetIsDistance()->rawValue().toBool()) {
116 _cameraCalc.distanceToSurface()->setRawValue(SettingsManager::instance()->appSettings()->defaultMissionItemAltitude()->rawValue());
117 }
118
119 connect(&_gridAngleFact, &Fact::rawValueChanged, this, &SurveyComplexItem::_setDirty);
120 connect(&_flyAlternateTransectsFact,&Fact::rawValueChanged, this, &SurveyComplexItem::_setDirty);
121 connect(&_splitConcavePolygonsFact, &Fact::rawValueChanged, this, &SurveyComplexItem::_setDirty);
123
124 connect(&_gridAngleFact, &Fact::valueChanged, this, &SurveyComplexItem::_rebuildTransects);
125 connect(&_flyAlternateTransectsFact,&Fact::valueChanged, this, &SurveyComplexItem::_rebuildTransects);
126 connect(&_splitConcavePolygonsFact, &Fact::valueChanged, this, &SurveyComplexItem::_rebuildTransects);
128
129 connect(&_surveyAreaPolygon, &QGCMapPolygon::isValidChanged, this, &SurveyComplexItem::_updateWizardMode);
130 connect(&_surveyAreaPolygon, &QGCMapPolygon::traceModeChanged, this, &SurveyComplexItem::_updateWizardMode);
131
132 if (!kmlOrShpFile.isEmpty()) {
133 _surveyAreaPolygon.loadKMLOrSHPFile(kmlOrShpFile);
134 _surveyAreaPolygon.setDirty(false);
135 }
136 setDirty(false);
137}
138
139void SurveyComplexItem::save(QJsonArray& planItems)
140{
141 QJsonObject saveObject;
142
143 _saveCommon(saveObject);
144 planItems.append(saveObject);
145}
146
147void SurveyComplexItem::savePreset(const QString& presetName)
148{
149 QJsonObject saveObject;
150
151 _saveCommon(saveObject);
152 _savePresetJson(presetName, saveObject);
153}
154
155void SurveyComplexItem::_saveCommon(QJsonObject& saveObject)
156{
158
159 saveObject[JsonParsing::jsonVersionKey] = 5;
162 saveObject[_jsonGridAngleKey] = _gridAngleFact.rawValue().toDouble();
163 saveObject[_jsonFlyAlternateTransectsKey] = _flyAlternateTransectsFact.rawValue().toBool();
164 saveObject[_jsonSplitConcavePolygonsKey] = _splitConcavePolygonsFact.rawValue().toBool();
165 saveObject[_jsonEntryPointKey] = _entryPoint;
166
167 // Polygon shape
168 _surveyAreaPolygon.saveToJson(saveObject);
169}
170
171void SurveyComplexItem::loadPreset(const QString& presetName)
172{
173 QString errorString;
174
175 QJsonObject presetObject = _loadPresetJson(presetName);
176 if (!_loadV4V5(presetObject, 0, errorString, 5, true /* forPresets */)) {
177 QGC::showAppMessage(tr("Internal Error: Preset load failed. Name: %1 Error: %2").arg(presetName).arg(errorString));
178 }
180}
181
183{
184 Q_UNUSED(prevAltitude);
185 _cameraCalc.setDistanceMode(prevAltFrame);
186}
187
188bool SurveyComplexItem::load(const QJsonObject& complexObject, int sequenceNumber, QString& errorString)
189{
190 // We need to pull version first to determine what validation/conversion needs to be performed
191 QList<JsonParsing::KeyValidateInfo> versionKeyInfoList = {
192 { JsonParsing::jsonVersionKey, QJsonValue::Double, true },
193 };
194 if (!JsonParsing::validateKeys(complexObject, versionKeyInfoList, errorString)) {
195 return false;
196 }
197
198 int version = complexObject[JsonParsing::jsonVersionKey].toInt();
199 if (version < 2 || version > 5) {
200 errorString = tr("Survey items do not support version %1").arg(version);
201 return false;
202 }
203
204 if (version == 4 || version == 5) {
205 if (!_loadV4V5(complexObject, sequenceNumber, errorString, version, false /* forPresets */)) {
206 return false;
207 }
208
210 if (_cameraShots == 0) {
211 // Shot count was possibly not available from plan file
213 }
214 } else {
215 // Must be v2 or v3
216 QJsonObject v3ComplexObject = complexObject;
217 if (version == 2) {
218 // Convert to v3
219 if (v3ComplexObject.contains(VisualMissionItem::jsonTypeKey) && v3ComplexObject[VisualMissionItem::jsonTypeKey].toString() == QStringLiteral("survey")) {
222 }
223 }
224 if (!_loadV3(complexObject, sequenceNumber, errorString)) {
225 return false;
226 }
227
228 // V2/3 doesn't include individual items so we need to rebuild manually
230 }
231
232 return true;
233}
234
235bool SurveyComplexItem::_loadV4V5(const QJsonObject& complexObject, int sequenceNumber, QString& errorString, int version, bool forPresets)
236{
237 QList<JsonParsing::KeyValidateInfo> keyInfoList = {
238 { VisualMissionItem::jsonTypeKey, QJsonValue::String, true },
239 { ComplexMissionItem::jsonComplexItemTypeKey, QJsonValue::String, true },
240 { _jsonEntryPointKey, QJsonValue::Double, true },
241 { _jsonGridAngleKey, QJsonValue::Double, true },
242 { _jsonFlyAlternateTransectsKey, QJsonValue::Bool, false },
243 };
244
245 if(version == 5) {
246 JsonParsing::KeyValidateInfo jSplitPolygon = { _jsonSplitConcavePolygonsKey, QJsonValue::Bool, true };
247 keyInfoList.append(jSplitPolygon);
248 }
249
250 if (!JsonParsing::validateKeys(complexObject, keyInfoList, errorString)) {
251 return false;
252 }
253
254 QString itemType = complexObject[VisualMissionItem::jsonTypeKey].toString();
255 QString complexType = complexObject[ComplexMissionItem::jsonComplexItemTypeKey].toString();
257 errorString = tr("%1 does not support loading this complex mission item type: %2:%3").arg(qgcApp()->applicationName()).arg(itemType).arg(complexType);
258 return false;
259 }
260
261 _ignoreRecalc = !forPresets;
262
263 if (!forPresets) {
265
266 if (!_surveyAreaPolygon.loadFromJson(complexObject, true /* required */, errorString)) {
267 _surveyAreaPolygon.clear();
268 return false;
269 }
270 }
271
272 if (!TransectStyleComplexItem::_load(complexObject, forPresets, errorString)) {
273 _ignoreRecalc = false;
274 return false;
275 }
276
277 _gridAngleFact.setRawValue (complexObject[_jsonGridAngleKey].toDouble());
278 _flyAlternateTransectsFact.setRawValue (complexObject[_jsonFlyAlternateTransectsKey].toBool(false));
279
280 // The key is missing from version 4 plans; default it off rather than inheriting the last used value
281 _splitConcavePolygonsFact.setRawValue(complexObject[_jsonSplitConcavePolygonsKey].toBool(false));
282
283 _entryPoint = complexObject[_jsonEntryPointKey].toInt();
284
285 _ignoreRecalc = false;
286
287 return true;
288}
289
290bool SurveyComplexItem::_loadV3(const QJsonObject& complexObject, int sequenceNumber, QString& errorString)
291{
292 QList<JsonParsing::KeyValidateInfo> mainKeyInfoList = {
293 { VisualMissionItem::jsonTypeKey, QJsonValue::String, true },
294 { ComplexMissionItem::jsonComplexItemTypeKey, QJsonValue::String, true },
295 { QGCMapPolygon::jsonPolygonKey, QJsonValue::Array, true },
296 { _jsonV3GridObjectKey, QJsonValue::Object, true },
297 { _jsonV3CameraObjectKey, QJsonValue::Object, false },
298 { _jsonV3CameraTriggerDistanceKey, QJsonValue::Double, true },
299 { _jsonV3ManualGridKey, QJsonValue::Bool, true },
300 { _jsonV3FixedValueIsAltitudeKey, QJsonValue::Bool, true },
301 { _jsonV3HoverAndCaptureKey, QJsonValue::Bool, false },
302 { _jsonV3Refly90DegreesKey, QJsonValue::Bool, false },
303 { _jsonV3CameraTriggerInTurnaroundKey, QJsonValue::Bool, false }, // Should really be required, but it was missing from initial code due to bug
304 };
305 if (!JsonParsing::validateKeys(complexObject, mainKeyInfoList, errorString)) {
306 return false;
307 }
308
309 QString itemType = complexObject[VisualMissionItem::jsonTypeKey].toString();
310 QString complexType = complexObject[ComplexMissionItem::jsonComplexItemTypeKey].toString();
312 errorString = tr("%1 does not support loading this complex mission item type: %2:%3").arg(qgcApp()->applicationName()).arg(itemType).arg(complexType);
313 return false;
314 }
315
316 _ignoreRecalc = true;
317
319
320 _hoverAndCaptureFact.setRawValue (complexObject[_jsonV3HoverAndCaptureKey].toBool(false));
321 _refly90DegreesFact.setRawValue (complexObject[_jsonV3Refly90DegreesKey].toBool(false));
322 _cameraTriggerInTurnAroundFact.setRawValue (complexObject[_jsonV3CameraTriggerInTurnaroundKey].toBool(true));
323 _splitConcavePolygonsFact.setRawValue(false);
324
325 _cameraCalc.valueSetIsDistance()->setRawValue (complexObject[_jsonV3FixedValueIsAltitudeKey].toBool(true));
326 _cameraCalc.setDistanceMode(complexObject[_jsonV3GridAltitudeRelativeKey].toBool(true) ? QGroundControlQmlGlobal::AltitudeFrameRelative : QGroundControlQmlGlobal::AltitudeFrameAbsolute);
327
328 bool manualGrid = complexObject[_jsonV3ManualGridKey].toBool(true);
329
330 QList<JsonParsing::KeyValidateInfo> gridKeyInfoList = {
331 { _jsonV3GridAltitudeKey, QJsonValue::Double, true },
332 { _jsonV3GridAltitudeRelativeKey, QJsonValue::Bool, true },
333 { _jsonV3GridAngleKey, QJsonValue::Double, true },
334 { _jsonV3GridSpacingKey, QJsonValue::Double, true },
335 { _jsonEntryPointKey, QJsonValue::Double, false },
336 { _jsonV3TurnaroundDistKey, QJsonValue::Double, true },
337 };
338 QJsonObject gridObject = complexObject[_jsonV3GridObjectKey].toObject();
339 if (!JsonParsing::validateKeys(gridObject, gridKeyInfoList, errorString)) {
340 _ignoreRecalc = false;
341 return false;
342 }
343
344 _gridAngleFact.setRawValue (gridObject[_jsonV3GridAngleKey].toDouble());
345 _turnAroundDistanceFact.setRawValue (gridObject[_jsonV3TurnaroundDistKey].toDouble());
346
347 if (gridObject.contains(_jsonEntryPointKey)) {
348 _entryPoint = gridObject[_jsonEntryPointKey].toInt();
349 } else {
350 _entryPoint = EntryLocationTopRight;
351 }
352
353 _cameraCalc.distanceToSurface()->setRawValue (gridObject[_jsonV3GridAltitudeKey].toDouble());
354 _cameraCalc.adjustedFootprintSide()->setRawValue (gridObject[_jsonV3GridSpacingKey].toDouble());
355 _cameraCalc.adjustedFootprintFrontal()->setRawValue (complexObject[_jsonV3CameraTriggerDistanceKey].toDouble());
356
357 if (manualGrid) {
359 } else {
360 if (!complexObject.contains(_jsonV3CameraObjectKey)) {
361 errorString = tr("%1 but %2 object is missing").arg("manualGrid = false").arg("camera");
362 _ignoreRecalc = false;
363 return false;
364 }
365
366 QJsonObject cameraObject = complexObject[_jsonV3CameraObjectKey].toObject();
367
368 // Older code had typo on "imageSideOverlap" incorrectly being "imageSizeOverlap"
369 QString incorrectImageSideOverlap = "imageSizeOverlap";
370 if (cameraObject.contains(incorrectImageSideOverlap)) {
371 cameraObject[_jsonV3SideOverlapKey] = cameraObject[incorrectImageSideOverlap];
372 cameraObject.remove(incorrectImageSideOverlap);
373 }
374
375 QList<JsonParsing::KeyValidateInfo> cameraKeyInfoList = {
376 { _jsonV3GroundResolutionKey, QJsonValue::Double, true },
377 { _jsonV3FrontalOverlapKey, QJsonValue::Double, true },
378 { _jsonV3SideOverlapKey, QJsonValue::Double, true },
379 { _jsonV3CameraSensorWidthKey, QJsonValue::Double, true },
380 { _jsonV3CameraSensorHeightKey, QJsonValue::Double, true },
381 { _jsonV3CameraResolutionWidthKey, QJsonValue::Double, true },
382 { _jsonV3CameraResolutionHeightKey, QJsonValue::Double, true },
383 { _jsonV3CameraFocalLengthKey, QJsonValue::Double, true },
384 { _jsonV3CameraNameKey, QJsonValue::String, true },
385 { _jsonV3CameraOrientationLandscapeKey, QJsonValue::Bool, true },
386 { _jsonV3CameraMinTriggerIntervalKey, QJsonValue::Double, false },
387 };
388 if (!JsonParsing::validateKeys(cameraObject, cameraKeyInfoList, errorString)) {
389 _ignoreRecalc = false;
390 return false;
391 }
392
393 _cameraCalc.landscape()->setRawValue (cameraObject[_jsonV3CameraOrientationLandscapeKey].toBool(true));
394 _cameraCalc.frontalOverlap()->setRawValue (cameraObject[_jsonV3FrontalOverlapKey].toInt());
395 _cameraCalc.sideOverlap()->setRawValue (cameraObject[_jsonV3SideOverlapKey].toInt());
396 _cameraCalc.sensorWidth()->setRawValue (cameraObject[_jsonV3CameraSensorWidthKey].toDouble());
397 _cameraCalc.sensorHeight()->setRawValue (cameraObject[_jsonV3CameraSensorHeightKey].toDouble());
398 _cameraCalc.focalLength()->setRawValue (cameraObject[_jsonV3CameraFocalLengthKey].toDouble());
399 _cameraCalc.imageWidth()->setRawValue (cameraObject[_jsonV3CameraResolutionWidthKey].toInt());
400 _cameraCalc.imageHeight()->setRawValue (cameraObject[_jsonV3CameraResolutionHeightKey].toInt());
401 _cameraCalc.minTriggerInterval()->setRawValue (cameraObject[_jsonV3CameraMinTriggerIntervalKey].toDouble(0));
402 _cameraCalc.imageDensity()->setRawValue (cameraObject[_jsonV3GroundResolutionKey].toDouble());
403 _cameraCalc.fixedOrientation()->setRawValue (false);
404 _cameraCalc._setCameraNameFromV3TransectLoad (cameraObject[_jsonV3CameraNameKey].toString());
405 }
406
407 // Polygon shape
413 if (!_surveyAreaPolygon.loadFromJson(complexObject, true /* required */, errorString)) {
414 _surveyAreaPolygon.clear();
415 _ignoreRecalc = false;
416 return false;
417 }
418
419 _ignoreRecalc = false;
420
421 return true;
422}
423
424QPointF SurveyComplexItem::_rotatePoint(const QPointF& point, const QPointF& origin, double angle)
425{
426 QPointF rotated;
427 double radians = (M_PI / 180.0) * -angle;
428
429 rotated.setX(((point.x() - origin.x()) * cos(radians)) - ((point.y() - origin.y()) * sin(radians)) + origin.x());
430 rotated.setY(((point.x() - origin.x()) * sin(radians)) + ((point.y() - origin.y()) * cos(radians)) + origin.y());
431
432 return rotated;
433}
434
435void SurveyComplexItem::_intersectLinesWithPolygon(const QList<QLineF>& lineList, const QPolygonF& polygon,
436 QList<QList<QLineF>>& resultLineGroups)
437{
438 resultLineGroups.clear();
439
440 const bool splitConcavePolygons = _splitConcavePolygonsFact.rawValue().toBool();
441 for (const QList<QLineF>& clippedLines : QGCPlanarGeometry::intersectLines(lineList, polygon)) {
442 if (clippedLines.isEmpty()) {
443 continue;
444 }
445
447 resultLineGroups.append(clippedLines);
448 } else {
449 resultLineGroups.append({QLineF(clippedLines.first().p1(), clippedLines.last().p2())});
450 }
451 }
452}
453
454double SurveyComplexItem::_clampGridAngle90(double gridAngle)
455{
456 // Clamp grid angle to -90<->90. This prevents transects from being rotated to a reversed order.
457 if (gridAngle > 90.0) {
458 gridAngle -= 180.0;
459 } else if (gridAngle < -90.0) {
460 gridAngle += 180;
461 }
462 return gridAngle;
463}
464
466{
467 return _turnAroundDistance() > 0;
468}
469
471{
472 _rebuildTransectsPhase1WorkerSinglePolygon(false /* refly */);
473 if (_refly90DegreesFact.rawValue().toBool()) {
474 _rebuildTransectsPhase1WorkerSinglePolygon(true /* refly */);
475 }
476}
477
478void SurveyComplexItem::_rebuildTransectsPhase1WorkerSinglePolygon(bool refly)
479{
480 if (_ignoreRecalc) {
481 return;
482 }
483
484 // If the transects are getting rebuilt then any previously loaded mission items are now invalid
486 _loadedMissionItems.clear();
487 _loadedMissionItemsParent->deleteLater();
489 }
490
491 if (_surveyAreaPolygon.count() < 3) {
492 return;
493 }
494
495 // Convert polygon to NED
496
497 QList<QPointF> polygonPoints;
498 QGeoCoordinate tangentOrigin = _surveyAreaPolygon.pathModel().value<QGCQGeoCoordinate*>(0)->coordinate();
499 qCDebug(SurveyComplexItemLog) << "_rebuildTransectsPhase1 Convert polygon to NED - _surveyAreaPolygon.count():tangentOrigin" << _surveyAreaPolygon.count() << tangentOrigin;
500 for (int i=0; i<_surveyAreaPolygon.count(); i++) {
501 double y, x, down;
502 QGeoCoordinate vertex = _surveyAreaPolygon.pathModel().value<QGCQGeoCoordinate*>(i)->coordinate();
503 if (i == 0) {
504 // This avoids a nan calculation that comes out of convertGeoToNed
505 x = y = 0;
506 } else {
507 QGCGeo::convertGeoToNed(vertex, tangentOrigin, y, x, down);
508 }
509 polygonPoints += QPointF(x, y);
510 qCDebug(SurveyComplexItemLog) << "_rebuildTransectsPhase1 vertex:x:y" << vertex << polygonPoints.last().x() << polygonPoints.last().y();
511 }
512
513 // Generate transects
514
515 double gridAngle = _gridAngleFact.rawValue().toDouble();
516 double gridSpacing = _cameraCalc.adjustedFootprintSide()->rawValue().toDouble();
517
518 gridAngle = _clampGridAngle90(gridAngle);
519 gridAngle += refly ? 90 : 0;
520 qCDebug(SurveyComplexItemLog) << "_rebuildTransectsPhase1 Clamped grid angle" << gridAngle;
521
522 qCDebug(SurveyComplexItemLog) << "_rebuildTransectsPhase1 gridSpacing:gridAngle:refly" << gridSpacing << gridAngle << refly;
523
524 // Convert polygon to bounding rect
525
526 qCDebug(SurveyComplexItemLog) << "_rebuildTransectsPhase1 Polygon";
527 QPolygonF polygon;
528 for (int i=0; i<polygonPoints.count(); i++) {
529 qCDebug(SurveyComplexItemLog) << "Vertex" << polygonPoints[i];
530 polygon << polygonPoints[i];
531 }
532 polygon << polygonPoints[0];
533 QRectF boundingRect = polygon.boundingRect();
534 QPointF boundingCenter = boundingRect.center();
535 qCDebug(SurveyComplexItemLog) << "Bounding rect" << boundingRect.topLeft().x() << boundingRect.topLeft().y() << boundingRect.bottomRight().x() << boundingRect.bottomRight().y();
536
537 // Create set of rotated parallel lines within the expanded bounding rect. Make the lines larger than the
538 // bounding box to guarantee intersection.
539
540 QList<QLineF> lineList;
541
542 // Sweep lines must extend beyond the polygon boundary regardless of grid angle.
543 // The worst case is when the polygon is rotated 45° relative to the sweep direction,
544 // where the required reach equals half the diagonal of the bounding rect.
545 // We use diagonal * 1.5 to provide a 50% safety margin beyond that worst case.
546 // Note: the old fixed +2000m was insufficient for polygons larger than ~10km.
547 const double diagonal = qSqrt(boundingRect.width() * boundingRect.width() + boundingRect.height() * boundingRect.height());
548 double maxWidth = diagonal * 1.5;
549 if (maxWidth <= 0.0) {
550 qCWarning(SurveyComplexItemLog) << "Degenerate polygon bounding rect (all vertices coincident or collinear), aborting transect rebuild";
551 return;
552 }
553
554 const auto generateSweepLines = [this, boundingCenter, gridAngle, maxWidth](double spacing) {
555 QList<QLineF> lines;
556 const double halfWidth = maxWidth / 2.0;
557 const double transectXMax = boundingCenter.x() + halfWidth;
558 for (double transectX = boundingCenter.x() - halfWidth; transectX < transectXMax; transectX += spacing) {
559 const double transectYTop = boundingCenter.y() - halfWidth;
560 const double transectYBottom = boundingCenter.y() + halfWidth;
561 lines.append(QLineF(_rotatePoint(QPointF(transectX, transectYTop), boundingCenter, gridAngle),
562 _rotatePoint(QPointF(transectX, transectYBottom), boundingCenter, gridAngle)));
563 }
564 return lines;
565 };
566
567 if (gridSpacing <= 0) {
568 // Invalid spacing: seed one center line so the < 2 fallback produces a single center transect.
569 qCWarning(SurveyComplexItemLog) << "Grid spacing" << gridSpacing << "is invalid, falling back to single center transect";
570 const double halfW = maxWidth / 2.0;
571 lineList += QLineF(
572 _rotatePoint(QPointF(boundingCenter.x(), boundingCenter.y() - halfW), boundingCenter, gridAngle),
573 _rotatePoint(QPointF(boundingCenter.x(), boundingCenter.y() + halfW), boundingCenter, gridAngle));
574 } else {
575 // Cap spacing so the sweep never generates more than maxTransectCount transects.
576 // Uses diagonal (not maxWidth) so the count reflects actual polygon-crossing transects.
577 if (gridSpacing < diagonal / maxTransectCount) {
578 qCWarning(SurveyComplexItemLog) << "Transect spacing" << gridSpacing << "raised to" << diagonal / maxTransectCount << "to limit transect count to" << maxTransectCount;
579 gridSpacing = diagonal / maxTransectCount;
580 }
581
582 lineList = generateSweepLines(gridSpacing);
583 }
584
585 // Now intersect the lines with the polygon. Fragments from the same sweep line stay grouped so that
586 // route ordering reverses complete sweeps and turnarounds are only added at the ends of each sweep.
587 QList<QList<QLineF>> sweepLineGroups;
588 _intersectLinesWithPolygon(lineList, polygon, sweepLineGroups);
589
590 // Split sweeps can produce several transects per sweep line, so the spacing cap above may not be enough
591 if (_splitConcavePolygonsFact.rawValue().toBool() && (gridSpacing > 0)) {
592 const double requestedGridSpacing = gridSpacing;
593 qsizetype splitTransectCount = transectCount(sweepLineGroups);
594 for (int attempt = 0; (attempt < maxSplitSpacingAttempts) && (splitTransectCount > maxTransectCount);
595 ++attempt) {
596 gridSpacing *= (static_cast<double>(splitTransectCount) / maxTransectCount) * splitSpacingGrowthMargin;
597 lineList = generateSweepLines(gridSpacing);
598 _intersectLinesWithPolygon(lineList, polygon, sweepLineGroups);
599 splitTransectCount = transectCount(sweepLineGroups);
600 }
601 if ((gridSpacing != requestedGridSpacing) && (splitTransectCount <= maxTransectCount)) {
602 qCWarning(SurveyComplexItemLog) << "Transect spacing" << requestedGridSpacing << "raised to" << gridSpacing
603 << "to limit split transect count to" << maxTransectCount;
604 }
605 }
606
607 // Less than two transects intersected with the polygon:
608 // Create a single transect which goes through the center of the polygon
609 // Intersect it with the polygon
610 if (transectCount(sweepLineGroups) < 2) {
611 _surveyAreaPolygon.center();
612 QLineF firstLine = lineList.first();
613 QPointF lineCenter = firstLine.pointAt(0.5);
614 QPointF centerOffset = boundingCenter - lineCenter;
615 firstLine.translate(centerOffset);
616 lineList.clear();
617 lineList.append(firstLine);
618 _intersectLinesWithPolygon(lineList, polygon, sweepLineGroups);
619 }
620
621 if (transectCount(sweepLineGroups) > maxTransectCount) {
622 qCWarning(SurveyComplexItemLog) << "Unable to limit split transect count to" << maxTransectCount
623 << "joining fragments instead";
624 joinLineFragments(sweepLineGroups);
625 }
626
627 // Convert from NED to Geo
628 GeoTransectGroups transectGroups;
629 transectGroups.reserve(sweepLineGroups.size());
630 for (const QList<QLineF>& lineGroup : sweepLineGroups) {
631 GeoTransectGroup transectGroup;
632 transectGroup.reserve(lineGroup.size());
633 for (const QLineF& line : lineGroup) {
634 QGeoCoordinate coord;
635 GeoTransect transect;
636
637 QGCGeo::convertNedToGeo(line.p1().y(), line.p1().x(), 0, tangentOrigin, coord);
638 transect.append(coord);
639 QGCGeo::convertNedToGeo(line.p2().y(), line.p2().x(), 0, tangentOrigin, coord);
640 transect.append(coord);
641
642 transectGroup.append(transect);
643 }
644 transectGroups.append(transectGroup);
645 }
646
647 if (transectGroups.isEmpty()) {
648 return;
649 }
650
651 if (_entryPoint == EntryLocationBottomLeft || _entryPoint == EntryLocationBottomRight) {
652 reverseAllGroupDirections(transectGroups);
653 }
654 if (_entryPoint == EntryLocationTopRight || _entryPoint == EntryLocationBottomRight) {
655 std::reverse(transectGroups.begin(), transectGroups.end());
656 }
657
658 if (refly) {
659 if (_transects.isEmpty()) {
660 return;
661 }
662 optimizeGroupsForShortestDistance(_transects.last().last().coord, transectGroups);
663 }
664
665 if (_flyAlternateTransectsFact.rawValue().toBool()) {
666 GeoTransectGroups alternatingGroups;
667 for (int i = 0; i < transectGroups.count(); i++) {
668 if (!(i & 1)) {
669 alternatingGroups.append(transectGroups[i]);
670 }
671 }
672 for (int i = transectGroups.count() - 1; i > 0; i--) {
673 if (i & 1) {
674 alternatingGroups.append(transectGroups[i]);
675 }
676 }
677 transectGroups = alternatingGroups;
678 }
679
680 // Adjust to lawnmower pattern by reversing every other sweep
681 for (qsizetype i = 1; i < transectGroups.count(); i += 2) {
682 reverseGroupDirection(transectGroups[i]);
683 }
684
685 struct SweepFragment
686 {
687 GeoTransect transect;
688 bool startsSweep;
689 bool endsSweep;
690 };
691
692 QList<SweepFragment> sweepFragments;
693 for (const GeoTransectGroup& group : transectGroups) {
694 for (qsizetype i = 0; i < group.count(); i++) {
695 sweepFragments.append({group[i], i == 0, i == group.count() - 1});
696 }
697 }
698
699 // Convert to CoordInfo transects and append to _transects
700 for (const SweepFragment& sweepFragment : sweepFragments) {
701 const GeoTransect& transect = sweepFragment.transect;
702 QGeoCoordinate coord;
703 QList<TransectStyleComplexItem::CoordInfo_t> coordInfoTransect;
704 TransectStyleComplexItem::CoordInfo_t coordInfo;
705
706 coordInfo = { transect[0], CoordTypeSurveyEntry };
707 coordInfoTransect.append(coordInfo);
708 coordInfo = { transect[1], CoordTypeSurveyExit };
709 coordInfoTransect.append(coordInfo);
710
711 // For hover and capture we need points for each camera location within the transect
713 double transectLength = transect[0].distanceTo(transect[1]);
714 double transectAzimuth = transect[0].azimuthTo(transect[1]);
715 if (triggerDistance() < transectLength) {
716 int cInnerHoverPoints = static_cast<int>(floor(transectLength / triggerDistance()));
717 qCDebug(SurveyComplexItemLog) << "cInnerHoverPoints" << cInnerHoverPoints;
718 for (int i=0; i<cInnerHoverPoints; i++) {
719 QGeoCoordinate hoverCoord = transect[0].atDistanceAndAzimuth(triggerDistance() * (i + 1), transectAzimuth);
720 TransectStyleComplexItem::CoordInfo_t hoverCoordInfo = { hoverCoord, CoordTypeInteriorHoverTrigger };
721 coordInfoTransect.insert(1 + i, hoverCoordInfo);
722 }
723 }
724 }
725
726 // Extend the sweep ends for turnaround. Fragments within a sweep get none, since the vehicle continues
727 // straight across the concave gap to the next fragment.
728 if (_hasTurnaround()) {
729 QGeoCoordinate turnaroundCoord;
730 double turnAroundDistance = _turnAroundDistanceFact.rawValue().toDouble();
731
732 if (sweepFragment.startsSweep) {
733 double azimuth = transect[0].azimuthTo(transect[1]);
734 turnaroundCoord = transect[0].atDistanceAndAzimuth(-turnAroundDistance, azimuth);
735 turnaroundCoord.setAltitude(qQNaN());
736 TransectStyleComplexItem::CoordInfo_t turnaroundCoordInfo = {turnaroundCoord, CoordTypeTurnaround};
737 coordInfoTransect.prepend(turnaroundCoordInfo);
738 }
739
740 if (sweepFragment.endsSweep) {
741 double azimuth = transect.last().azimuthTo(transect[transect.count() - 2]);
742 turnaroundCoord = transect.last().atDistanceAndAzimuth(-turnAroundDistance, azimuth);
743 turnaroundCoord.setAltitude(qQNaN());
744 coordInfo = {turnaroundCoord, CoordTypeTurnaround};
745 coordInfoTransect.append(coordInfo);
746 }
747 }
748
749 _transects.append(coordInfoTransect);
750 }
751}
752
753
755{
756 double triggerDistance = this->triggerDistance();
757
758 if (triggerDistance == 0) {
759 _cameraShots = 0;
760 } else {
761 if (_cameraTriggerInTurnAroundFact.rawValue().toBool()) {
763 } else {
764 _cameraShots = 0;
765
767 // We have to do it the hard way based on the mission items themselves
769 // Count the number of camera triggers in the mission items
770 for (const MissionItem* missionItem: _loadedMissionItems) {
771 _cameraShots += missionItem->command() == MAV_CMD_IMAGE_START_CAPTURE ? 1 : 0;
772 }
773 } else {
774 bool waitingForTriggerStop = false;
775 QGeoCoordinate distanceStartCoord;
776 QGeoCoordinate distanceEndCoord;
777 for (const MissionItem* missionItem: _loadedMissionItems) {
778 if (missionItem->command() == MAV_CMD_NAV_WAYPOINT) {
779 if (waitingForTriggerStop) {
780 distanceEndCoord = QGeoCoordinate(missionItem->param5(), missionItem->param6());
781 } else {
782 distanceStartCoord = QGeoCoordinate(missionItem->param5(), missionItem->param6());
783 }
784 } else if (missionItem->command() == MAV_CMD_DO_SET_CAM_TRIGG_DIST) {
785 if (missionItem->param1() > 0) {
786 // Trigger start
787 waitingForTriggerStop = true;
788 } else {
789 // Trigger stop
790 waitingForTriggerStop = false;
792 distanceEndCoord.distanceTo(distanceStartCoord), triggerDistance);
793 distanceStartCoord = QGeoCoordinate();
794 distanceEndCoord = QGeoCoordinate();
795 }
796 }
797 }
798
799 }
800 } else {
801 // We have transects available, calc from those
802 // Hover and capture takes an image at the survey entry, exit and each interior hover point
803 const auto isHoverImageCoord = [](const TransectStyleComplexItem::CoordInfo_t& coordInfo) {
804 return coordInfo.coordType == CoordTypeSurveyEntry || coordInfo.coordType == CoordTypeSurveyExit ||
806 };
807 for (const QList<TransectStyleComplexItem::CoordInfo_t>& transect: _transects) {
809 _cameraShots += std::count_if(transect.cbegin(), transect.cend(), isHoverImageCoord);
810 continue;
811 }
812
813 // Turnarounds are only present at sweep ends, so locate the survey entry/exit by type
814 QGeoCoordinate firstCameraCoord, lastCameraCoord;
815 for (const TransectStyleComplexItem::CoordInfo_t& coordInfo : transect) {
816 if (coordInfo.coordType == CoordTypeSurveyEntry) {
817 firstCameraCoord = coordInfo.coord;
818 } else if (coordInfo.coordType == CoordTypeSurveyExit) {
819 lastCameraCoord = coordInfo.coord;
820 }
821 }
822 _cameraShots +=
823 _distanceTriggerImageCount(firstCameraCoord.distanceTo(lastCameraCoord), triggerDistance);
824 }
825 }
826 }
827 }
828
829 emit cameraShotsChanged();
830}
831
836
838{
839 if (_entryPoint == EntryLocationLast) {
840 _entryPoint = EntryLocationFirst;
841 } else {
842 _entryPoint++;
843 }
844
846
847 setDirty(true);
848}
849
851{
852 return _vehicleSpeed == 0 ? 0 : triggerDistance() / _vehicleSpeed;
853}
854
856{
857 double hoverTime = 0;
858
860 for (const QList<TransectStyleComplexItem::CoordInfo_t>& transect: _transects) {
861 hoverTime += _hoverAndCaptureDelaySeconds * transect.count();
862 }
863 }
864
865 return hoverTime;
866}
867
868void SurveyComplexItem::_updateWizardMode(void)
869{
871 setWizardMode(false);
872 }
873}
#define qgcApp()
Geographic coordinate conversion utilities using GeographicLib.
#define QGC_LOGGING_CATEGORY(name, categoryStr)
static QString canonicalManualCameraName(void)
void _savePresetJson(const QString &name, QJsonObject &presetObject)
static constexpr const char * jsonComplexItemTypeKey
This mission item attribute specifies the type of the complex item.
QJsonObject _loadPresetJson(const QString &name)
Holds the meta data associated with a Fact.
void rawValueChanged(const QVariant &value)
QVariant rawValue() const
Definition Fact.h:87
void valueChanged(const QVariant &value)
This signal is only meant for use by the QT property system. It should not be connected to by client ...
Master controller for mission, fence, rally.
bool isValid(void) const
bool traceMode(void) const
void traceModeChanged(bool traceMode)
void saveToJson(QJsonObject &json)
static constexpr const char * jsonPolygonKey
bool isValidChanged(void)
double timeBetweenShots(void) final
static constexpr const char * jsonComplexItemTypeValue
Q_INVOKABLE void rotateEntryPoint(void)
Fact * splitConcavePolygons(void)
void refly90DegreesChanged(bool refly90Degrees)
static constexpr const char * settingsGroup
ReadyForSaveState readyForSaveState(void) const final
static constexpr const char * splitConcavePolygonsName
double additionalTimeDelay(void) const final
static constexpr const char * gridAngleName
SurveyComplexItem(PlanMasterController *masterController, bool flyView, const QString &kmlOrShpFile)
bool load(const QJsonObject &complexObject, int sequenceNumber, QString &errorString) final
void applyPreviousAltitudeFrame(QGroundControlQmlGlobal::AltitudeFrame prevAltFrame, double prevAltitude) final
static constexpr const char * jsonV3ComplexItemTypeValue
void loadPreset(const QString &name)
void savePreset(const QString &name)
void save(QJsonArray &planItems) final
static constexpr const char * flyAlternateTransectsName
virtual void _rebuildTransectsPhase1(void)=0
Rebuilds the _transects array.
QObject * _loadedMissionItemsParent
Parent for all items in _loadedMissionItems for simpler delete.
QList< QList< CoordInfo_t > > _transects
QList< MissionItem * > _loadedMissionItems
Mission items loaded from plan file.
void setSequenceNumber(int sequenceNumber) final
QGeoCoordinate coordinate(void) const final
int sequenceNumber(void) const final
TransectStyleComplexItem(PlanMasterController *masterController, bool flyView, QString settignsGroup)
static constexpr int maxTransectCount
Maximum number of transects allowed; spacing is raised to enforce this limit.
ReadyForSaveState readyForSaveState(void) const override
bool _load(const QJsonObject &complexObject, bool forPresets, QString &errorString)
static constexpr int _hoverAndCaptureDelaySeconds
static int _distanceTriggerImageCount(double transectLength, double triggerDistance)
void _save(QJsonObject &saveObject)
virtual void _recalcCameraShots(void)=0
@ CoordTypeTurnaround
Turnaround extension waypoint.
@ CoordTypeSurveyExit
Waypoint at exit edge of survey polygon.
@ CoordTypeInteriorHoverTrigger
Interior waypoint for hover and capture trigger.
@ CoordTypeSurveyEntry
Waypoint at entry edge of survey polygon.
bool flyView(void) const
static constexpr const char * jsonTypeComplexItemValue
Item type is Complex Item.
QString _editorQml
Qml resource for editing item.
void setWizardMode(bool wizardMode)
static constexpr const char * jsonTypeKey
Json file attribute which specifies the item type.
PlanMasterController * masterController(void)
double azimuth(void) const
QByteArray line(std::string_view command)
command as one CR/LF-terminated line.
constexpr const char * toString(HwVideoBufferPath path) noexcept
Definition GstHwTypes.h:37
bool validateKeys(const QJsonObject &jsonObject, const QList< KeyValidateInfo > &keyInfo, QString &errorString)
Validates that all required keys are present and that listed keys have the expected type.
constexpr const char * jsonVersionKey
Definition JsonParsing.h:14
void convertGeoToNed(const QGeoCoordinate &coord, const QGeoCoordinate &origin, double &x, double &y, double &z)
Definition QGCGeo.cc:36
void convertNedToGeo(double x, double y, double z, const QGeoCoordinate &origin, QGeoCoordinate &coord)
Definition QGCGeo.cc:58
QList< QList< QLineF > > intersectLines(const QList< QLineF > &lines, const QPolygonF &polygon)
void showAppMessage(const QString &message, const QString &title)
Modal application message. Queued if the UI isn't ready yet.
Definition AppMessages.cc:9