Skip to content

feat(core): apply local meter scales in custom projections - #10745

Merged
Pessimistress merged 7 commits into
masterfrom
codex/alt-proj-size-scale-texture
Oct 10, 2026
Merged

Pessimistress merged 7 commits into
masterfrom
codex/alt-proj-size-scale-texture

Conversation

@Pessimistress

@Pessimistress Pessimistress commented Sep 24, 2026 •

Copy link
Copy Markdown
Collaborator

For #10739 (PR 6 of 6)

Account for local projection distortion when rendering meter-sized objects and altitude.

Screenshot 2026-09-23 at 10 32 04 PM Screenshot 2026-09-23 at 10 32 23 PM Screenshot 2026-09-23 at 10 32 51 PM

Changed list

  • Estimate local area-equivalent scale across each projection.
  • Add WebGL texture and WebGPU storage-buffer scale sampling.
  • Isolate external-projection shader paths from existing views.
  • Apply local altitude scaling while preserving common-space aggregation sizes.
  • Test scale validity, approximation error, and discontinuities.
  • Update meter-size documentation, test-app sizing, and render coverage.

Method

Generation

Generate a 64×64 scale grid over the projection’s normalized extent. At each valid sample, inverse-project its position and estimate the local projection derivatives using one-meter displacements in world coordinates.

Use the square root of the absolute Jacobian determinant to obtain an area-equivalent scalar scale. Applying the same scale in both horizontal directions preserves the aspect ratio of anchored objects rather than reproducing directional distortion.

Compute scale slopes from neighboring samples, then extend valid values and slopes one cell into unsampled regions to cover valid positions near curved projection boundaries. Reuse the generated resource across camera changes; regenerate when its projection configuration changes.

Encoding

Each grid cell stores four floats:

[scale, dScale/dX, dScale/dY, altitudeScale]

A zero scale marks an invalid sample. WebGL stores float bit patterns in an integer texture; WebGPU uses a vec4<f32> storage buffer with direct address lookup.

Interpolation

Fetch the nearest cell and reconstruct the local scale using its slopes:

scale(position) = scale(cellCenter)
                + dScale/dX × offsetX
                + dScale/dY × offsetY

Altitude scale receives the same relative adjustment. This requires one record lookup without bilinear filtering. Four-cell blending and higher-order interpolation remain documented alternatives if greater continuity or precision is needed.

Measured approximation error

Current harness results, in percent. “Center” covers a 128×128 common-unit square; “whole” covers valid positions within the 512×512 extent. Discontinuity measures the scale jump across nearest-cell boundaries, relative to the reference scale.

Projection Max error, center Max error, whole Max discontinuity, center Max discontinuity, whole
Web Mercator 0.128704% 0.132717% 0.015536% 0.023561%
Equal Earth 0.000897% 0.007637% 0.000159% 0.006859%
Stereographic 0.680093% 0.680093% 0.000007% 0.184600%
Albers conic 0.000098% 0.002310% 0.000042% 0.002301%

Test domains: Web Mercator through ±85.0511° latitude; Equal Earth worldwide; north-polar stereographic from 60°S to 90°N; Albers over [-135, 30, -45, 75].

All sampled valid positions retrieved valid scale values. Tests enforce error and discontinuity below 1%. These are sampled maxima for these configurations, not universal bounds. Equal Earth’s exact poles are excluded from relative-error calculations because the numerical reference is singular there, but sample validity is still checked.


Note

Medium Risk
Changes core projection shaders and per-view GPU resources for the experimental custom-projection path; ordinary MapView rendering stays on the existing code path via shader defines.

Overview
Custom projection views now size meter-based layer geometry (radius, width, elevation) using a location-dependent scale field instead of a single viewport-center correction. A new toBounds option defines the map-meter extent used to build that field without changing position normalization.

The viewport precomputes a 64×64 grid of area-equivalent scales (shape-preserving, not directionally stretched), with slopes and neighbor bleeding for curved boundaries. ProjectionScaleResources caches a WebGL rgba32uint texture or WebGPU storage buffer per view, regenerated when CRS/bounds signatures change and released when views are removed.

The project shader module gains an opt-in USE_EXTERNAL_PROJECTION path (enabled for custom geospatial viewports) that samples the field via nearest-texel Taylor reconstruction. Aggregation layers (including heatmap weight passes) pass the scale resource through draw; max-weight reduction explicitly disables external projection.

Default geographic distortion estimation switches from a simple spherical model to WGS84 ellipsoidal ground distances. Documentation, the custom-projection test app (toBounds on stereographic), render golden tests, and extensive unit/error harnesses cover the new behavior and fallbacks (viewport-center scale outside toBounds or invalid samples).

