Conversation
…hange) render() is now a thin Cpu-arm wrapper over render_with_backend(map, view, full_res, Backend). The Gpu arm currently wraps the CPU pixmap as a single DrawCmd::Image — a correct scene from day one; Task 3 moves eligible vector layers out of the image into lyon-tessellated meshes. GpuScene/MeshVertex/PointInstance are the ui-egui wgpu contract: origin-relative f32 positions (f64 subtraction on the CPU), premultiplied colors, stroke normals + per-vertex stroke_px so stroke width stays screen-constant at any zoom. Golden pixmap hash test locks the CPU path (0x8caa20979bae31b7, 800x500 world sample).
…ules mesh.rs: EvenOdd polygon fills with holes, round-join/cap strokes at unit width (the GPU vertex shader applies per-vertex stroke_px along lyon's unit normal, so width stays screen-constant at any zoom), the CPU path's 0.35 physical-px decimation, and marker instances (5 shapes; halo as a larger leading instance). Tests cover EvenOdd holes, the decimation rule incl. the last-point exception, centerline/normal recovery, the 0.5 px line floor (and its absence on polygon rings), halo sizing, and alpha premultiplication. mesh fns are cfg_attr(not(test)) allow(dead_code) until the next commit wires them into render_with_backend's Gpu arm.
The single render loop now branches per layer. GPU-eligible vector layers (flat map, full opacity, no mask/blend/aggregation/extrusion/graphics) tessellate into ordered Mesh/Points commands; everything else — basemap backdrop, web tiles, rasters, offscreen-composited layers, label icons — keeps drawing with tiny-skia into the CPU accumulator pixmap, flushed as ordered DrawCmd::Image whenever a GPU command follows (exact painter's-algorithm interleave). Selection highlights tessellate right after their layer. Globe, view effects and color-vision frames downgrade the whole render to the CPU backend automatically. Per-layer origin = drawn features' extent centre (stable across pans; f32-safe offsets). Labels/attribution/pending channels are computed by the same code for both backends and a test pins their equality. New scene-content tests cover mesh/points presence for the world sample, blend-layer image interleave (mesh–image–mesh), selection highlight ordering, and the globe/effects fallback arms.
mapgpu.rs opens with the pure math the wgpu pass needs: view_proj (origin-relative f32 vertices; the f64 origin-minus-center subtraction happens on the CPU) and marker_displace (the marker shader's unit-template-to-clip pixel offset, y flipped for screen-space templates). Golden-tested against Camera::to_screen at world zoom, city zoom and custom (UTM-metre) units to 1/100 px. Plan correction: the v2 plan's view_proj carried a wrong sign/offset term; the matches_to_screen golden test exists precisely to catch that, and the corrected form is what lands here.
mapgpu.rs plays a render::gpu_scene::GpuScene inside egui's own wgpu render pass (egui_wgpu::CallbackTrait::paint — the SpatialOS VectorCallback pattern): polygon/line mesh pipeline (per-vertex stroke_px along lyon normals keeps stroke width screen-constant), instanced marker pipeline (5 unit-space shape templates in a shared uniform bank; CPU outline = a larger under-fill instance, selection halo = the largest, first), and an image pipeline compositing CPU-rasterized runs (linear Rgba8Unorm, matching egui's textures). Hosts hand over frame.wgpu_render_state() (desktop + web); mapview renders via render_backend(Backend::Gpu) when the frame is flat and effect-free, else the CPU path untouched. Camera-only pans/zooms on all-GPU scenes rewrite per-draw uniforms instead of re-tessellating (SceneBuffers::set_camera; scenes with CPU image runs re-render fully). Verified: cargo xtask ci green; headless ui_shot A/B (900x550 @2x, World Atlas) — mean abs diff 0.42/255, 0.77% pixels >16, differences confined to edge/label AA (1x MSAA vs tiny-skia analytic); render_ms 38 -> 14 on this machine. ui_shot now shares one headless RenderState between app and harness so the GPU path is exercised in tests.
Quality: the scene now renders into an offscreen 4x MSAA target in CallbackTrait::prepare (persistent across frames, recreated on resize) and paints as a resolved-texture blit into egui's 1x pass — thin line work anti-aliased, matching tiny-skia's look. Marker parity fix: the CPU strokes marker outlines centred on the shape edge, so the GPU fill instance shrinks by w/2 under the stroke's r+w/2 disk. Parity harness (mapgpu tests, adapter-gated): gpu_render_offscreen renders a GpuScene through the production MSAA path and diffs against render() — raw mean < 1.5/255 plus a structural-outlier rule (a >16 mismatch in a CPU-flat 3x3 neighbourhood fails; analytic-AA vs MSAA edge quantization is excluded by design). Cases: world sample (light+dark), polygon with hole, all five marker shapes, lines + selection, transparent-layer image interleave. PARITY_DUMP=/dir writes cpu/gpu/diff PNGs for debugging. PARITY dump alpha fixed to opaque.
The GPU backend gets a real command: View tab > Display > GPU Rendering (checked state, tooltip documenting the CPU fallback for globe/effects/color-vision), persisted via Services prefs (key ui.map.gpu); RUSTGIS_GPU still force-enables. MapView::invalidate() drops the GPU frame too, so the flip re-renders on the next frame. Strings seeded (English) into all 15 i18n catalogs. Test: gpu_toggle.rs flips twice, checks the pref writes. Verified in ui_shot: toggle on → map on GPU, render_ms 39 -> 9 on the World Atlas.
split_view gains the same two-arm path as the main view (its own MSAA target slot — the two views differ in size). The camera fast path also covers keyframe animations (app.ws.playing), so animated camera moves re-project in the shader instead of re-tessellating per frame; the labels' hide-while-zooming / shift-while-panning behaviour is unchanged (tex_camera intentionally lags on the fast path). Verified in ui_shot: map.new + ui.splitView with RUSTGIS_GPU=1 renders both panes on the GPU, 10 -> 3 ms.
User guide (maps.md): the View > Display > GPU Rendering beta toggle, its persistence, RUSTGIS_GPU, and the CPU fallback matrix. WebGL2-limit audit: the scene pipelines use only vertex/uniform buffers (no storage buffers, no compute; the 5760-byte marker template bank is well under the 16 KB WebGL2 uniform minimum), MSAA x4 render targets are WebGL2-legal, and textures stay within 4096 px. cargo build --target wasm32-unknown-unknown -p rustgis-web is green. The parity suite now also runs the world sample on wgpu's GL backend (the web app's forced path). A real-browser pass on a display-capable machine remains the one manual check.
The status bar's right end gains a CPU/GPU chip (running the existing ui.map.gpu command, so the toggle persists and invalidates the same way as the ribbon button) and a frames-per-second readout next to the render_ms one: MapView keeps a rolling 2 s window of map-frame times; fps() is Some(frames in the last second) while the map moves and None when idle (egui repaints on demand, so no frames = idle, distinct from 0 fps when moving). Unit-tested; both new strings seeded into all 15 i18n catalogs. Verified in ui_shot: clicking the chip flips CPU -> GPU live (36 ms -> 9 ms on the World Atlas).
…, command polish
Review fixes for the GPU backend, in one commit because they interlock:
- The basemap water travels as the scene's clear colour (the MSAA pass's LoadOp::Clear)
instead of an always-present full-view Image command, so pure-vector scenes carry no
image and the camera fast path can engage at all.
- Tessellation results are Results: a lyon failure falls the whole layer, its highlight and
the basemap/graticule back to the CPU pixmap instead of dropping features. Non-finite
coordinates are dropped before lyon (its path builder panics on NaN).
- The magnifier hides while GPU frames draw: it samples the CPU texture, which GPU frames
don't update.
- ui.map.gpu takes {"on": bool} like ui.theme takes {"dark"} and joins the command search;
Rendered2 is renamed RenderOutput; xtask's UI_ONLY gains wgpu and egui-wgpu; pollster is
workspace-pinned.
The fast path marked the frame fresh (key = current), so when a pan/zoom or camera animation ended nothing re-rendered: extent culling, the 0.35 px decimation and label placement stayed baked for the pre-gesture camera (empty areas, coarse outlines, hidden labels until an unrelated change). The fast path now leaves key/tex_camera at the last full render and only skips that frame's full render; the settle frame's stale key triggers one. Regression test drives a camera animation in a wgpu harness and asserts full_frame_camera() refreshes.
gpu_layer is the layer's eligibility; gpu_done is what happened. A layer whose tessellation failed draws into the CPU accumulator (flushed as an Image later); its highlight must follow it there — tessellated into cmds as before, the layer's image would cover the highlight. Unreachable from public input today (lyon accepts NaN widths and self-intersections); fixed as an invariant because the resource-limit guards make collect_layer's Err reachable.
ring_path breaks a ring where the projection can't show a point (bounded-area projections like the polar presets return NaN there); decimate dropped such points but joined their neighbours, drawing fill triangles and line segments across areas the CPU leaves empty. decimate_runs yields one run per maximal finite segment; path_of/stroke open a subpath per run. Regression tests: decimate_runs break semantics at unit level, and a northPolar world-sample parity case (1206 structural outliers before, zero after).
…ex overflow guard SceneBuffers::from_scene checks every vertex/index/instance buffer against the device's max_buffer_size and every image against max_texture_dimension_2d (256 MiB/8192 defaults, lower on WebGL2-class adapters) and returns None; both map views treat None as GPU-declined and render the frame with the existing CPU path. extend_mesh refuses meshes that would overflow their u32 indices (the layer falls back the same way). Strokes with non-finite widths are skipped rather than uploading NaN vertices. Tests: fits_limits at synthetic limits, NaN stroke-width scene has only finite mesh data.
…, mesh helpers, from_scene) Closes the bot's docstring-coverage gap on functions the diff adds; test fns and trait-impl overrides stay undocumented per the repo's existing convention.
…lean fallbacks Second round of review findings, each validated before fixing: - Strokes were tessellated at lyon's default tolerance 0.1 — ~5 segments per full circle at our radius 0.5, scaled to any width by the shader, reading as polygonal next to tiny-skia's analytic curves. Tolerance 0.005 (~31 segments/circle) with a subdivision test. - flush_acc copied a full-screen pixmap per flush; DrawCmd::Image now moves the Pixmap (zero copies), and frames alternating CPU-only and GPU layers past four image commands fall back to a plain CPU render (cheaper than the uploads). As a side effect, 0x0 and size-mismatched images became unconstructible — the type does the work now. - Hidden tile layers no longer mark the frame dirty: no spurious empty Image, and the camera fast path keeps engaging on maps with hidden tiles. - mesh.rs's Result<_, ()> is now a named TessError (result_unit_err nit); the golden-hash comment records its purpose and CI's cross-platform arbiter role. Not fixed, with evidence: float_next_after duplicates (lyon pins 1.0.0, geo 2.0.0 — semver-disjoint); ATTRIBUTION.md (first-party WGSL needs no row); the golden FNV hash (kept — it is the refactor byte-lock and tiny-skia is deterministic f32).
…nt meshes Investigated a report of buildings vanishing at zoomed-out views on the GPU backend: - Root cause: a ring decimated below 3 points at the view's zoom vanished entirely (fill and stroke both required 3). The CPU strokes such a 2-point remnant as a visible dash. Ring strokes now accept 2 points and stroke them open — the same pixels as the CPU's closed back-and-forth. Regression test: 100 sub-pixel buildings contribute triangles to the GPU scene again. - The layer loop now hands collect_layer the thinned geometry () — the same vertices the CPU draws (#320's LOD copies) instead of the full projected cache: identical output, much less tessellation at zoom-out. Selection highlights keep the full geometry, as the CPU's do. - Meshes chunk at 4M vertices (160 MB — under the 256 MiB default max_buffer_size), so giant layers (a whole country's buildings) fit the device instead of being declined to the CPU path. Chunk order preserves painter's order. Verified: sub-pixel regression test, chunk test (test-scaled cap), full parity suite green, xtask ci + pre-commit green, ui_shot A/B unchanged (mean 0.175/255).
Baseline (2026-10-18, release build, Intel Core Ultra 9 285K, rustc 1.99.0), 1M-building world zoom at 1280x800, 10-frame mean after warm-up: - Cpu: 78.5 ms/frame - Gpu: 365.2 ms/frame, 8,742,612 triangles
thin_run is now VW: repeat removal of the smallest-effective-area vertex above an area threshold (area_tol = tol^2), with ends and non-finite vertices pinned, a 4-vertex floor for rings and 2 for lines, and a removed-flags + filter-in-order rebuild. The spec's linked-list heap sketch collapsed closed rings, re-removed duplicate heap entries and dropped NaN vertices (review doc §1.3); the verified removed-flags variant with the !is_finite break guard is used instead. Public API unchanged: thin, THIN_PX, THIN_ABOVE, MIN_SAVING, LEVELS_KEPT, level, tolerance, thinnable, vertices. Tests: budget-parity (VW keeps a sharp corner the greedy rule drops at the same kept count, review §1.4), exact-closure ring (first == last by value, keeps >= 4 and stays closed), plus the spec's ends/NaN-pin, ring-floor and monotonicity tests. The two greedy-era lod tests are re-pinned to VW's contract (collinear runs thin to their ends; a NaN vertex now also keeps both neighbours, review §1.3), and a_small_ring_stays_whole expects the 4-vertex floor per the spec. map/src/lib.rs (test-only): the long_line fixture gains a gentle wiggle — a perfectly straight line thins to its ends at every tolerance under VW (zero-area vertices), which broke the two thinned_in caching tests; the wiggle keeps every assertion unchanged (verified: ~5% saving at tol 1.0 and 2^-10, uncached -> full draw; 601 of 201,000 vertices at tol 8192, cached, < full/40). Golden hash: unchanged — the sample world totals ~12.5k vertices, far below THIN_ABOVE = 200,000, so thinning never engages on it and 0x8caa_2097_9bae_31b7 still holds; crates/render/src/lib.rs is untouched. CPU<->GPU parity suite green (both backends draw from drawn). lod_bench (1M-building world zoom, release, same machine as the baseline): CPU: 78.5 -> 77.8 ms/frame GPU: 365.2 -> 369.9 ms/frame GPU triangles: 8,742,612 -> 8,742,612 (unchanged) No area_tol recalibration: no level changed MIN_SAVING cache-worthiness on the harness (4-vertex rings hit VW's floor exactly like greedy's <4 clone), so area_tol stays tol^2 per the spec.
A feature whose screen footprint is under COLLAPSE_PX (1 px) in both axes now draws as one filled dot at its extent centre instead of walking and tessellating its rings: Ctx::dot on the CPU path, a circle PointInstance on the GPU path. Both backends decide through the same collapsed_dot(e, map_per_px); points, graphics rows, and the globe keep full geometry, as do highlights, labels, aggregation and extrusion (they read geoms). The existing subpixel_polygons_still_draw_on_gpu asserted dash triangles; those buildings now collapse, so it asserts dots instead. The new subpixel_features_collapse_to_dots_on_both_backends uses a Blank basemap and no graticule so the scene is the buildings layer's commands alone (the default Paper backdrop and graticule are meshes of their own). Bench (lod_bench, release, back-to-back with HEAD): CPU: 75.3 -> 146.2 ms/frame (recorded Task 0 baseline: 78.5) GPU: 353.4 -> 27.3 ms/frame (recorded Task 0 baseline: 365.2) GPU triangles: 8,742,612 -> 70,612 (1M buildings are dots, not meshes) The GPU drop is the task's point. The CPU rise is the trade's other side on this fixture: a 4-vertex ring costs almost nothing to walk and its degenerate sliver fill + dash stroke was nearly free, while a real 1 px circle rasterizes flattened cubics per feature. High-vertex sub-pixel rings (the spec's 60M-vertex motivation) invert it. Golden pixmap hash: unchanged at 0x8caa_2097_9bae_31b7 — no sample-world feature collapses at world zoom; world_atlas_pixmap_is_byte_stable passes unmodified.
Layers over CULL_INDEX_ABOVE (100_000) features answer the per-frame "what can intersect this view" extent scan with a binary search over a min_x-sorted row index cached on Layer next to projected_extents (built lazily by cull_index_in, dropped on reprojection) plus a scan of the matching prefix, instead of testing every feature on every frame (twice per GPU layer in collect_layer). Candidates are sorted back to ascending row order, painter's order being row order; the per-row rows/visible checks stay in both the CPU draw loop and both collect_layer passes, so culling is pixel-invisible (golden hash 0x8caa_2097_9bae_31b7 unchanged, GPU triangle counts identical). Small layers and the globe path keep the linear scan (candidates: None). lod_bench (1M-building fixture, 1280x800, release), before -> after: world Cpu: 146.3 -> 146.1 ms/frame (whole prefix visible: no win, as designed) world Gpu: 25.8 -> 20.3 ms/frame (70,612 tris, unchanged) zoomed Cpu: 9.7 -> 8.7 ms/frame (~1-degree window mid-grid) zoomed Gpu: 24.6 -> 8.9 ms/frame (120,892 tris, unchanged)
Add render_backend_lod(map, view, backend, lod_bias): the bias multiplies the thinning tolerance, so 4.0 renders from the thinned copy two power-of-two LOD levels coarser. Values <= 0 or non-finite clamp to 1.0; render_backend stays a thin wrapper passing 1.0, so the default path is byte-identical (the world_atlas_pixmap_is_byte_stable golden hash is unchanged). The map view passes 4.0 for full re-renders while interacting or playing — the case that matters: GPU scenes containing CPU tile/raster images re-render every mid-gesture frame — and 1.0 otherwise; the settle frame re-renders exact because the camera changed during the gesture, so Key differs (the bias is deliberately not part of Key). No engine change: its crate-level re-export (pub use rustgis_render as render) carries the new function. Caveat: when a gesture ends without one last camera change (hold still, then release), no settle re-render is triggered and the biased frame can persist until the next change — a narrow follow-up, not bundled here. Cache note (plan review 1.5): Layer::thinned_in caches NEGATIVE results too — a (level, None) marker for a level that fails MIN_SAVING occupies an LRU slot like any other. Bias frames and settle frames now compete for the LEVELS_KEPT = 3 slots, and bias frames can evict known-unworthy markers, causing repeat thinning attempts of expensive levels. LEVELS_KEPT stays 3 here; raise it to 4 only if profiling shows thrash (spec Task 4 Step 3). Tests: new lod_bias_thins_during_interaction on a 262,144-vertex sine line (the fixture must clear lod::THIN_ABOVE = 200,000 or the layer never thins, and span the view densely enough that the 0.35 px draw-time decimation does not mask the difference): GPU mesh vertices 70,345 at bias 1.0 vs 67,707 at bias 4.0; NaN/0/negative biases clamp to the exact path. cargo test -p rustgis-render: 46 passed (golden hash unchanged). cargo test -p rustgis-ui-egui: 72 passed. cargo xtask ci: ok.
crates/render/tests/lod_data.rs: the real-data suite of docs/plans/2026-10-17-rustgis-lod-testdata.md §4/§5/§7 against the corpus in $RUSTGIS_LOD_DATA (Tasks 0-4: VW thinning, sub-pixel collapse, cull index, interaction bias). Env-gated: unset → every test prints `skipped` and passes (verified: 10 passed, 1 ignored, 0.00s). With the corpus (debug, 172s): 10 passed, 1 ignored. - X3.1 every loadable dataset × world/region/city × CPU/GPU completes, incl. dem-alps/worldcover rasters alone and dem-alps+ne-rivers overlay; osm-netherlands (1.4 GB > io::MAX_BYTES) skips by design. - X2.1 every dataset renders byte-identical twice (fnv1a of the pixmap). - X1.1 both backends complete; GPU scene non-empty when CPU drew; monaco at world: 2 199 GPU dots, CPU draws them too. - T1 ne-admin0 thinned cache 111 788 (world) → 548 471 (region) → 548 471 (city) vertices; ne-rivers 44 696 → 257 645 → 257 645; min ring size 4 everywhere. NOTE: the plan's "world > region > city" direction is inverted for the whole-layer tolerance-keyed cache (world carries the coarsest tolerance → fewest vertices); the test pins the actual invariant, non-increasing in tolerance (lod.rs's vw_monotone_in_tolerance). - T1.4 ne-admin0 projects fully finite in Web Mercator (latitude clamps at ±85.05°), so polar/antimeridian NaN pinning is not exercised by real data here; the survival assertion holds (0 == 0) and the pinning itself is covered by lod.rs unit tests. - T2 monaco world: 2 199 dots vs 100 triangles (2 large non-building polygons of the multipolygons layer mesh — "meshes small", not zero); monaco city: 14 dots, not 0 — measured: 14 genuine 2-4 m OSM features (sheds/kiosks, 5-20 vertices) are still sub-pixel at res 4 and collapse by design; asserted as a tight bound (<= 20), exact counts logged. ne-lakes world: 336 dots + 209 246 triangles in one layer (threshold crossed naturally). - T3.1 CullIndex == linear intersects scan exactly (set+order) for ne-admin1 (4 596), overture-buildings (1 643 621 sampled of 4 930 863) and osm-amsterdam (1 730 616) × 50 probes (world, hemispheres, empty Pacific, 44 LCG 1° windows). - T4 osm-amsterdam world: 73 422 → 72 891 mesh vertices at bias 4.0; settle byte-exact; biases 0/-1/NaN/+inf render identical to unbiased. - T4.4/X4 dem-alps+ne-rivers: at city-raster (res 4) the MIN_SAVING gate rejects thinning for rivers entirely (95 250 == 95 250, pinned as the gate's no-op by design); at world, bias 4.0 thins with the raster present (311 513 → 172 351) and settle is byte-exact at both presets. Perf (release, 10-frame means after warm-up; scene stats exist for GPU only): dataset preset backend ms/frame triangles mesh_vertices dots osm-amsterdam world Cpu 7213.8 - - - osm-amsterdam world Gpu 225.5 72110 73422 5252846 osm-amsterdam region Cpu 7474.9 - - - osm-amsterdam region Gpu 289.4 1688935 1806931 5221242 osm-amsterdam city Cpu 379.0 - - - osm-amsterdam city Gpu 143.0 2167842 2258984 149237 overture-buildings world Cpu 1417.5 - - - overture-buildings world Gpu 112.3 70612 71808 1643617 overture-buildings region Cpu 10.9 - - - overture-buildings region Gpu 11.1 22731 23027 0 overture-buildings city Cpu 11.1 - - - overture-buildings city Gpu 12.8 92627 93767 0 The CPU dot-cost question, answered on real data: Amsterdam at world draws 5.25M collapsed dots at 7 214 ms/frame on CPU vs 226 ms to build the GPU scene (32x); region is worse still on CPU (7 475 ms — the cull index can't shrink a window that holds the whole metro) while the city window culls to 379 ms. The overture part-0 sample covers the Americas/Antarctica (lon -180..-86), so its region/city rows are the empty-window case: ~11 ms on both backends with 1.6M features indexed (the cull index's win case); its world row meshes 1.64M dots at 112 ms vs 1 418 ms CPU. overture-buildings is used extents-only for correctness (T3.1): the parquet materializes a 1 643 621-feature sample of the 4 930 863 buildings (the provider's even-spread cap), so per-pixel render loops skip it; it does render in the perf table above. Gates: cargo fmt --check clean; cargo clippy -p rustgis-render --tests -D warnings clean; cargo test -p rustgis-render: 46 lib + 10 lod_data (skip) green; cargo xtask ci exit 0.
Task 4's "exact on settle" relied on the camera changing between the last biased
render and settle: the bias was deliberately not part of Key, so a gesture ending
WITHOUT one final camera change (hold still, then release; a scroll-tail stop; a
tween's last frame) left stale=false on settle and the coarser-LOD frame persisted
until the next change — on has_images GPU scenes, which re-render every mid-gesture
frame (the pure-GPU fast path never updates the key mid-gesture and was immune).
Fix follows the globe's proven draft pattern: Key gains lod_draft, recording
whether the last full render was biased (lod_bias != 1.0), set from the same
interacting || playing condition that computes lod_bias and stored only when a
full render actually happens.
cam_only trace: mid-gesture, stored and current keys both have lod_draft=true, so
Key { cam: k.cam, ..key } == k still holds when only the camera moves — the GPU
fast path (uniform rewrite) is untouched; on settle the current key has
lod_draft=false against the stored true, so stale && !cam_only forces exactly one
full re-render at bias 1.0. Behavior is otherwise identical (4.0 while
interacting/playing, 1.0 on settle, CPU fallback likewise; hostile-input clamping
stays in render).
Test: lod_draft_forces_exact_render_on_settle pins the mid-gesture cam_only case
and the settle transition (biased stored key → same-camera settle key ⇒ stale &&
!cam_only). cargo test -p rustgis-ui-egui: 73 passed. cargo xtask ci: ok.
The Task 2 collapse traded per-feature ring walking for a per-dot circle path build + fill_path scan (~0.9 us/dot: 0.24 us of path building plus ~0.64 us of per-call scan/blitter setup — measured with a 1M-dot scratch bench). On the osm-amsterdam corpus (~1.8M collapsed buildings/lines at world zoom) that made the CPU path slower than before the collapse. Same-paint batching (many circle subpaths in one fill) was measured and rejected: 1.93 us/dot, worse — one AA scan over 4M edges costs more than the per-call setup it saves. A dot whose diameter is at most one physical pixel covers a single pixel, so write it directly, replicating tiny-skia's premultiplied src-over byte-for-byte (its lowp pipeline: dst = src + (dst*(255-src_a) + 255) >> 8; an opaque fill strength-reduces to a plain store — verified byte-identical to fill_rect of the same pixel for opaque and translucent paints, overlapping dots included). A dot fully outside the pixmap draws nothing; an edge-straddling dot and larger (HiDPI) dots keep the antialiased circle. The GPU path is unchanged (mesh.rs untouched): the mapgpu structural-parity check (flat-3x3 outliers) records 0 outliers on a dense 45k-collapsed-dot probe, same as circle-vs-circle. Numbers (release; osm-amsterdam cells are 3-frame means of a stripped harness at f00f410 and HEAD — the committed 10-frame table matches HEAD within noise): osm-amsterdam f00f410 (pre-collapse) HEAD 1d353ef this commit world CPU 6619.1 7272.2 5856.1 ms/frame region CPU 6795.1 7549.5 6073.5 city CPU 378.1 386.9 385.6 world GPU 2121.9 225.8 229.6 (scene build) lod_bench (1M buildings, world): CPU 152.2 -> 19.6 ms/frame (7.8x); GPU 20.7 unchanged; GPU triangles 70612 identical. The remaining Amsterdam world CPU cost is the points layer's 1.73M markers (points never collapse, by design), not the collapsed dots. Gates: golden pixmap hash 0x8caa_2097_9bae_31b7 unchanged (no sample-world feature collapses); corpus X2.1 byte-stability and all lod_data correctness tests green on the real corpus; cargo test -p rustgis-render (47 unit tests, incl. a new fast-path byte-exactness pin) and -p rustgis-ui-egui green — the mapgpu parity tests rendered on the real adapter (/dev/dri/renderD128, PARITY_DUMP artifacts produced); cargo xtask ci exit 0.
…GIS_LOG stderr logger) RUSTGIS_FPS=1 logs one stderr line per map frame outcome: fast-path uniform rewrite, full render (backend, ms, bias, size, res, has_images), or a stale frame served by the shifted texture. RUSTGIS_LOG=1 installs a stderr logger so wgpu/eframe log records stop being silent. Both off by default; used to diagnose the resize-storm window close and the multi-second CPU settles on multi-million-feature layers.
|
Important Draft PR not reviewedDraft PRs are not automatically reviewed by default.
To automatically review draft PRs, update your CodeRabbit configuration: reviews:
auto_review:
drafts: true
Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out. Comment |
Code reviewThis PR adds a GPU map backend (lyon tessellation plus a wgpu pass in Bugs
Performance
Quality
Security
AGENTS.md
Change sizeCompared: the whole PR against main (merge base bc27fe3 to PR head fba2724)
|
…nd hygiene The cull index sorts with total_cmp over get()-looked-up extents — a NaN min_x can no longer make the comparator non-total (sort_by may panic on one since Rust 1.81) or panic on the slice index. This was listed as fixed earlier but had not actually landed. EAGER_PROJECT_UP_TO is a tenth on wasm (50k), where the warm runs on the browser's single main thread several times slower than the native numbers the 500k cap was measured against. The worker's result send blocks instead of dropping when the slot is occupied (the UI polls every frame, so it frees within one), and a caught panic clears the clone's caches before it is returned — an unwind can stop mid-rebuild, and adopt_caches cannot tell a half-built cache from a whole one. Two VW doc comments corrected to match the code (stale entries are skipped, never acted on; the ring floor's fourth vertex is the closing duplicate).
Code reviewThis was a partial review. The diff is about 272 KB across 28 files. I read Bugs
Security
Performance
Quality
AGENTS.md
Change sizeCompared: the whole PR against main (merge base bc27fe3 to PR head 435d84d).
|
total_cmp orders a sign-bit-set NaN before -inf, so a NaN min_x at the front of min_xs would cut partition_point's candidate list to nothing — every feature silently dropped. Non-finite keys (NaN either sign, or an empty extent's +inf) now map to +INFINITY and sort truly last, where intersects rejects the row anyway. Regression-tested with both NaN signs.
Code reviewI read the new Bugs
Security
Performance
Quality
AGENTS.md
Change sizeCompared: the whole PR against main (merge base bc27fe3 to PR head 3fb836d).
|
GPU is now on by default; RUSTGIS_GPU=0 or pref ui.map.gpu=0 disables it. Declined frames (globe, effects, blended layers, oversized scenes) fall back to CPU automatically. Measured 28x faster settle frames (171 ms vs 4860 ms at Amsterdam scale).
For Renderer::Single layers, resolve the symbol once per layer instead of per-feature symbol() calls in the hot loop. drawn_rows and visible_rows now reuse a Mutex-guarded buffer across frames instead of allocating a new Vec<bool> each call. Phase-level profiling bench added (bench_settle_phases).
| split_gpu: None, | ||
| gpu_target_split: std::sync::Arc::new(std::sync::Mutex::new(None)), | ||
| render_state: None, | ||
| gpu_enabled: std::env::var_os("RUSTGIS_GPU").is_some(), |
There was a problem hiding this comment.
Default enables the GPU backend only when RUSTGIS_GPU is set (even RUSTGIS_GPU=0 enables it), which contradicts the field doc ("on by default; RUSTGIS_GPU=0 disables"). lib.rs later overwrites it from prefs/env, so the app path is right, but any MapView::default() use that skips that init (tests, embeds, the web shell if it doesn't hit that code) gets the opposite default. Suggest making Default match: gpu_enabled: !std::env::var_os("RUSTGIS_GPU").is_some_and(|v| v == "0"), or share one helper with lib.rs. Confidence: medium.
| if !gains { | ||
| return; | ||
| } | ||
| self.projected = other.projected.clone(); |
There was a problem hiding this comment.
adopt_caches never compares projected_for (the projection key) between self and other. If the user changes projection while a worker render is in flight, geometry_rev is unchanged, so the clone's old-projection projected/thinned/cull_index can overwrite a layer that has already re-projected, whenever gains is true via thinned or cull_index. is_cached then fails on the key, so the result is correct but the new projection is dropped and recomputed. Add other.projected_for == self.projected_for (or only adopt when self isn't cached) to populated. Confidence: medium-low.
Code reviewI read the new worker, cull index, Bugs
Security
Performance
Quality
AGENTS.md
Change sizeCompared: the whole PR against main (merge base bc27fe3 to PR head 2a4d2db)
Largest changes:
|
… unlikely Before building the full thinned copy, sample up to 1000 features and thin only those. If the sample doesn't meet MIN_SAVING (25% vertex reduction), record the level as not-worth-thinning and return the projected geometry directly. This avoids paying the full VW cost at fine zoom levels where most features are already simple enough that thinning wouldn't save enough vertices. The sample overhead (~1000 × thin_cost) is negligible compared to the full build (e.g. ~1ms vs 1256ms for Amsterdam multipolygons). When thinning IS worthwhile (coarse zoom), behavior is unchanged.
| split_gpu: None, | ||
| gpu_target_split: std::sync::Arc::new(std::sync::Mutex::new(None)), | ||
| render_state: None, | ||
| gpu_enabled: std::env::var_os("RUSTGIS_GPU").is_some(), |
There was a problem hiding this comment.
MapView::default() sets gpu_enabled to true only when RUSTGIS_GPU is set (to any value, including 0), while lib.rs (~519) makes the GPU backend on by default and treats RUSTGIS_GPU=0 as off. The two disagree, and the doc comment on the field says "on by default". docs/user-guide/maps.md says "off by default" and "RUSTGIS_GPU=1 forces it on". Please pick one behaviour and make code and docs match. Anything that builds MapView::default() without going through the prefs loader will see the Default value. Confidence: high.
|
|
||
| **View › Display › GPU Rendering** (beta) draws the flat map on the GPU instead of the CPU: | ||
| vector layers are tessellated once and re-projected per frame, so panning and zooming stay | ||
| smooth on large datasets. It is off by default, and the setting is remembered across sessions |
There was a problem hiding this comment.
The docs say GPU rendering is off by default and RUSTGIS_GPU=1 forces it on, but crates/ui-egui/src/lib.rs enables it by default (RUSTGIS_GPU=0 or pref ui.map.gpu=0 disables it). The PR description also doesn't mention the GPU backend at all, even though it is about half the diff (mesh.rs, mapgpu.rs, the WGSL shader, the status-bar toggle). A default-on beta renderer deserves explicit mention in the description. Confidence: high.
| let sample_size = 1000.min(self.projected.len()); | ||
| let mut sample_all = 0usize; | ||
| let mut sample_kept = 0usize; | ||
| for g in self.projected.iter().take(sample_size).flatten() { |
There was a problem hiding this comment.
The sampling pre-check has two problems. (1) It samples only the first 1000 rows. For spatially sorted data (country-ordered, tiled, or one huge feature) the sample is unrepresentative, and a wrong "not worth it" verdict caches (level, None) for the whole layer at that level, which disables thinning. (2) When the sample says "thin", the first 1000 features are thinned twice, and for a single-feature layer (e.g. the long_line case) the whole VW pass runs twice. Consider a strided sample across the rows, or drop the pre-check and rely on the existing worth test after the full build. Confidence: medium.
| pub fn drawn_rows(&self, scale: f64) -> Vec<bool> { | ||
| let mut rows = self.visible_rows(); | ||
| let n = self.dataset.features.len(); | ||
| let Ok(mut buf) = self.drawn_rows_buf.0.lock() else { return vec![true; n] }; |
There was a problem hiding this comment.
The "reusable buffer" does not avoid allocation. Both drawn_rows and visible_rows end with buf.clone(), which allocates a new Vec<bool> every call. The Mutex also adds locking, keeps an n-byte buffer alive per layer, and blocks concurrent callers (the render worker works on a clone, but &self access is shared). drawn_rows also duplicates the visible_rows logic inline. Simplest fix: revert to building a local Vec<bool> and drop SharedBuf. Confidence: high.
| /// pixmap or a GPU scene (see [`Backend`]); `lod_bias` scales the thinning tolerance (see | ||
| /// [`render_backend_lod`]). | ||
| fn render_with_backend(map: &mut Map, view: &View, full_res_rasters: bool, backend: Backend, lod_bias: f64) -> Option<RenderOutput> { | ||
| let prof = std::env::var_os("RUSTGIS_PROF").is_some(); |
There was a problem hiding this comment.
Nit: RUSTGIS_PROF adds an env lookup per frame and about a dozen if let Some(t0) / eprintln! blocks interleaved through the hot render loop. This is debug instrumentation in a library crate that is not covered by the PR description. Consider using log::debug! with a small timing helper, or removing it before merge. Related: the GPU→CPU fallback at the end (images > 4 → render_with_backend(.., Cpu, ..)) re-runs the entire render, including streamed-layer requests and label_lock assignment, so the work is doubled and the label lock may be set from the discarded pass. Confidence: low–medium.
Code reviewI read the whole diff and checked the surrounding source where it mattered. I did not build the code or run the tests. The map, LOD, render, mesh, worker and Bugs
Security
Performance
Quality
AGENTS.md
Change sizeCompared: the whole PR against main (merge base bc27fe3 to PR head 29e52d7)
|
| let copy: Vec<Option<Geometry>> = { | ||
| #[cfg(not(target_arch = "wasm32"))] | ||
| { | ||
| use rayon::prelude::*; | ||
| self.projected.par_iter().map(|g| g.as_ref().map(|g| lod::thin(g, t))).collect() | ||
| } | ||
| #[cfg(target_arch = "wasm32")] | ||
| { | ||
| self.projected.iter().map(|g| g.as_ref().map(|g| lod::thin(g, t))).collect() | ||
| } | ||
| }; | ||
| // The saving counts against every vertex the copy holds, points included. | ||
| let all: usize = self.projected.iter().flatten().map(lod::vertices).sum(); | ||
| let kept: usize = copy.iter().flatten().map(lod::vertices).sum(); | ||
| let all: usize = { | ||
| #[cfg(not(target_arch = "wasm32"))] | ||
| { | ||
| use rayon::prelude::*; | ||
| self.projected.par_iter().flatten().map(lod::vertices).sum() | ||
| } | ||
| #[cfg(target_arch = "wasm32")] | ||
| { | ||
| self.projected.iter().flatten().map(lod::vertices).sum() | ||
| } | ||
| }; | ||
| let kept: usize = { | ||
| #[cfg(not(target_arch = "wasm32"))] | ||
| { | ||
| use rayon::prelude::*; | ||
| copy.par_iter().flatten().map(lod::vertices).sum() | ||
| } | ||
| #[cfg(target_arch = "wasm32")] | ||
| { | ||
| copy.iter().flatten().map(lod::vertices).sum() | ||
| } | ||
| }; | ||
| let worth = (kept as f64) <= all as f64 * (1.0 - lod::MIN_SAVING); |
There was a problem hiding this comment.
Nit (quality, ~70% confidence): three copies of the same #[cfg(not(wasm32))] / #[cfg(wasm32)] pair is a lot of duplication. The vertex counts (all, kept) are cheap compared with thin, so parallelizing them gains little. Only the thin map needs rayon. Also, all is already computed in the sample pre-check, so only copy needs a full count. A small helper such as fn par_map<T: Sync, U: Send>(v: &[T], f: impl Fn(&T) -> U + Sync + Send) -> Vec<U>, with the cfg inside it, would keep the call site clean. Separately, par_iter runs on rayon's global pool, which on desktop is shared with any other rayon work. A panic in lod::thin is re-raised on the calling thread, so the Session::run catch still covers it.
Code reviewThis PR is large: 29 files, including a GPU fast path ( Bugs
Security
Performance
Quality
AGENTS.md
Change sizeCompared: the whole PR against main (merge base bc27fe3 to PR head f801d30).
|
Replace the sequential .iter().map(lod::thin) in Layer::thinned_in() with rayon par_iter() gated behind cfg(not(target_arch = "wasm32")). Also parallelize the vertex counting (all/kept sums). Order is preserved by rayon's par_iter. wasm32 builds keep the original sequential path. Profiling showed VW thinning at 1278 ms for Amsterdam multipolygons (1.39M features, ~20M vertices); this was the dominant cost in both CPU and GPU settle frames. The thinning is embarrassingly parallel.
f801d30 to
35c89ce
Compare
| sample_all += lod::vertices(g); | ||
| sample_kept += lod::vertices(&lod::thin(g, t)); | ||
| } | ||
| let should_thin = sample_all == 0 || (sample_kept as f64) <= sample_all as f64 * (1.0 - lod::MIN_SAVING); |
There was a problem hiding this comment.
The skip-thinning decision rests on the first 1000 rows only. Files are often spatially or type-sorted (e.g. a few simple features, then dense coastlines), so the sample can be unrepresentative. That would wrongly skip a worthwhile thinning, or build a full copy that is then discarded by worth. Sampling with a stride across self.projected (step_by(len / sample_size)) would be more robust. It's only a heuristic, so the result stays correct either way. Confidence: low-medium.
Also, all and kept are summed in two more passes, and all could be computed once per layer. This is a minor point.
Code reviewI read the smaller new modules in full ( Bugs
Performance
Quality
Security
AGENTS.md
Change sizeCompared against: the whole PR against main (merge base bc27fe3 to PR head 35c89ce).
|
|
Closing in favour of a new approach tracked in #635: rather than tuning the picture/scene renderer further, vector tiles and raster basemaps move to a MapLibre-style tile layer (fixed GPU pools, tiles prepared once off the main thread, a bounded cancellable scheduler). Thank you for the work and the measurements here — they shaped that plan, and pieces may be reused as it lands. |
Objectives
_NET_WM_PINGduring resize storms (mutter kills the window on ping timeout).Measured impact (honest)
Warm-frame perf table, same machine, base
7dfec13vs HEAD — throughput is unchanged; the fixes are responsiveness:Notes
The initial worker integration double-rendered every stale frame and stamped the wrong camera on delivery; reworked to the settle-only design above. Cull index is Arc-shared (clones stop copying ~12 B/feature), eager-build gate aligned with the renderer's (
>),size_only_changeextracted and tested for real, dot/marker fast paths deduplicated intoink_pixel.Verification
cargo xtask cigreen (fmt, clippy -D warnings, tests, layers). New tests: worker round-trip, eager warming afterlayer.addData, eager cull-index build + Arc sharing, marker path boundary, resize key predicate. Corpus correctness 10/10; perf table quoted above.