1/****************************************************************************
3 * (c) 2009-2024 QGROUNDCONTROL PROJECT <http://www.qgroundcontrol.org>
5 * QGroundControl is licensed according to the terms in the file
6 * COPYING.md in the root of the source code directory.
8 ****************************************************************************/
15import QGroundControl.Controls
16import QGroundControl.GeoMap
18import "GeoMapAltitude.js" as GeoMapAltitude
20/// Mission path for the GeoMap: a 3D ribbon connecting every mission item in
21/// sequence order (simple items at their coordinate; complex items via their
22/// generic entryCoordinate/exitCoordinate, so the ribbon routes straight
23/// through a complex item's own footprint rather than skipping it), at true
24/// (AMSL) altitude. A leg is flown in its destination item's frame (ArduPilot
25/// AC_WPNav): legs arriving at a terrain-frame item are draped over the DEM
26/// with a linear AGL ramp, all other legs are straight lines. Straight legs
27/// that pass below the terrain draw in collisionColor, as Plan view marks
28/// them. Stays visible
29/// in 2D mode (crossfade3D off), same as GeoMapFlightPath. Rebuilt wholesale
30/// on any mission change (missions are edited, not streamed, so the flight
31/// path's incremental append API is not needed here).
35 enum Leg { Generic, Terrain, Takeoff, Land, Interior }
37 property var missionController
38 property var vehicle ///< Active vehicle, for the RTL-to-home segment
39 property var plannedHomePosition: QtPositioning.coordinate() ///< Return endpoint of a plan being edited, preferred over the vehicle's home
40 // DEM-vs-home-AMSL bias (see GeoMapVehicleItem), computed once by the
41 // consumer for the active vehicle and shared with GeoMapMissionItems
42 // instead of being re-sampled here independently
43 property real homeTerrainBias: 0
44 property real lineWidth: ScreenTools.defaultFontPixelHeight / 5
45 // Matches MissionLineView.qml's existing flight-path line color
46 property color lineColor: QGroundControl.globalPalette.mapMissionTrajectory
47 property color collisionColor: "red"
49 altitudeMode: GeoMapItem.Absolute
51 node3DOpacity: opacity
53 if (!_geometry || !_geometry.anchorCoordinate.isValid) {
54 return QtPositioning.coordinate()
56 const anchor = _geometry.anchorCoordinate
57 return QtPositioning.coordinate(anchor.latitude, anchor.longitude, anchor.altitude + root.homeTerrainBias)
59 visible: !!missionController
61 // The geometry lives inside the 3D delegate (created/destroyed with the
62 // scene); this bridges its anchor out for the coordinate binding above
63 property var _geometry: null
65 readonly property var _camera: scene ? scene.camera : null
67 // Pixel-to-scene-unit factor at unit distance; the shader scales it by
68 // each vertex's own camera distance
69 readonly property real _screenFactor: _camera ? _camera.unitsPerPixelAtUnitDistance : 0
71 // terrainHeightAt does not notify: bumped as terrain tiles arrive while a route point waits on its terrain query
72 property int _terrainRev: 0
74 // Altitude to draw a route point at; amsl is NaN while a terrain-frame item waits on its terrain query
75 function _displayAmsl(visualItem, coordinate, amsl) {
77 return GeoMapAltitude.displayAmsl(
79 visualItem.isSimpleItem ? visualItem.altitude.rawValue : NaN,
80 isNaN(amsl) && root.surfaceModel ? root.surfaceModel.terrainHeightAt(coordinate) : NaN,
84 // Ordered route points ({coordinate, leg}) of every item the vehicle
85 // actually routes through, mirroring MissionController::_recalcFlightPathSegments:
86 // items must specifiesCoordinate && !isStandaloneCoordinate to get a
87 // segment (excludes RTL, which has no mission-encoded coordinate, and
88 // standalone items like ROI); a qualifying item contributes its
89 // entryCoordinate, plus its exitCoordinate too when that differs
90 // (exitCoordinateSameAsEntry false) — for a simple item these are always
91 // the same point, for a complex item this routes the ribbon straight
92 // through its footprint edge-to-edge. Hitting RTL stops the walk and
93 // links the last point to home instead (linkEndToHome). A land item ends
94 // the walk at its entry: its interior path (loiter exit -> touchdown) is
95 // drawn by the landing pattern visual from the slope start, not straight
96 // from the loiter center, and _recalcFlightPathSegments draws no segment
97 // after a landing item either. The walk starts at item 1 (item 0 is the
98 // MissionSettingsItem, i.e. home); home is prepended only when the mission
99 // starts from the ground — rover, or a takeoff command before the first
100 // coordinate item — mirroring linkStartToHome. leg is the type of the leg
101 // ARRIVING at a point, mirroring segmentTypeForPair: Takeoff / Land
102 // destinations first, then Terrain for a terrain-frame destination
103 // (MAV_FRAME_GLOBAL_TERRAIN_ALT), else Generic; Interior is a complex
104 // item's own entry -> exit span, which has no flight path segment. Recomputes automatically on any
105 // structural or per-item change since the loop below reads every
106 // NOTIFY-backed property it depends on.
107 readonly property var _routePoints: {
109 if (root.missionController) {
110 const items = root.missionController.visualItems
111 let linkStartToHome = root.vehicle ? root.vehicle.rover : false
112 for (let i = 1; i < items.count; ++i) {
113 const visualItem = items.get(i)
114 if (visualItem.isSimpleItem && visualItem.command === MAVLinkEnums.MAV_CMD_NAV_RETURN_TO_LAUNCH) {
115 const returnCoordinate = root.plannedHomePosition.isValid ? root.plannedHomePosition
116 : (root.vehicle ? root.vehicle.homePosition : QtPositioning.coordinate())
117 if (points.length > 0 && returnCoordinate.isValid) {
118 points.push({ coordinate: returnCoordinate, leg: GeoMapMissionPath.Generic })
122 if (points.length === 0 && visualItem.isTakeoffItem) {
123 linkStartToHome = true
125 if (visualItem.specifiesCoordinate && !visualItem.isStandaloneCoordinate) {
127 coordinate: QtPositioning.coordinate(visualItem.entryCoordinate.latitude,
128 visualItem.entryCoordinate.longitude,
129 root._displayAmsl(visualItem, visualItem.entryCoordinate,
130 visualItem.amslEntryAlt)),
131 pendingAmsl: isNaN(visualItem.amslEntryAlt),
132 leg: visualItem.isTakeoffItem ? GeoMapMissionPath.Takeoff
133 : visualItem.isLandCommand ? GeoMapMissionPath.Land
134 : (visualItem.isSimpleItem && visualItem.altitudeFrame === QGroundControl.AltitudeFrameTerrain) ? GeoMapMissionPath.Terrain
135 : GeoMapMissionPath.Generic
137 if (visualItem.isLandCommand) {
140 if (!visualItem.exitCoordinateSameAsEntry) {
142 coordinate: QtPositioning.coordinate(visualItem.exitCoordinate.latitude,
143 visualItem.exitCoordinate.longitude,
144 root._displayAmsl(visualItem, visualItem.exitCoordinate,
145 visualItem.amslExitAlt)),
146 pendingAmsl: isNaN(visualItem.amslExitAlt),
147 leg: GeoMapMissionPath.Interior
152 if (linkStartToHome && points.length > 0 && items.count > 0) {
153 const home = items.get(0)
154 if (home.coordinate.isValid) {
156 coordinate: QtPositioning.coordinate(home.coordinate.latitude,
157 home.coordinate.longitude,
158 root._displayAmsl(home, home.coordinate, home.amslEntryAlt)),
159 pendingAmsl: isNaN(home.amslEntryAlt),
160 leg: GeoMapMissionPath.Generic
168 // Straight legs longer than this are subdivided along the great circle
169 // (matching MissionLineView.qml): the geometry joins points linearly in
170 // Web Mercator, which diverges materially from the actual route over long
172 readonly property real _maxSegmentLengthM: 50000
174 // Terrain-frame legs sample the DEM at this spacing (same idea as
175 // FenceWallGeometry), capped so a degenerate long leg can't explode the
177 readonly property real _terrainSampleSpacingM: 50
178 readonly property int _maxTerrainSamplesPerLeg: 200
180 // Terrain sampling can't live in the _routePoints binding: terrainHeightAt
181 // is not NOTIFY-reactive, so draping is re-run explicitly here on route
182 // changes and on terrainHeightsChanged as DEM patches stream in.
183 // Returns the ribbon points and a highlight flag per point.
184 function _expandedPath() {
185 const points = root._routePoints
186 const collisions = root._legCollisions
187 const coordinates = []
188 const highlights = []
189 for (let i = 0; i < points.length; ++i) {
190 const coord = points[i].coordinate
192 const prev = points[i - 1].coordinate
193 const collision = collisions[i]
194 // Restart a recolored leg at a copy of its start point so the color
195 // changes at the waypoint instead of blending along the leg
196 if (collision !== highlights[highlights.length - 1]) {
197 coordinates.push(prev)
198 highlights.push(collision)
200 if (points[i].leg === GeoMapMissionPath.Terrain && root.surfaceModel) {
201 root._appendTerrainLeg(coordinates, prev, coord)
203 coordinates.push(...root._longLegSubdivision(prev, coord))
205 coordinates.push(coord)
206 while (highlights.length < coordinates.length) {
207 highlights.push(collision)
210 coordinates.push(coord)
211 highlights.push(points.length > 1 && collisions[1])
214 return { coordinates: coordinates, highlights: highlights }
217 // Interior points of a straight leg (none when it is short enough)
218 function _longLegSubdivision(prev, coord) {
220 const distance = prev.distanceTo(coord)
221 if (distance <= root._maxSegmentLengthM) {
224 const segments = Math.ceil(distance / root._maxSegmentLengthM)
225 const azimuth = prev.azimuthTo(coord)
226 for (let j = 1; j < segments; ++j) {
227 const point = prev.atDistanceAndAzimuth((j * distance) / segments, azimuth)
228 result.push(QtPositioning.coordinate(point.latitude, point.longitude,
229 prev.altitude + ((coord.altitude - prev.altitude) * j) / segments))
234 // ArduPilot flies a terrain-frame leg at a height above terrain that
235 // ramps from the origin's AGL to the destination's while riding the
236 // terrain profile (AC_WPNav terrain offset); approximate that by draping
237 // the leg over the DEM with a linear AGL ramp. AGLs are computed against
238 // the same DEM the surface renders from, so the ribbon meets both
239 // endpoint markers exactly (the DEM-vs-home AMSL bias cancels between
240 // the endpoint and sample terms).
241 function _appendTerrainLeg(result, prev, coord) {
242 const distance = prev.distanceTo(coord)
243 const steps = Math.min(Math.ceil(distance / root._terrainSampleSpacingM), root._maxTerrainSamplesPerLeg)
247 const azimuth = prev.azimuthTo(coord)
248 const prevAgl = prev.altitude - root.surfaceModel.terrainHeightAt(prev)
249 const destAgl = coord.altitude - root.surfaceModel.terrainHeightAt(coord)
250 for (let j = 1; j < steps; ++j) {
252 const point = prev.atDistanceAndAzimuth(distance * s, azimuth)
253 result.push(QtPositioning.coordinate(point.latitude, point.longitude,
254 root.surfaceModel.terrainHeightAt(point) + prevAgl + ((destAgl - prevAgl) * s)))
258 // Per route point: the leg arriving there passes below the terrain
259 // (FlightPathSegment::terrainCollision rules). Terrain-frame legs ride the
260 // terrain and never collide.
261 property var _legCollisions: []
263 // FlightPathSegment::_collisionIgnoreMeters: takeoff and land legs meet the ground at one end
264 readonly property real _collisionIgnoreMeters: 10
266 function _computeLegCollisions() {
267 const points = root._routePoints
268 const collisions = points.map(() => false)
269 // A rover follows the ground: its constant-altitude legs aren't a flight path
270 if (!root.surfaceModel || (root.vehicle && root.vehicle.rover)) {
273 const straightUpTakeoff = !(root.vehicle && root.vehicle.fixedWing)
274 for (let i = 1; i < points.length; ++i) {
275 const leg = points[i].leg
276 if (leg === GeoMapMissionPath.Terrain || leg === GeoMapMissionPath.Interior) {
279 const coord = points[i].coordinate
280 let prev = points[i - 1].coordinate
281 // MissionController::_createFlightPathSegmentWorker: a non-fixed-wing
282 // climbs vertically, then flies over at the takeoff altitude
283 if (leg === GeoMapMissionPath.Takeoff && straightUpTakeoff) {
284 prev = QtPositioning.coordinate(prev.latitude, prev.longitude, coord.altitude)
286 // Check the same great-circle pieces _expandedPath draws
287 const chain = [prev, ...root._longLegSubdivision(prev, coord), coord]
288 for (let j = 1; j < chain.length && !collisions[i]; ++j) {
289 collisions[i] = root.surfaceModel.segmentBelowTerrain(
290 root._demFrame(chain[j - 1]), root._demFrame(chain[j]),
291 (leg === GeoMapMissionPath.Takeoff && j === 1) ? root._collisionIgnoreMeters : 0,
292 (leg === GeoMapMissionPath.Land && j === chain.length - 1) ? root._collisionIgnoreMeters : 0)
298 // Route altitudes are vehicle AMSL; the rendered DEM sits homeTerrainBias above that frame
299 function _demFrame(coord) {
300 return QtPositioning.coordinate(coord.latitude, coord.longitude, coord.altitude + root.homeTerrainBias)
303 function _setGeometryPath() {
304 const path = root._expandedPath()
305 _geometry.setPath(path.coordinates, path.highlights)
308 function _reloadPath() {
310 root._legCollisions = root._computeLegCollisions()
311 root._setGeometryPath()
315 function _refreshCollisions() {
319 const collisions = root._computeLegCollisions()
320 const changed = collisions.some((collision, i) => collision !== root._legCollisions[i])
321 root._legCollisions = collisions
323 root._setGeometryPath()
327 function _redrapePath() {
329 root._setGeometryPath()
333 // Qt.callLater coalesces rebuild bursts (per-patch terrainHeightsChanged
334 // during tile streaming, route + terrain changes in one pass) into one
335 // re-drape, same idea as FenceWallGeometry::_scheduleRebuild
336 function _scheduleReloadPath() {
337 Qt.callLater(root._reloadPath)
340 function _scheduleCollisionRefresh() {
341 Qt.callLater(root._refreshCollisions)
344 on_RoutePointsChanged: _scheduleReloadPath()
345 onHomeTerrainBiasChanged: _scheduleCollisionRefresh()
347 readonly property bool _hasTerrainLeg: _routePoints.some(p => p.leg === GeoMapMissionPath.Terrain)
348 readonly property bool _hasPendingAmsl: _routePoints.some(p => p.pendingAmsl)
351 target: root.surfaceModel
353 // Draped legs follow the drawn mesh, which also changes on patch churn
354 function onTerrainHeightsChanged() {
355 if (root._hasPendingAmsl) {
358 if (root._hasTerrainLeg) {
359 Qt.callLater(root._redrapePath)
363 function onTerrainDataChanged() {
364 root._scheduleCollisionRefresh()
368 delegate3D: Component {
369 // z offsets are relative altitudes; flatten them with the terrain
370 // during the 2D<->3D transition (anchor z already tracks terrainScale
371 // through GeoMapItem)
373 scale: Qt.vector3d(1, 1, root.scene ? root.scene.terrainScale : 1)
376 geometry: FlightPathGeometry {
382 materials: CustomMaterial {
383 shadingMode: CustomMaterial.Unshaded
384 cullMode: Material.NoCulling
385 // Opaque unless the path is dimmed: blending would move it to the transparent pass
386 sourceBlend: root.node3DOpacity < 1 ? CustomMaterial.SrcAlpha : CustomMaterial.NoBlend
387 destinationBlend: root.node3DOpacity < 1 ? CustomMaterial.OneMinusSrcAlpha : CustomMaterial.NoBlend
388 vertexShader: "shaders/flightpath.vert"
389 fragmentShader: "shaders/flightpath.frag"
391 property real lineWidth: root.lineWidth
392 property real screenFactor: root._screenFactor
393 property color pathColor: root.lineColor
394 property color highlightColor: root.collisionColor
395 property real pathOpacity: root.node3DOpacity
396 // Ramps in as the terrain flattens, effectively disabling
397 // depth testing in 2D mode (see flightpath.vert)
398 property real depthPull: root.scene ? 0.5 * (1.0 - root.scene.terrainScale) : 0.0
401 Component.onCompleted: {
402 root._geometry = pathGeometry
405 Component.onDestruction: root._geometry = null