Reviewed by Cursor Bugbot for commit cfcde0f. Bugbot is set up for automated code reviews on this repo. Configure here.

@greptile-apps

greptile-apps Bot commented Sep 24, 2026 •

Copy link
Copy Markdown

RetriggerConfidence Score: 5/5

[High impact] No outstanding finding identified in this review prevents merging.

Summary

This PR adds location-dependent meter sizing for custom projections while retaining the fixed scale used for positions and altitude. It includes:

  • A sampled scale field with WebGL and WebGPU bindings.
  • View-scoped GPU resource cleanup and aggregation-layer integration.
  • Projection-scale tests, render coverage, and API documentation.

Diagram

%%{init: {'theme': 'neutral'}}%%
flowchart LR
  V[Custom projection viewport] --> G[Generate local scale field]
  G --> R[View-scoped GPU resource]
  R --> S[Projection shader sampling]
  S --> L[Meter-sized layer geometry]
Loading

Reviews (10) · Last reviewed commit: "address comments" · Reviewed by Greptile

@Pessimistress
Pessimistress force-pushed the codex/alt-proj-size-scale-texture branch from 8039c42 to 1a80405 Compare September 24, 2026 05:39
@coveralls

coveralls commented Sep 24, 2026 •

Copy link
Copy Markdown

Coverage Status

coverage: 83.503% (+0.08%) from 83.419% — codex/alt-proj-size-scale-texture into master

@Pessimistress
Pessimistress force-pushed the codex/alt-proj-size-scale-texture branch from 1a80405 to be5c334 Compare September 24, 2026 21:44
@Pessimistress
Pessimistress force-pushed the codex/alt-proj-size-scale-texture branch from be5c334 to db51ab8 Compare September 29, 2026 16:59
@athomct

athomct commented Oct 7, 2026

Copy link
Copy Markdown

Tested this stack (head d874f2db3) with proj4 converters, comparing the local meter scales with PROJ's own scale factors (PROJ 9.5.1 get_factors). For projections on the WGS84 ellipsoid, the scales are off by a latitude-dependent amount, up to 0.67%.

Cause: estimateUnitsPerMeter converts its one-meter steps to degrees on a sphere of radius 6378137 (EC / 360 north, EC / 360 * cos(lat) east). That sphere is exactly right for EPSG:3857, which PROJ and proj4js define on +a=6378137 +b=6378137, and the Web Mercator case matches PROJ to ~1e-7. On the WGS84 ellipsoid, though, a degree of latitude spans M * π / 180 meters and a degree of longitude spans N * cos(lat) * π / 180, with M and N the meridional and prime-vertical radii. That covers +datum=WGS84, UTM and most EPSG projected codes.

Measurement. Map meters per ground meter is getDistanceScales(map).unitsPerMeter / NORMALIZATION_SCALE. The X column is compared with PROJ's parallel scale, Y with its meridional scale, and Z with the square root of their product (the areal scale used for sizes).

CRS lng, lat X (east) error Y (north) error Z (size) error
UTM 18N −75, 0 0.000% −0.669% −0.335%
UTM 18N −75, 42 +0.150% −0.221% −0.036%
UTM 18N −75, 75 +0.314% +0.269% +0.291%
UTM 18N −78, 10 +0.010% −0.639% −0.315%
Albers, NAD83 (EPSG:5070) −96, 29.5 +0.081% −0.427% −0.173%
Albers, NAD83 (EPSG:5070) −80, 42 +0.150% −0.221% −0.036%
Web Mercator (EPSG:3857) any 0.000% 0.000% 0.000%

On the UTM central meridian PROJ gives exactly k0 = 0.9996 at every latitude. This stack gives 0.99290 (north, equator) and 1.00274 (east, 75°N). The same estimate fills the 64×64 size-scale texture (getSizeScaleData → localUnitsPerMeter), which project_external_size_scale_at samples, so meter-sized geometry inherits the Z column.

Why the scale-accuracy test passes: projection-scale-error.ts builds its default reference from the same constant (meters = step * 40075016.6855 / 360). For the two WGS84 cases (equal-earth, albers) it compares the estimator with itself, so it cannot see this. The web-mercator case is correct as it stands, and the stereographic case uses an analytic reference on its +R=6371008.8 sphere.

The fix depends on the CRS's figure of the Earth. Checked locally by patching estimateUnitsPerMeter:

  • With the WGS84 radii, UTM and Albers match PROJ to within 1e-7, but EPSG:3857 becomes 0.67% wrong, and the stereographic accuracy test fails.
  • With the +R=6371008.8 sphere, all four scale-accuracy cases pass.

