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 ****************************************************************************/
12import QtQuick3D.Helpers
16import QGroundControl.Controls
17import QGroundControl.GeoMap
19/// Experimental 2D/3D map control (preview feature): the GeoMap-engine
20/// counterpart of FlightMap. Renders the LOD surface patch quadtree with full
21/// Google Earth-style camera gestures (pan, orbit, zoom, twist, first-person
22/// look) and no view chrome.
26 // Keep map item overlays (GeoMapItem) inside the viewport, matching
27 // QtLocation Map behavior
30 property alias camera: geoCamera
32 // Same contract as FlightMap: block pinch-to-zoom while virtual joystick
33 // thumbs are down (issue #13450)
34 property bool pinchZoomDisabledByVirtualJoysticks: false
36 // Same contract as FlightMap: plain left-click/tap (no drag, no modifier)
37 // in viewport coordinates; consumers convert via surfaceCoordinateAt
38 signal mapClicked(var position)
40 // Geographic coordinate of the rendered terrain surface under a screen
41 // point (viewport pixels): the pick lands on the visible front surface,
42 // so ridges occlude the ground behind them. Works at any tilt, unlike a
43 // ground-plane pick which can land kilometers past elevated terrain.
44 // Invalid coordinate on a sky pick.
45 function surfaceCoordinateAt(screenPos) {
46 return patchModel.surfaceCoordinateAtScreenPoint(geoCamera, screenPos,
47 geoScene.verticalScale * geoScene.terrainScale)
50 // Auto-centering (parity with FlightMap): one-shot GCS/vehicle centering
51 // plus vehicle following, all decided by the shared MapPositionTracker
52 property alias allowGCSLocationCenter: _positionTracker.allowGCSLocationCenter
53 property alias allowVehicleLocationCenter: _positionTracker.allowVehicleLocationCenter
54 property alias keepVehicleCentered: _positionTracker.keepVehicleCentered
55 property alias positionTracker: _positionTracker
56 property rect followViewportRect: Qt.rect(0, 0, width, height) ///< Map area the followed vehicle is kept within
57 property var followOccluders: [] ///< Rects within the viewport covered by host UI
58 property bool followOffscreenVehicle: true ///< false: the map is not recentered when the vehicle leaves the viewport
60 // Live SurfaceModel stats for debug overlays
61 property alias patchCount: patchModel.patchCount
62 property alias pendingCount: patchModel.pendingCount
63 property alias maxZoomLevel: patchModel.maxZoomLevel
64 property alias modelStats: patchModel.statsText
65 property alias perfCapturing: patchModel.capturing
67 function startPerfCapture() {
68 patchModel.startCapture()
71 // Returns the CSV file path (empty on failure)
72 function stopPerfCapture() {
73 return patchModel.stopCapture()
76 readonly property int cameraAnimationMs: 500
78 readonly property var _activeVehicle: QGroundControl.multiVehicleManager.activeVehicle
79 readonly property var _activeVehicleCoordinate: _activeVehicle ? _activeVehicle.coordinate : QtPositioning.coordinate()
80 // Vehicle items render at coordinate.altitude + home terrain bias (see
81 // GeoMapVehicleItem): occluder-follow must track that same rendered point or
82 // the recenter target is vertically off by the bias under a tilted camera
83 readonly property var _trackedVehicleCoordinate: QtPositioning.coordinate(_activeVehicleCoordinate.latitude,
84 _activeVehicleCoordinate.longitude,
85 _activeVehicleCoordinate.altitude + _homeTerrainBias)
87 // DEM height minus vehicle-reported AMSL, sampled at home (same math as
88 // GeoMapVehicleItem). terrainHeightAt is not a binding dependency, so
89 // re-sampled explicitly below as terrain tiles arrive and when home moves.
90 property real _homeTerrainBias: 0
92 function _updateHomeTerrainBias() {
93 if (_activeVehicle && _activeVehicle.homePosition.isValid && !isNaN(_activeVehicle.homePosition.altitude)) {
94 _homeTerrainBias = patchModel.terrainDataHeightAt(_activeVehicle.homePosition) - _activeVehicle.homePosition.altitude
100 on_ActiveVehicleChanged: _updateHomeTerrainBias()
102 // Render-statistics overlay (FPS, frame timing, draw calls, texture/mesh
103 // memory) for perf work; owned here because it needs the internal View3D
104 property bool renderStats: false
106 // Terrain displacement factor (see GeoScene.terrainScale)
107 property alias terrainScale: geoScene.terrainScale
109 // Scene wiring for map items (GeoMapItem consumers)
110 readonly property GeoScene scene: geoScene
111 readonly property SurfacePatchModel surfaceModel: patchModel
113 function analyzeSurface() {
114 patchModel.analyzeSurface()
117 // Compass reset: animate heading back to north
118 function animateHeadingToNorth() {
119 headingAnimation.stop()
120 // Wrap through 360 for the short way home; the setter normalizes the
121 // final value back to 0
122 headingAnimation.to = (geoCamera.heading > 180) ? 360 : 0
123 headingAnimation.start()
126 // Show the whole QGeoRectangle at the current heading/tilt
127 function fitToRegion(region) {
128 completeCameraAnimations()
129 geoCamera.fitToRegion(region)
132 // LOD checker colors for debug mode (imagery off)
133 function _lodColor(centerX, centerY, span, zoomLevel) {
134 const parity = (Math.round(centerX / span) + Math.round(centerY / span)) & 1
135 return Qt.hsla((zoomLevel * 0.13) % 1.0, 0.5, parity ? 0.45 : 0.6, 1.0)
138 // Gestures jump a running mode transition to its end state rather
139 // than stranding the pose mid-transition (2D mode locks tilt, so a
140 // half-finished 3D->2D tilt could never recover by gesture)
141 function completeCameraAnimations() {
142 tiltAnimation.complete()
143 headingAnimation.complete()
144 terrainAnimation.complete()
145 // A recenter jumped to its end would fight the starting gesture; drop it
146 recenterAnimation.stop()
149 // Keep the camera's look-at point riding the terrain data, not the drawn
150 // mesh: the pivot feeds LOD selection, so following patch churn would loop.
151 // Without this the orbit center stays at z=0 and a close-zoom 2D->3D switch
152 // over high terrain puts the camera under the mesh (blank view)
153 function _updateCenterElevation() {
154 geoCamera.centerElevation = patchModel.terrainDataHeightAt(geoCamera.center)
155 * geoScene.verticalScale * geoScene.terrainScale
158 // Scene-space z of the rendered surface under a screen point, so gestures
159 // anchor to the terrain the user actually clicked instead of the z=0
160 // plane far beneath it. Sample at the ground-plane hit, then refine once
161 // at that elevation (same two-step solve as onRecenterVehicleTo).
162 function _surfaceZAt(screenPos) {
163 const coord = geoCamera.coordinateAtScreenPoint(screenPos)
164 if (!coord.isValid) {
167 const zScale = geoScene.verticalScale * geoScene.terrainScale
168 const z = patchModel.terrainHeightAt(coord) * zScale
169 const refined = geoCamera.coordinateAtScreenPoint(screenPos, z)
170 return refined.isValid ? (patchModel.terrainHeightAt(refined) * zScale) : z
175 objectName: "geoMapCamera"
176 viewportSize: Qt.size(root.width, root.height)
177 sceneOrigin: geoScene.sceneOrigin
178 // Startup pose: overhead view of a land area with terrain relief so
179 // imagery and elevation are visually verifiable (home-position
180 // integration comes later). Until this center applies, the camera is
181 // unpositioned and SurfaceModel builds nothing (see
182 // GeoMapCamera::isPositioned), so the null-island default pose never
183 // triggers doomed terrain fetches at (0,0).
184 center: QtPositioning.coordinate(47.6329078, -122.0876875)
189 objectName: "geoMapScene"
191 content3D: mapContent3D
196 objectName: "geoMapPatchModel"
199 statsEnabled: root.renderStats
200 // Drape the map imagery the rest of QGC uses (empty disables imagery)
201 mapType: QGroundControl.settingsManager.flightMapSettings.mapProvider.rawValue
202 + " " + QGroundControl.settingsManager.flightMapSettings.mapType.rawValue
208 gcsPosition: QGroundControl.positionManager.gcsPosition
209 vehicleCoordinate: root._activeVehicleCoordinate
210 centerGCSWhenVehicleValid: QGroundControl.settingsManager.flyViewSettings.keepMapCenteredOnVehicle.rawValue
211 userInteracting: panHandler.active || orbitHandler.active || shiftOrbitHandler.active
212 || lookHandler.active || metaLookHandler.active || pinchHandler.active
213 animating: recenterAnimation.running
215 onCenterMap: (coordinate, firstPosition) => {
216 recenterAnimation.stop()
217 geoCamera.center = coordinate
219 geoCamera.distance = geoCamera.distanceForZoomLevel(QGroundControl.flightMapInitialZoom)
223 onRecenterVehicleTo: (screenPoint) => {
224 recenterAnimation.stop()
225 recenterAnimation.from = geoCamera.center
226 // The solve assumes the camera pivot elevation stays put, but the
227 // pivot rides the terrain (_updateCenterElevation): re-solve at
228 // the elevation the pivot will settle to at the destination
229 let target = geoScene.centerForCoordinateAtScreenPoint(root._trackedVehicleCoordinate, screenPoint)
230 target = geoScene.centerForCoordinateAtScreenPoint(root._trackedVehicleCoordinate, screenPoint,
231 patchModel.terrainDataHeightAt(target))
232 recenterAnimation.to = target
233 recenterAnimation.start()
239 running: root.visible && root.followOffscreenVehicle
242 const screenPos = geoScene.screenPositionFor(root._trackedVehicleCoordinate)
243 // Unprojectable (behind camera) counts as off-screen: recenter
244 const vehiclePoint = (screenPos === undefined) ? Qt.point(-1, -1) : screenPos
245 _positionTracker.evaluateOccluderFollow(vehiclePoint, root.followViewportRect, root.followOccluders)
251 objectName: "geoMapViewport"
254 environment: SceneEnvironment {
255 clearColor: "#1a2028"
256 backgroundMode: SceneEnvironment.Color
257 // Distance haze toward the background color hides the far-field
258 // LOD rings at the patch range edge
263 depthNear: 10 * geoCamera.distance
264 depthFar: (patchModel.maxRangeMultiplier + 1) * geoCamera.distance
270 ambientColor: Qt.rgba(0.4, 0.4, 0.4, 1.0)
273 // Scene camera fully driven by the GeoMapCamera pose. Clip planes
274 // scale with distance so the surface stays visible from close-up
275 // through whole-earth views.
278 objectName: "geoMapSceneCamera"
279 position: geoCamera.scenePosition
280 rotation: geoCamera.sceneRotation
281 fieldOfView: geoCamera.verticalFieldOfView
282 clipNear: Math.max(1, geoCamera.distance / 1000)
283 // Ray length to the farthest retained ground point is at most
284 // maxRange + camera height <= (maxRangeMultiplier + 1) * distance
285 clipFar: Math.max(100000, geoCamera.distance * (patchModel.maxRangeMultiplier + 1))
288 // One surface patch per active SurfaceModel entry: draped tile
289 // imagery once delivered, LOD-colored fallback while loading.
290 // The shared z-scale converts true-meter heights into mercator scene
291 // units (verticalScale) and animates terrain flat<->full during the
292 // 2D/3D mode transition (terrainScale) without geometry rebuilds:
293 // one binding here instead of one per delegate (delegate creation
294 // cost dominates patch churn, and transitions re-evaluated it N
295 // times per frame). Never exactly 0: a singular scale breaks the
298 scale: Qt.vector3d(1, 1, Math.max(0.0001, geoScene.terrainScale * geoScene.verticalScale))
304 objectName: "geoMapPatchDelegate"
305 required property real centerX
306 required property real centerY
307 required property real span
308 required property int zoomLevel
309 required property var heights
310 required property bool covered
311 required property var edgeLodDeltas
312 required property var tileImage
313 required property bool hasTileImage
315 // A covered pending patch stays hidden: its empty flat grid
316 // would z-fight the retained retiring cover
318 position: Qt.vector3d(centerX, centerY, 0)
319 geometry: PatchGeometry {
320 gridSize: patchModel.gridSize
321 span: patchDelegate.span
322 heights: patchDelegate.heights
323 edgeLodDeltas: patchDelegate.edgeLodDeltas
328 // Clamp: default Repeat wrap bleeds opposite-edge texels
329 // at UV 0/1, drawing 1-px seams on every patch border
330 tilingModeHorizontal: Texture.ClampToEdge
331 tilingModeVertical: Texture.ClampToEdge
332 textureData: PatchTextureData {
333 image: patchDelegate.tileImage
339 cullMode: Material.NoCulling
340 // Unlit: tiles carry their own shading, and lighting
341 // would show the per-patch normal seams
342 lighting: DefaultMaterial.NoLighting
343 diffuseMap: patchDelegate.hasTileImage ? patchTexture : null
344 // Loading fallback: quiet neutral when imagery is on
345 // (LOD flash on zoom); LOD checker colors in debug mode
346 diffuseColor: patchDelegate.hasTileImage
348 : (patchModel.mapType !== ""
350 : root._lodColor(patchDelegate.centerX, patchDelegate.centerY,
351 patchDelegate.span, patchDelegate.zoomLevel))
358 // Map item 3D content (GeoMapItem delegate3D instances). Sibling of
359 // the terrain node: items pre-scale their own z, and the terrain
360 // z-scale would squash models during the 2D/3D transition.
365 // Gestures (Google Earth semantics): the ground point under the cursor
366 // at gesture start stays under the cursor throughout. Any gesture
367 // completes a running mode/compass animation to its end state so
368 // the two never fight over the same pose properties.
372 acceptedButtons: Qt.LeftButton
373 // Plain drag only: Shift/Ctrl+left-drag are the orbit/look gestures below
374 acceptedModifiers: Qt.NoModifier
377 root.completeCameraAnimations()
378 // Anchor at the current position, not pressPosition: after a
379 // two-finger pinch drops to one finger this handler re-activates
380 // with a stale pressPosition, and anchoring there jumps the map.
381 geoCamera.beginPan(centroid.position, root._surfaceZAt(centroid.position))
386 geoCamera.panTo(centroid.position)
391 // Right/middle-drag orbits about the pressed ground point: full width =
392 // 360 deg heading, full height = 180 deg tilt.
393 // Mouse/touchpad only: acceptedButtons doesn't filter touch points, so
394 // without acceptedDevices this handler steals single-finger drags from
395 // panHandler on touchscreens (touch orbits via PinchHandler twist instead).
396 // TouchPad keeps trackpad secondary-click drag working.
400 acceptedDevices: PointerDevice.Mouse | PointerDevice.TouchPad
401 acceptedButtons: Qt.RightButton | Qt.MiddleButton
402 // Unmodified only: macOS synthesizes Ctrl+left-click as a right-click
403 // (carrying MetaModifier), which must fall through to metaLookHandler
404 acceptedModifiers: Qt.NoModifier
407 root.completeCameraAnimations()
408 geoCamera.beginOrbit(centroid.pressPosition, root._surfaceZAt(centroid.pressPosition))
409 // Apply motion accumulated before activation: a short drag
410 // can activate and release with no further centroid change
411 geoCamera.orbitTo(centroid.position)
416 geoCamera.orbitTo(centroid.position)
423 // Default acceptedDevices=Mouse drops trackpad scroll (and mouse
424 // wheel on Wayland/xcb, which misreport as TouchPad) — see the
425 // FlightMap WheelHandler comment for the full platform rundown
426 acceptedDevices: PointerDevice.Mouse | PointerDevice.TouchPad
427 onWheel: (event) => {
428 root.completeCameraAnimations()
429 geoCamera.zoom(event.angleDelta.y, point.position)
433 // Shift+left-drag orbits about the pressed ground point, same as
434 // right/middle-drag (keyboard-modifier alternative for one-button mice)
436 id: shiftOrbitHandler
438 acceptedDevices: PointerDevice.Mouse | PointerDevice.TouchPad
439 acceptedButtons: Qt.LeftButton
440 acceptedModifiers: Qt.ShiftModifier
443 root.completeCameraAnimations()
444 geoCamera.beginOrbit(centroid.pressPosition, root._surfaceZAt(centroid.pressPosition))
445 // Apply motion accumulated before activation (see orbitHandler)
446 geoCamera.orbitTo(centroid.position)
451 geoCamera.orbitTo(centroid.position)
456 // Ctrl+left-drag is first-person look: the camera stays put and the
457 // view rotates, like turning your head (Google Earth Ctrl+drag).
458 // Drag toward where you want to look.
462 acceptedDevices: PointerDevice.Mouse | PointerDevice.TouchPad
463 acceptedButtons: Qt.LeftButton
464 acceptedModifiers: Qt.ControlModifier
467 root.completeCameraAnimations()
468 geoCamera.beginLook(centroid.pressPosition)
469 // Apply motion accumulated before activation (see orbitHandler)
470 geoCamera.lookTo(centroid.position)
475 geoCamera.lookTo(centroid.position)
480 // macOS delivers the physical Ctrl key as Qt.MetaModifier (Qt swaps
481 // Ctrl/Cmd), so accept it too: Ctrl+drag looks on every platform
482 // (and Cmd+drag still works via lookHandler, matching Google Earth).
483 // RightButton included because macOS synthesizes Ctrl+left-click as a
484 // right-click, so that's the button this drag actually arrives on.
488 enabled: Qt.platform.os === "osx"
489 acceptedDevices: PointerDevice.Mouse | PointerDevice.TouchPad
490 acceptedButtons: Qt.LeftButton | Qt.RightButton
491 acceptedModifiers: Qt.MetaModifier
494 root.completeCameraAnimations()
495 geoCamera.beginLook(centroid.pressPosition)
496 // Apply motion accumulated before activation (see orbitHandler)
497 geoCamera.lookTo(centroid.position)
502 geoCamera.lookTo(centroid.position)
507 // Pinch zooms about the centroid; two-finger twist rotates around it
508 // (handler rotation is positive clockwise on screen; heading follows
509 // so the world tracks the fingers)
513 enabled: !root.pinchZoomDisabledByVirtualJoysticks
516 root.completeCameraAnimations()
519 onScaleChanged: (delta) => geoCamera.zoomBy(1 / delta, centroid.position)
520 onRotationChanged: (delta) => geoCamera.rotateBy(delta, centroid.position)
523 // Plain click/tap: the default DragThreshold gesture policy means any
524 // pan drag cancels the tap, so this never fires during camera gestures
526 acceptedButtons: Qt.LeftButton
527 acceptedModifiers: Qt.NoModifier
528 onTapped: (eventPoint, button) => root.mapClicked(eventPoint.position)
532 // Pivot ring (Google Earth-style): marks the ground point an orbit drag
533 // rotates about, visible only while the drag is active. The pivot stays
534 // pinned to its press position on screen, so the ring never moves.
536 id: orbitPivotIndicator
537 objectName: "geoMapOrbitPivotIndicator"
539 readonly property point _pivot: orbitHandler.active ? orbitHandler.centroid.pressPosition
540 : shiftOrbitHandler.centroid.pressPosition
542 visible: orbitHandler.active || shiftOrbitHandler.active
543 x: _pivot.x - (width / 2)
544 y: _pivot.y - (height / 2)
545 width: ScreenTools.defaultFontPixelHeight * 1.5
549 // Dark halo keeps the white ring visible over light imagery
550 border.color: Qt.rgba(0, 0, 0, 0.4)
551 border.width: (ScreenTools.defaultFontPixelHeight / 8) + 2
558 border.color: "white"
559 border.width: ScreenTools.defaultFontPixelHeight / 8
563 anchors.centerIn: parent
564 width: ScreenTools.defaultFontPixelHeight / 4
571 /// Ground station location (parity with the FlightMap marker)
576 surfaceModel: patchModel
577 coordinate: gcsIndicator._gcsPosition
578 anchorPoint: Qt.point(gcsImage.width / 2, gcsImage.height / 2)
579 width: gcsImage.width
580 height: gcsImage.height
581 visible: gcsIndicator._gcsPosition.isValid
583 readonly property var _gcsPosition: QGroundControl.positionManager.gcsPosition
584 readonly property real _gcsHeading: QGroundControl.positionManager.gcsHeading
588 source: isNaN(gcsIndicator._gcsHeading) ? "/res/QGCLogoFull.svg" : "/res/QGCLogoArrow.svg"
591 fillMode: Image.PreserveAspectFit
592 height: ScreenTools.defaultFontPixelHeight * (isNaN(gcsIndicator._gcsHeading) ? 1.75 : 2.5)
593 sourceSize.height: height
594 transform: Rotation {
595 origin.x: gcsImage.width / 2
596 origin.y: gcsImage.height / 2
597 // Camera heading rotates map north on screen; the arrow follows
598 angle: isNaN(gcsIndicator._gcsHeading) ? 0 : gcsIndicator._gcsHeading + geoCamera.heading
604 objectName: "geoMapRenderStats"
605 anchors.left: parent.left
606 anchors.top: parent.top
608 visible: root.renderStats
609 resourceDetailsVisible: true
616 duration: root.cameraAnimationMs
617 easing.type: Easing.InOutQuad
624 duration: root.cameraAnimationMs
625 easing.type: Easing.InOutQuad
631 property: "terrainScale"
632 duration: root.cameraAnimationMs
633 easing.type: Easing.InOutQuad
636 CoordinateAnimation {
637 id: recenterAnimation
641 easing.type: Easing.InOutQuad
644 // Single transition path for every mode writer (button, goTo2D/3D,
645 // C++): mode changes always animate tilt and terrain to the mode's
646 // targets, so camera state and terrain displacement cannot desync
649 function onModeChanged() {
650 const to3D = geoCamera.mode === GeoMapCamera.Mode3D
652 tiltAnimation.to = to3D ? geoCamera.default3DTilt : 0
653 tiltAnimation.start()
654 terrainAnimation.stop()
655 terrainAnimation.to = to3D ? 1 : 0
656 terrainAnimation.start()
658 function onCenterChanged() {
659 root._updateCenterElevation()
665 function onTerrainDataChanged() {
666 root._updateCenterElevation()
667 root._updateHomeTerrainBias()
673 function onTerrainScaleChanged() {
674 root._updateCenterElevation()
676 // verticalScale depends on the scene origin
677 function onSceneOriginChanged() {
678 root._updateCenterElevation()
683 target: root._activeVehicle
684 function onHomePositionChanged() {
685 root._updateHomeTerrainBias()