Kepler.gl is a powerful open source geospatial analysis tool for large-scale data sets.
fix: globe mode LOD, high-zoom rendering, pan jump, and annotation occlusion (#3551)
Igor Dykhta1c49c29d0880
diff --git a/src/components/src/annotations/annotation-overlay.tsx b/src/components/src/annotations/annotation-overlay.tsxindex 032d98325..99704f456 100644--- a/src/components/src/annotations/annotation-overlay.tsx+++ b/src/components/src/annotations/annotation-overlay.tsx@@ -16,7 +16,13 @@ import {Annotation} from '@kepler.gl/types';import {ActionHandler, updateAnnotation, setSelectedAnnotation} from '@kepler.gl/actions';import AnnotationNode from './annotation-node';import AnnotationText from './annotation-text';-import {MapViewport, movePoint, moveText, resizeCircle} from './annotation-utils';+import {+ MapViewport,+ isPointVisibleOnGlobe,+ movePoint,+ moveText,+ resizeCircle+} from './annotation-utils';const AnnotationOverlayContainer = styled.div`position: absolute;@@ -50,6 +56,7 @@ export type AnnotationOverlayProps = {isAnnotationMode: boolean;mapIndex: number;viewport: MapViewport;+ isGlobeEnabled?: boolean;updateAnnotation: ActionHandler<typeof updateAnnotation>;setSelectedAnnotation: ActionHandler<typeof setSelectedAnnotation>;};@@ -61,12 +68,22 @@ const AnnotationOverlay: FC<AnnotationOverlayProps> = ({isAnnotationMode,mapIndex,viewport,+ isGlobeEnabled,updateAnnotation: onUpdateAnnotation,setSelectedAnnotation: onSetSelectedAnnotation}) => {const annotationsToRender = useMemo(- () => annotations.filter(ann => (ann.mapIndex ?? 0) === mapIndex && ann.isVisible).reverse(),- [annotations, mapIndex]+ () =>+ annotations+ .filter(+ ann =>+ (ann.mapIndex ?? 0) === mapIndex &&+ ann.isVisible &&+ // Hide annotations on the far side of the globe (occluded by the planet)+ (!isGlobeEnabled || isPointVisibleOnGlobe(ann.anchorPoint, viewport))+ )+ .reverse(),+ [annotations, mapIndex, isGlobeEnabled, viewport]);const draggedAnnotationRef = React.useRef<Annotation | null>(null);diff --git a/src/components/src/annotations/annotation-utils.ts b/src/components/src/annotations/annotation-utils.tsindex 474b5e63b..7e47a19f3 100644--- a/src/components/src/annotations/annotation-utils.ts+++ b/src/components/src/annotations/annotation-utils.ts@@ -78,6 +78,47 @@ export function isLeftOriented(angle: number): boolean {return angle > 90 || angle < -90;}+/** Great-circle angular distance between two lng/lat points, in degrees. */+function angularDistanceDeg(a: [number, number], b: [number, number]): number {+ const toRad = Math.PI / 180;+ const phi1 = a[1] * toRad;+ const phi2 = b[1] * toRad;+ const dLambda = (b[0] - a[0]) * toRad;+ const cosD =+ Math.sin(phi1) * Math.sin(phi2) + Math.cos(phi1) * Math.cos(phi2) * Math.cos(dLambda);+ return Math.acos(Math.min(1, Math.max(-1, cosD))) / toRad;+}++// Round-trip tolerance in degrees. Front-facing points round-trip back to+// themselves within numerical error; occluded points resolve to a different+// (front) surface point that is several degrees away.+const GLOBE_VISIBILITY_TOLERANCE_DEG = 0.5;++/**+ * Geometric occlusion test for a point on the globe.+ *+ * In globe mode `viewport.project()` still returns valid screen coordinates for+ * points on the far (back) side of the planet, so DOM overlays like annotations+ * keep rendering "through" the opaque globe. Rather than approximate with a+ * lng/lat box, we project the point to screen space and unproject it back:+ * deck's `GlobeViewport.unproject` returns the *nearest* (front-facing) point on+ * the sphere along that ray. If the point comes back to (approximately) itself+ * it is on the visible hemisphere; otherwise the ray hit the front of the globe+ * first and the point is occluded. This uses the real projection math, so it+ * follows the true horizon and adapts to zoom/altitude automatically.+ */+export function isPointVisibleOnGlobe(point: [number, number], viewport: MapViewport): boolean {+ const projected = viewport.project(point);+ if (!projected || !Number.isFinite(projected[0]) || !Number.isFinite(projected[1])) {+ return false;+ }+ const roundTrip = viewport.unproject([projected[0], projected[1]]);+ if (!roundTrip || !Number.isFinite(roundTrip[0]) || !Number.isFinite(roundTrip[1])) {+ return false;+ }+ return angularDistanceDeg(point, [roundTrip[0], roundTrip[1]]) < GLOBE_VISIBILITY_TOLERANCE_DEG;+}+export function movePoint(annotation: Annotation,delta: {x: number; y: number},diff --git a/src/components/src/index.ts b/src/components/src/index.tsindex 9a7ce8001..8c21190f1 100644--- a/src/components/src/index.ts+++ b/src/components/src/index.ts@@ -368,7 +368,14 @@ export {default as AnnotationManagerFactory} from './annotations/annotation-paneexport {AnnotationOverlay} from './annotations';export {AnnotationNode} from './annotations';export {AnnotationText} from './annotations';-export {makeMarker, movePoint, moveText, resizeCircle, isLeftOriented} from './annotations';+export {+ makeMarker,+ movePoint,+ moveText,+ resizeCircle,+ isLeftOriented,+ isPointVisibleOnGlobe+} from './annotations';export type {MapViewport, AnnotationMarker} from './annotations';export {default as AnnotationControlFactory} from './map/annotations/annotation-control';diff --git a/src/components/src/map-container.tsx b/src/components/src/map-container.tsxindex c8873dfaa..6272f5d48 100644--- a/src/components/src/map-container.tsx+++ b/src/components/src/map-container.tsx@@ -964,7 +964,11 @@ export default function MapContainerFactory(mapboxApiAccessToken: mapboxApiAccessToken || '',globe: mapState.globe,mapStyleType: mapStyle?.styleType,- basemapProvider: globeBasemapProvider+ basemapProvider: globeBasemapProvider,+ // Use the live (internal) latitude so the tile LOD compensation+ // stays in sync with the deck viewport during a drag; mapState+ // latitude lags behind while rotating.+ latitude: internalMapState.latitude}): [];const globeTopLayers =@@ -1399,6 +1403,7 @@ export default function MapContainerFactory(isAnnotationMode={Boolean(mapControls?.annotation?.active)}mapIndex={index || 0}viewport={this._getAnnotationViewport(mapState, internalViewState)}+ isGlobeEnabled={Boolean(mapState.globe?.enabled)}updateAnnotation={visStateActions.updateAnnotation}setSelectedAnnotation={visStateActions.setSelectedAnnotation}/>diff --git a/src/components/src/modals/export-video-modal.tsx b/src/components/src/modals/export-video-modal.tsxindex f0eab0e2c..0ca110a6b 100644--- a/src/components/src/modals/export-video-modal.tsx+++ b/src/components/src/modals/export-video-modal.tsx@@ -396,7 +396,7 @@ const ExportVideoModalFactory = () => {// In globe mode the deck.gl GlobeView renders the planet (and basemap tiles)// itself; the flat maplibre base map must be disabled so it doesn't render a- // 2D Mercator map behind/around the globe (mirrors studio's disableStaticMap).+ // 2D Mercator map behind/around the globe.const isGlobeEnabled = Boolean(mapState?.globe?.enabled);const onFilterFrameUpdate = useCallback(diff --git a/src/components/src/side-panel/map-style-panel/globe-config-panel.tsx b/src/components/src/side-panel/map-style-panel/globe-config-panel.tsxindex a1e7ae194..d97c1dd07 100644--- a/src/components/src/side-panel/map-style-panel/globe-config-panel.tsx+++ b/src/components/src/side-panel/map-style-panel/globe-config-panel.tsx@@ -51,9 +51,8 @@ const SliderWrapper = styled.div<{$enabled?: boolean}>`// Slider rows (Day/Night, Sun Azimuth) put the label and the slider side by side.// Give the label only the width its (short) text needs so the slider gets the-// rest of the row, matching studio-monorepo's usable slider width. The child-// indent is kept small (~half an eye-icon width) so the sub-row eye icon lines-// up close to the parent (atmosphere) row like it does in studio, rather than+// rest of the row. The child indent is kept small (~half an eye-icon width) so the+// sub-row eye icon lines up close to the parent (atmosphere) row, rather than// being pushed ~1.5 icon widths to the right.const SliderRow = styled(StyledConfigRow)`align-items: center;diff --git a/src/components/src/side-panel/panel-header.tsx b/src/components/src/side-panel/panel-header.tsxindex 738c41325..4aca9c085 100644--- a/src/components/src/side-panel/panel-header.tsx+++ b/src/components/src/side-panel/panel-header.tsx@@ -222,6 +222,12 @@ export const SaveExportDropdownFactory = (key: 'image',onClick: props => props.onExportImage},+ {+ label: 'toolbar.exportVideo',+ icon: Play,+ key: 'video',+ onClick: props => props.onExportVideo+ },{label: 'toolbar.exportData',icon: DataTable,@@ -234,12 +240,6 @@ export const SaveExportDropdownFactory = (key: 'map',onClick: props => props.onExportMap},- {- label: 'toolbar.exportVideo',- icon: Play,- key: 'video',- onClick: props => props.onExportVideo- },{label: 'toolbar.saveMap',icon: Save2,diff --git a/src/constants/src/default-settings.ts b/src/constants/src/default-settings.tsindex d8debc976..4c0fe627d 100644--- a/src/constants/src/default-settings.ts+++ b/src/constants/src/default-settings.ts@@ -1360,13 +1360,18 @@ export const GLOBE_MIN_ZOOM = 2;/*** Maximum zoom in globe mode.*- * TODO: investigate further. Past this level the globe basemap breaks down in- * deck.gl 9.x: the vector basemap tileset (mapbox-streets vector tiles) stops- * loading / renders as empty rectangles, and there are interaction issues on- * zoom in and panning (the camera drifts). Capping zoom here keeps the basemap- * and interactions coherent until the underlying tile/controller issue is fixed.+ * The previous "empty rectangles" at high zoom were caused by the vector basemap+ * layer declaring `maxZoom: 23` while the raw tile endpoints only have data to+ * z16 (mapbox-streets-v8) / z14 (CARTO) — deck then requested non-existent tiles+ * that 404. That is fixed in `getGlobeBaseLayers` by setting `maxZoom` to each+ * source's true data max so deck overzooms instead.+ *+ * The remaining practical ceiling is float32 precision: deck's globe places+ * geometry in common space on a sphere of radius 256 with no fp64/relative-to-+ * center trick, so beyond ~visual-zoom 16 (roughly this mapState zoom minus+ * `zoomAdjust(lat)` ≈ 1.65 at the equator) geometry starts to jitter/drift.*/-export const GLOBE_MAX_ZOOM = 12;+export const GLOBE_MAX_ZOOM = 16;/*** Maximum absolute center latitude allowed in globe mode. Constrains the cameradiff --git a/src/deckgl-layers/src/globe/atmosphere-layer.ts b/src/deckgl-layers/src/globe/atmosphere-layer.tsindex 627e6976c..1ddaa36be 100644--- a/src/deckgl-layers/src/globe/atmosphere-layer.ts+++ b/src/deckgl-layers/src/globe/atmosphere-layer.ts@@ -165,6 +165,17 @@ export class AtmosphereLayerRealistic extends SimpleMeshLayer<any, AtmosphereLayfragColor = vec4(c1, 1.0 - c0 * fTerminatorAttenuateFactor);fragColor.a *= fTerminatorOpacityFactor;++ // Keep the day hemisphere completely unshaded — the attenuation-based+ // alpha above is non-zero even at noon, which slightly darkens the lit+ // side. Gate it with a day/night mask so darkening only appears across+ // the terminator and onto the night side.+ // fLightAngle = dot(sunDir, surfaceNormal): +1 at the subsolar point+ // (noon), 0 at the terminator, -1 at midnight. smoothstep maps the day+ // side (>= 0.2) to 0 (no darkening), ramps through the terminator, and+ // reaches full darkening on the night side (<= -0.2).+ float fNightMask = smoothstep(0.2, -0.2, fLightAngle);+ fragColor.a *= fNightMask;`,'fs:DECKGL_FILTER_COLOR': ``}diff --git a/src/deckgl-layers/src/globe/enhanced-multi-icon-layer.ts b/src/deckgl-layers/src/globe/enhanced-multi-icon-layer.tsindex 4dbb7bdb2..c7fa921de 100644--- a/src/deckgl-layers/src/globe/enhanced-multi-icon-layer.ts+++ b/src/deckgl-layers/src/globe/enhanced-multi-icon-layer.ts@@ -6,9 +6,9 @@ import {_MultiIconLayer as MultiIconLayer} from '@deck.gl/layers';// Back-face culling for globe-mode text labels.//-// Ported from studio-monorepo's EnhancedMultiIconLayer. deck.gl's TextLayer uses a-// MultiIconLayer to render glyphs; on a globe, labels anchored on the far hemisphere-// would otherwise be drawn "through" the planet. This subclass injects a small GLSL+// deck.gl's TextLayer uses a MultiIconLayer to render glyphs; on a globe, labels+// anchored on the far hemisphere would otherwise be drawn "through" the planet.+// This subclass injects a small GLSL// snippet into the icon vertex shader that degenerates (collapses) glyph vertices// whose anchor is facing away from the camera, so back-side labels disappear.//diff --git a/src/deckgl-layers/src/globe/globe-layers.ts b/src/deckgl-layers/src/globe/globe-layers.tsindex ace90bbee..71b96c4a5 100644--- a/src/deckgl-layers/src/globe/globe-layers.ts+++ b/src/deckgl-layers/src/globe/globe-layers.ts@@ -284,9 +284,85 @@ export function getGlobeClearColor(const INVISIBLE_COLOR: [number, number, number, number] = [0, 0, 0, 0];const BASEMAP_MVT_PARAMETERS = {- depthMask: false+ // Occlude the far side of the globe via the DEPTH DISK (getGlobeDepthDiskLayer)+ // rather than back-face culling. Globe mode sets a global `cull: true` for the+ // opaque sphere surface, but back-face culling relies on stable triangle+ // winding — and deck.gl 9's globe projection loses precision at high zoom+ // (float32), flipping the winding of the small admin/water triangles so they+ // get wrongly culled and the geometry vanishes past ~zoom 12 (you then see+ // through to the far side / "different geometry"). Depth testing against the disk+ // is a precision-robust occluder that works at any zoom, so:+ // - cull: false → don't winding-cull the near-side geometry+ // - depthTest: true → far-side geometry (behind the disk) fails depth, hidden+ // - depthMask: false → don't write depth (avoid self z-fighting on the shell)+ // Raster tiles are unaffected (their 4-corner quads keep stable winding), which+ // is why satellite already zooms to max cleanly. Labels disable cull for the+ // same reason (see mvt-label-layer.ts).+ depthTest: true,+ depthMask: false,+ cull: false};+// deck.gl 9's globe selects finer tiles than needed for a given view (its+// GlobeViewport scale is ~3x smaller than the equivalent mercator zoom), so bias+// vector tile selection coarser to keep the tile count — and thus performance —+// in check. This trades a little detail for far fewer tiles; make it less negative+// (toward 0) for sharper detail, or more negative for more perf.+// These are *base* offsets: globeLatitudeZoomCompensation is added on top at draw+// time, so the effective zoomOffset only equals these exact values at the equator.+// Satellite raster uses base 0 — it doesn't need the vector bias (a coarser raster+// tile just looks softer rather than dropping features).+const MAPBOX_GLOBE_VECTOR_ZOOM_OFFSET = -2;+const CARTO_GLOBE_VECTOR_ZOOM_OFFSET = -2;+const GLOBE_SATELLITE_ZOOM_OFFSET = 0;++// Whole-world tile extent (Web Mercator latitude limit). Required whenever a+// negative `zoomOffset` is used: deck's `getTileIndices` returns NO tiles when+// the target zoom drops below `minZoom` *unless* an `extent` is set (in which+// case it clamps to `minZoom` instead). Without this, zooming out or panning+// toward the poles (where deck 9's globe controller lowers the effective zoom)+// makes the whole globe basemap disappear.+const GLOBE_TILE_EXTENT: [number, number, number, number] = [+ -180, -85.051129, 180, 85.051129+];++// Max *native* zoom of each vector tile source. Set this (not an arbitrarily+// high number) so deck overzooms — i.e. keeps rendering the deepest real tile+// when the view zooms past it — instead of requesting tiles that don't exist+// and 404 (which shows up as empty rectangles). The raw `.vector.pbf` /`.mvt`+// endpoints do NOT auto-overzoom the way Mapbox GL does.+// - mapbox-streets-v8 has data up to z16+// - CARTO carto.streets v1 has data up to z14+const MAPBOX_VECTOR_MAX_DATA_ZOOM = 16;+const CARTO_VECTOR_MAX_DATA_ZOOM = 14;++/**+ * deck.gl 9's globe couples zoom to latitude via `zoomAdjust` (see+ * globe-viewport.js): `scale = 2^(zoom - zoomAdjust(lat))`, and its controller+ * *lowers* the stored `zoom` as you pan toward the poles to keep the globe's+ * on-screen size constant. Tile LOD, however, is selected from the raw `zoom`,+ * so rotating toward a pole silently drops the LOD and thins out labels.+ * Replicated from `@deck.gl/core` globe-viewport.js `zoomAdjust`.+ */+function zoomAdjust(latitude: number): number {+ return Math.log2(Math.PI * Math.cos((latitude * Math.PI) / 180));+}++/**+ * Latitude compensation to add to a globe tile layer's `zoomOffset`, so tile LOD+ * tracks the *visual* (on-screen) scale instead of the latitude-adjusted mercator+ * zoom. This cancels the pan-induced zoom drop, keeping tile detail/labels+ * constant while rotating toward the poles.+ */+function globeLatitudeZoomCompensation(latitude?: number): number {+ if (latitude == null || !Number.isFinite(latitude)) {+ return 0;+ }+ // Clamp away from the poles to avoid log2(0) = -Infinity at |lat| = 90.+ const clamped = Math.max(-85, Math.min(85, latitude));+ return zoomAdjust(0) - zoomAdjust(clamped);+}+/*** Globe basemap tile provider.*@@ -423,7 +499,8 @@ export const getGlobeBaseLayers = ({mapboxApiAccessToken,globe,mapStyleType,- basemapProvider+ basemapProvider,+ latitude}: {mapboxApiAccessToken: string;globe: Globe;@@ -433,12 +510,20 @@ export const getGlobeBaseLayers = ({* a token is present, otherwise falls back to the token-free `carto` tiles.*/basemapProvider?: GlobeBasemapProvider;+ /**+ * Current camera center latitude. Used to keep tile LOD constant while rotating+ * toward the poles (deck.gl 9 lowers the effective zoom near the poles). When+ * omitted, no latitude compensation is applied (equator behavior).+ */+ latitude?: number;}): Layer[] => {const {config} = globe;const isSatellite = mapStyleType === 'satellite';const isSatelliteStreet = mapStyleType === 'satellite-street';+ const latZoomCompensation = globeLatitudeZoomCompensation(latitude);+// Fall back to the free CARTO tiles whenever no Mapbox token is available so// the globe basemap still renders (matches kepler's default token-free// MapLibre/CARTO basemaps). Callers should pass an explicit `basemapProvider`@@ -490,6 +575,8 @@ export const getGlobeBaseLayers = ({],minZoom: 0,maxZoom: useCarto ? 18 : 19,+ zoomOffset: GLOBE_SATELLITE_ZOOM_OFFSET + latZoomCompensation,+ extent: GLOBE_TILE_EXTENT,// Esri tiles are 256px; Mapbox @2x tiles are 512px.tileSize: useCarto ? 256 : 512 / devicePixelRatio,renderSubLayers: (props: any) => {@@ -520,7 +607,13 @@ export const getGlobeBaseLayers = ({? CARTO_VECTOR_TILE_URLS: `https://a.tiles.mapbox.com/v4/mapbox.mapbox-streets-v8/{z}/{x}/{y}.vector.pbf?access_token=${mapboxApiAccessToken}`,minZoom: 0,- maxZoom: 23,+ // Overzoom past the source's native max instead of 404-ing on tiles that+ // don't exist (which renders as empty rectangles at high zoom).+ maxZoom: useCarto ? CARTO_VECTOR_MAX_DATA_ZOOM : MAPBOX_VECTOR_MAX_DATA_ZOOM,+ zoomOffset:+ (useCarto ? CARTO_GLOBE_VECTOR_ZOOM_OFFSET : MAPBOX_GLOBE_VECTOR_ZOOM_OFFSET) ++ latZoomCompensation,+ extent: GLOBE_TILE_EXTENT,binary: false,parameters: BASEMAP_MVT_PARAMETERS,loadOptions: useCartodiff --git a/src/deckgl-layers/src/globe/globe-view.ts b/src/deckgl-layers/src/globe/globe-view.tsindex cad019c08..3dd9ecd6c 100644--- a/src/deckgl-layers/src/globe/globe-view.ts+++ b/src/deckgl-layers/src/globe/globe-view.ts@@ -11,6 +11,7 @@ import {GLOBE_MAX_LATITUDE} from '@kepler.gl/constants';// namespace with a loose type. Runtime behavior is unchanged.const DeckGlobeView = (DeckCore as any)._GlobeView as any;const GlobeController = (DeckCore as any)._GlobeController as any;+const DeckGlobeViewport = (DeckCore as any)._GlobeViewport as any;/*** Latitude-based zoom adjustment used by deck.gl's GlobeViewport, replicated@@ -27,8 +28,8 @@ function zoomAdjust(latitude: number): number {* In deck.gl 9.x, the default GlobeController's GlobeState.zoom() ignores the* cursor position and always zooms toward the center. This controller patches* that behavior by overriding the ControllerState's zoom method to pan the- * globe under the cursor while zooming, matching the behavior of deck.gl 8.x- * and MapController.+ * globe under the cursor while zooming, so zoom-to-cursor works the same way it+ * does for the 2D MapController.*/class ZoomToCursorGlobeController extends GlobeController {constructor(...args: any[]) {@@ -70,17 +71,15 @@ class ZoomToCursorGlobeController extends GlobeController {return clamp(zoom, minZoom + zoomAdjustment, maxZoom + zoomAdjustment);}- // Zoom-to-cursor, ported verbatim from deck.gl 8.9.x MapState.zoom() +- // GlobeViewport.panByPosition(coords, pixel) — which is what studio-monorepo- // uses and where zoom-to-cursor tracks the cursor accurately over a whole- // gesture. deck.gl 9.x regressed this in two ways that we avoid here:+ // Exact zoom-to-cursor. deck.gl 9.x's GlobeController does not keep the point+ // under the cursor fixed while zooming, in two ways we work around here:// 1. Its GlobeState.zoom() ignores the cursor and zooms toward the center.- // 2. Its GlobeViewport.panByPosition became a lossy, *linearized* 3-arg+ // 2. Its GlobeViewport.panByPosition is a lossy, *linearized* 3-arg// rotation (longitude += (0.25/scale)*(startPixel-pixel), re-derives// zoom). Using it per wheel tick accumulates error, so after a long// continuous zoom the point ends up noticeably shifted from what was// originally under the cursor.- // The 8.9.x recenter below is an *exact absolute* translation: unproject the+ // The recenter below is an *exact absolute* translation: unproject the// cursor pixel in the zoomed viewport to get the geo point currently under it,// then shift the center by (anchor - thatPoint). No zoom coupling, no// rotationSpeed, and it applies to zoom-in and zoom-out symmetrically, so@@ -148,7 +147,7 @@ class ZoomToCursorGlobeController extends GlobeController {zoom});- // 8.9.x GlobeViewport.panByPosition(startZoomLngLat, pos):+ // Anchor the grabbed geo point back under the cursor:// fromPosition = viewport.unproject(pos) // geo point now under the cursor// longitude = startZoomLngLat[0] - fromPosition[0] + viewport.longitude// latitude = startZoomLngLat[1] - fromPosition[1] + viewport.latitude@@ -171,13 +170,68 @@ class ZoomToCursorGlobeController extends GlobeController {});}- // Clear the persisted pinch anchor at gesture end (matches 8.9.x).+ // Clear the persisted pinch anchor at gesture end.zoomEnd() {return (this as any)._getUpdatedState({startZoom: null,startZoomLngLat: null});}++ // Exact, cursor-anchored pan: the geo point grabbed on mousedown stays+ // locked under the cursor for the whole drag.+ //+ // deck.gl 9.x's GlobeController pans with a *linearized, center-anchored*+ // rotation (GlobeViewport.panByPosition([lng,lat,zoom], pixel, startPixel):+ // longitude += (0.25/scale)*(startPixel-pixel)). Because the anchor is the+ // view CENTER rather than the grabbed point, the first drag frame snaps the+ // center to satisfy the linear approximation, producing the visible "jump to+ // the side/up" at the start of a pan (most noticeable at high zoom), after+ // which incremental deltas track fine. The exact anchor below removes that+ // first-frame snap.+ panStart({pos}: {pos: [number, number]}) {+ return (this as any)._getUpdatedState({+ startPanLngLat: (this as any)._unproject(pos)+ });+ }++ pan({pos, startPos}: {pos: [number, number]; startPos?: [number, number]}) {+ const startPanLngLat =+ (this as any).getState().startPanLngLat || (this as any)._unproject(startPos);+ if (!startPanLngLat) {+ return this;+ }++ const props = (this as any).getViewportProps();+ const viewport = (this as any).makeViewport(props);+ const fromPosition = viewport.unproject(pos);++ // Guard: pixels off the sphere silhouette unproject to NaN/undefined.+ const valid =+ Array.isArray(fromPosition) &&+ Number.isFinite(fromPosition[0]) &&+ Number.isFinite(fromPosition[1]);+ if (!valid) {+ return this;+ }++ const longitude = startPanLngLat[0] - fromPosition[0] + props.longitude;+ let latitude = startPanLngLat[1] - fromPosition[1] + props.latitude;+ latitude = clamp(latitude, -GLOBE_MAX_LATITUDE, GLOBE_MAX_LATITUDE);++ // deck.gl 9's GlobeViewport scale = 2^(zoom - zoomAdjust(latitude)), so a+ // constant zoom would make the globe grow on screen as the center moves+ // toward the poles. Re-couple zoom to the new latitude (as deck.gl 9's own+ // pan does) to keep the on-screen scale — and thus tile LOD — constant.+ const visualZoom = props.zoom - zoomAdjust(props.latitude);+ const zoom = visualZoom + zoomAdjust(latitude);++ return (this as any)._getUpdatedState({longitude, latitude, zoom});+ }++ panEnd() {+ return (this as any)._getUpdatedState({startPanLngLat: null});+ }} as any;}}@@ -196,6 +250,22 @@ export class KeplerGlobeView extends DeckGlobeView {get ControllerType() {return ZoomToCursorGlobeController;}++ // deck.gl 9's GlobeView.getViewportType() swaps the viewport class based on zoom:+ // `return viewState.zoom > 12 ? WebMercatorViewport : GlobeViewport;`+ // Crossing zoom 12 therefore recomputes tile bounds with completely different+ // projection math (globe vs flat mercator). That makes deck's TileLayer/MVTLayer+ // reselect tiles inconsistently across the boundary — mixed LODs (e.g. a z4 tile+ // next to z11), a visible "flicker" at 12, and tiles that get dropped and stick+ // as black/empty quads (most often crossing 12 on the way *out*).+ //+ // Force GlobeViewport at every zoom to eliminate the z=12 viewport swap so tile+ // selection stays consistent. The trade-off is that zoom > 12 now uses float32+ // globe precision (deck's documented "no high-precision rendering > 12" limit)+ // instead of switching to mercator — far preferable to the black quads.+ getViewportType() {+ return DeckGlobeViewport;+ }}KeplerGlobeView.displayName = 'KeplerGlobeView';diff --git a/src/deckgl-layers/src/globe/index.ts b/src/deckgl-layers/src/globe/index.tsindex 57ca604fd..483d7b23e 100644--- a/src/deckgl-layers/src/globe/index.ts+++ b/src/deckgl-layers/src/globe/index.ts@@ -1,33 +1,20 @@// SPDX-License-Identifier: MIT// Copyright contributors to the kepler.gl project-// Globe mode layer adjustments ported from studio-monorepo.+// Globe mode layer adjustments.//-// The following globe-specific adjustments from studio-monorepo are NOT ported-// because they are not applicable or feasible in deck.gl 9.x:-//-// 1. Hex tile highPrecision flag:-// Studio-monorepo forced `highPrecision: true` for H3 hexagons at low resolutions-// in globe mode. Kepler.gl doesn't have hex-tile layers in the same form.-//-// 2. MVT clipBounds disabled in globe mode:-// Studio-monorepo's custom MVT layer skipped clipBounds/ClipExtension in globe mode.-// Deck.gl 9.x's MVTLayer handles globe projection natively without this workaround.-//-// Ported adjustments:+// Globe-specific adjustments handled here:// - Grid / Hexagon aggregation cells on the globe: deck.gl 9.x's GridCellLayer /// HexagonCellLayer position cells in flat mercator common space and draw them with// project_common_position_to_clipspace, which leaves them on the XY plane through the// globe center rather than on its surface. ScaleEnhancedGridLayer /// ScaleEnhancedHexagonLayer swap in a globe-aware cell subclass (see// layer-utils/globe-cell-utils) that remaps each cell vertex from common space back to-// lng/lat and onto the sphere (equivalent to studio-monorepo's UnfoldedGridCellLayer-// globe offset handling, adapted to deck.gl 9.x's aggregation pipeline).+// lng/lat and onto the sphere.// - Text/Label rendering with back-face culling: MVTLabelLayer renders place labels via a// TextLayer whose glyph sublayer is EnhancedMultiIconLayer, which degenerates glyph// vertices on the far side of the globe (dot(surfaceNormal, toCamera) < 0.1) so labels-// don't show through the planet. Implemented as a GLSL inject rather than the deck.gl-// 8.x per-vertex hook studio relied on.+// don't show through the planet. Implemented as a GLSL inject.export {AtmosphereLayerRealistic,diff --git a/src/deckgl-layers/src/globe/mvt-label-layer.ts b/src/deckgl-layers/src/globe/mvt-label-layer.tsindex ca8417e12..563c113ae 100644--- a/src/deckgl-layers/src/globe/mvt-label-layer.ts+++ b/src/deckgl-layers/src/globe/mvt-label-layer.ts@@ -9,7 +9,7 @@ import type {Feature} from 'geojson';import EnhancedMultiIconLayer from './enhanced-multi-icon-layer';-// Ported from studio-monorepo (modules/studio/src/components/globe/mvt-label-layer.ts).+// Custom globe basemap label layer.//// This composite is used as the `renderSubLayers` of the globe basemap MVTLayer.// It renders two things per tile:@@ -18,7 +18,7 @@ import EnhancedMultiIconLayer from './enhanced-multi-icon-layer';//// The TextLayer uses a custom `EnhancedMultiIconLayer` as its glyph (characters)// sublayer, which culls labels on the far side of the globe so they aren't drawn-// through the planet (ported from studio-monorepo).+// through the planet.type MVTLabelLayerProps = {data: {features: Feature[]} | Feature[];diff --git a/src/layers/src/raster-tile/raster-tile-layer.ts b/src/layers/src/raster-tile/raster-tile-layer.tsindex 4dbe5187e..db410c5a1 100644--- a/src/layers/src/raster-tile/raster-tile-layer.ts+++ b/src/layers/src/raster-tile/raster-tile-layer.ts@@ -403,7 +403,7 @@ export default class RasterTileLayer extends KeplerLayer {/*** Update zRange of viewport. This is necessary so that tiles in extruded mode are shown properly- * at high elevations: https://github.com/foursquare/studio-monorepo/pull/1892/files+ * at high elevations.* Derived from https://github.com/visgl/deck.gl/blob/8d824a4b836fee3bfebe6fc962e0f03d8c1dbd0d/modules/geo-layers/src/terrain-layer/terrain-layer.js#L173-L196** @param tiles Array of tiles in current viewportdiff --git a/src/schemas/src/map-state-schema.ts b/src/schemas/src/map-state-schema.tsindex f9e9c4818..a53a2bbda 100644--- a/src/schemas/src/map-state-schema.ts+++ b/src/schemas/src/map-state-schema.ts@@ -24,8 +24,7 @@ export const propertiesV1 = {mapSplitMode: null,swipeComparePercentage: null,// Persist the current view mode (2D / 3D / Globe) and the full globe config- // (colors, toggles, background) so globe maps round-trip through save/load,- // matching studio-monorepo's persisted map state.+ // (colors, toggles, background) so globe maps round-trip through save/load.mapViewMode: null,globe: null};diff --git a/test/browser/components/side-panel/side-panel-test.js b/test/browser/components/side-panel/side-panel-test.jsindex dfdeb8bb6..743ecd560 100644--- a/test/browser/components/side-panel/side-panel-test.js+++ b/test/browser/components/side-panel/side-panel-test.js@@ -381,32 +381,32 @@ test('Components -> SidePanel -> PanelHeader -> ExportDropDown', t => {wrapper.find(ToolbarItem).at(0).find('.toolbar-item').simulate('click');t.ok(toggleModal.calledWith(EXPORT_IMAGE_ID), 'Should call toggleModal with EXPORT_IMAGE_ID');- // export data+ // export videot.equal(wrapper.find(ToolbarItem).at(1).find('.toolbar-item__title').text(),- 'Export Data',- 'Should render Export Data'+ 'Export Video',+ 'Should render Export Video');wrapper.find(ToolbarItem).at(1).find('.toolbar-item').simulate('click');- t.ok(toggleModal.calledWith(EXPORT_DATA_ID), 'Should call toggleModal with EXPORT_DATA_ID');+ t.ok(toggleModal.calledWith(EXPORT_VIDEO_ID), 'Should call toggleModal with EXPORT_VIDEO_ID');- // export map+ // export datat.equal(wrapper.find(ToolbarItem).at(2).find('.toolbar-item__title').text(),- 'Export Map',- 'Should render Export Map'+ 'Export Data',+ 'Should render Export Data');wrapper.find(ToolbarItem).at(2).find('.toolbar-item').simulate('click');- t.ok(toggleModal.calledWith(EXPORT_MAP_ID), 'Should call toggleModal with EXPORT_MAP_ID');+ t.ok(toggleModal.calledWith(EXPORT_DATA_ID), 'Should call toggleModal with EXPORT_DATA_ID');- // export video+ // export mapt.equal(wrapper.find(ToolbarItem).at(3).find('.toolbar-item__title').text(),- 'Export Video',- 'Should render Export Video'+ 'Export Map',+ 'Should render Export Map');wrapper.find(ToolbarItem).at(3).find('.toolbar-item').simulate('click');- t.ok(toggleModal.calledWith(EXPORT_VIDEO_ID), 'Should call toggleModal with EXPORT_VIDEO_ID');+ t.ok(toggleModal.calledWith(EXPORT_MAP_ID), 'Should call toggleModal with EXPORT_MAP_ID');t.end();});diff --git a/test/node/utils/annotation-utils-test.js b/test/node/utils/annotation-utils-test.jsindex 8dabedc74..28620747e 100644--- a/test/node/utils/annotation-utils-test.js+++ b/test/node/utils/annotation-utils-test.js@@ -3,7 +3,14 @@import test from 'tape';import {AnnotationKind} from '@kepler.gl/constants';-import {makeMarker, movePoint, moveText, resizeCircle, isLeftOriented} from '@kepler.gl/components';+import {+ makeMarker,+ movePoint,+ moveText,+ resizeCircle,+ isLeftOriented,+ isPointVisibleOnGlobe+} from '@kepler.gl/components';const mockViewport = {project: ([lng, lat]) => [lng * 10 + 500, lat * -10 + 300],@@ -203,3 +210,60 @@ test('#resizeCircle -> radius cannot go below 0', t => {t.end();});++test('#isPointVisibleOnGlobe -> front-facing point round-trips to itself', t => {+ // A GlobeViewport-like mock where project/unproject are inverses: any point+ // resolves back to itself, i.e. it is on the near (visible) hemisphere.+ const identityViewport = {+ project: ([lng, lat]) => [lng, lat],+ unproject: ([x, y]) => [x, y]+ };++ t.equal(isPointVisibleOnGlobe([0, 0], identityViewport), true, 'center point is visible');+ t.equal(isPointVisibleOnGlobe([30, -45], identityViewport), true, 'off-center point is visible');++ t.end();+});++test('#isPointVisibleOnGlobe -> occluded point resolves to a different surface point', t => {+ // Mock the far-side occlusion: unproject always returns the front-most point+ // ([0, 0]) regardless of pixel, as deck's GlobeViewport does for a ray that+ // hits the near hemisphere first.+ const occludingViewport = {+ project: ([lng, lat]) => [lng, lat],+ unproject: () => [0, 0]+ };++ t.equal(isPointVisibleOnGlobe([0, 0], occludingViewport), true, 'front point stays visible');+ t.equal(+ isPointVisibleOnGlobe([120, 0], occludingViewport),+ false,+ 'point far from the resolved surface point is occluded'+ );++ t.end();+});++test('#isPointVisibleOnGlobe -> non-finite projection is treated as not visible', t => {+ const nanProjectViewport = {+ project: () => [NaN, NaN],+ unproject: ([x, y]) => [x, y]+ };+ const nanUnprojectViewport = {+ project: ([lng, lat]) => [lng, lat],+ unproject: () => [NaN, NaN]+ };++ t.equal(+ isPointVisibleOnGlobe([10, 10], nanProjectViewport),+ false,+ 'non-finite project result is not visible'+ );+ t.equal(+ isPointVisibleOnGlobe([10, 10], nanUnprojectViewport),+ false,+ 'non-finite unproject result is not visible'+ );++ t.end();+});