So a single constant cannot be right for all of them. The estimator needs the target CRS's semi-major axis and eccentricity:

/** Ground meters per degree (east, north) on an ellipsoid; e2 = 0 for a sphere. */
function metersPerDegree(latitude: number, a: number, e2: number): [east: number, north: number] {
  const lat = (Math.min(Math.max(latitude, -89.9), 89.9) * Math.PI) / 180;
  const w = 1 - e2 * Math.sin(lat) ** 2;
  const east = (a * Math.cos(lat)) / Math.sqrt(w);
  const north = (a * (1 - e2)) / (w * Math.sqrt(w));
  return [(east * Math.PI) / 180, (north * Math.PI) / 180];
}

A proj4 converter does not expose its ellipsoid. proj4(from, to) returns only forward/inverse, while proj4.Proj(def) has a/es. So core would have to get the figure some other way. Options:

  • parse +R, +a/+b, +ellps and +datum from toCrs, as isSphericalCrs already does for units;
  • accept the figure as an option;
  • leave non-WGS84 figures to getDistanceScale.

EPSG codes need a lookup in any case: EPSG:3857 and EPSG:32618 are both "WGS 84" by name but sit on different figures.

Happy to open a PR against this branch once you pick a direction.

@Pessimistress
Pessimistress force-pushed the codex/alt-proj-size-scale-texture branch from d874f2d to 3fdce2e Compare October 8, 2026 19:39

@cursor cursor Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Cursor Bugbot has reviewed your changes using default effort and found 1 potential issue.

Fix All in Cursor

❌ Bugbot Autofix is OFF. To automatically fix reported issues with cloud agents, have a team admin enable autofix in the Cursor dashboard.

Reviewed by Cursor Bugbot for commit 3fdce2e. Configure here.

@Pessimistress

Copy link
Copy Markdown
Collaborator Author

Thanks @athomct for the investigation. I’ve updated the default estimator to use a hardcoded WGS84 ellipsoid for ground distances, independently of the target projection’s coordinate formulas. Applications using a different Earth model can override this with getDistanceScale.

Also introduced independent reference in the unit test and added the UTM and NAD83 Albers cases you reported.

Base automatically changed from x/alt-proj-test-app to master October 8, 2026 20:37
@Pessimistress
Pessimistress force-pushed the codex/alt-proj-size-scale-texture branch from 299d5e4 to 7ca311c Compare October 8, 2026 21:05

@ibgreen ibgreen left a comment

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Thanks Xiaoji, local meter sizing is a useful completion of this first custom-projection stack. Sampling distortion at each object, using an area-equivalent scalar to preserve marker shape, and keeping position altitude on the fixed map-meter scale give the API a clear coordinate contract. Anchor-aware getDistanceScales() also addresses the earlier camera-dependent aggregation sizing concern.

Approving the overall direction, with four remaining issues recorded inline: distinguishing failed scale measurements from valid samples, preserving positive sizing when Taylor reconstruction fails, handling feet-based source units, and releasing resources for removed views. Please address these as the implementation progresses.

The numerical estimator would fit naturally in math.gl: source-unit conversion, the ground-distance metric, Jacobian and area-equivalent scale calculation, and explicit validity handling. The GPU encoding, shader bindings, and resource lifecycle belong in deck.gl. This could also let the estimator consume math.gl/crs metadata rather than expanding ad hoc CRS string interpretation in core.

Static review at 7ca311c; tests were not run.

1
]
: [1, 1, 1];
const metersPerUnit = [1, 1, 1];

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

[P2] Account for source linear units before estimating ground-meter scale. isGeographicCrs() recognizes +units=ft and +units=us-ft as linear, but this branch assigns one meter to each input unit. For a simple feet-to-map-meters converter, the measured scale is approximately 0.3048 instead of 1, so meter-sized objects render at about 30.48% of the intended size. This source-unit limitation remains from the earlier viewport implementation and now also feeds the local scale field. Please convert recognized source units to meters, or require an explicit getDistanceScale override for units the estimator cannot interpret. math.gl/crs metadata could supply this conversion.

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This requires parsing the CRS string, will address in a follow up PR when we switch to @math.gl/crs.

@Pessimistress
Pessimistress force-pushed the codex/alt-proj-size-scale-texture branch from bde9915 to cfcde0f Compare October 10, 2026 00:27
@Pessimistress
Pessimistress merged commit dcddb6c into master Oct 10, 2026
8 checks passed
@Pessimistress
Pessimistress deleted the codex/alt-proj-size-scale-texture branch October 10, 2026 00:39
@chrisgervang chrisgervang mentioned this pull request Oct 22, 2026
53 of 66 tasks
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

4 participants