Skip to content

Free, open-source 3D sculpting for Linux, macOS and Windows: dense meshes, remeshing, painting, built-in AI (image/text to 3D), Send to Unreal, game-ready LODs, Gaussian splats and OpenUSD.

Merge origin/main (0.11.0-beta.1) into research/core-200m; N1 live (SF_SCREEN_STROKE) measured against Background Preview

islandmed1458b7228e23
diff --cc CMakeLists.txt
index b7e13ef8,4e97bf4a..2cf9c14f
--- a/CMakeLists.txt
+++ b/CMakeLists.txt
@@@ -381,6 -383,6 +385,7 @@@ if(SCULPTFORGE_BUILD_APP
src/render/Camera.cpp
src/render/Clusters.cpp
src/render/Ghost.cpp
++ src/render/ScreenStroke.cpp
src/render/Renderer.cpp
src/render/UvView.cpp
src/render/MicroRenderer.cpp
diff --cc docs/design/core-200m.md
index b2b53094,00000000..11934910
mode 100644,000000..100644
--- a/docs/design/core-200m.md
+++ b/docs/design/core-200m.md
@@@ -1,403 -1,0 +1,435 @@@
+# Core 200M: 200 million sculptable polygons on a 16 GB laptop with an integrated GPU
+
+Research branch `research/core-200m` (2026-11-03). Generic techniques, designed here from first principles (regular
+grids, multiresolution offsets, quantization, page tables, copy-on-write); no competitor code, files or docs.
+
+**Headline target, floor profile** (integrated GPU, GL 3.3, 4 cores; perf-moonshots.md §0, `SF_HW_SIMULATE=floor`):
+
+| | target |
+|---|---|
+| Asset | 200M triangles on a 16 GB laptop with an iGPU (shared video memory) |
+| Stroke latency (pen to visible surface) | < 16 ms |
+| Frame while sculpting | p99 < 33 ms |
+| Orbit | smooth (p99 < 33 ms), full detail refined on release |
+| Open | < 5 s to a sculptable, fully shaded view |
+| Memory | 0.6-1.2 GB for the 200M asset (RSS, everything) |
+
+The rule behind every piece: **cost follows the pixels on screen and the brush footprint, never the total count.**
+
+## 0. What we already have (mapped before designing)
+
+| Piece | Where | State | What it gives 200M | Gap |
+|---|---|---|---|---|
+| Regular grid patches over the base cage, implicit topology | `core/Micro.h` (`MicroMesh`, `MicroPatch`, `BaseCage`) | on | the storage model of §1: one grid of `(n+1)(n+2)/2` points per base triangle, no index buffer, edges stitched | heights are one level, measured from the Phong surface of the cage, not from a smoothed lower level |
+| 16-bit quantized displacement | `MicroMesh::disp` (`MicroStore`) | on | 2 B a grid point, 1.11 B a triangle at Micro 5 | edges and corners stored once per patch (~10% extra at Micro 5) |
+| Derived normals | `MicroShader` (CPU), shading grid on the GPU | on | no normals stored on the CPU | the GPU shading grid is 4 B a point for every patch (440 MB at 200M) and the first full shading runs at open |
+| Per-cluster LOD to a triangle budget | `render/MicroRenderer` | on | draw cost bounded by `renderTriangleBudget` (3-4M drawn at 299M-1B, 8-13 ms on this laptop) | every patch's full grid is resident on the GPU (6 B a point); the budget is triangles, not pixels |
+| Stride-sampled ("scale-adaptive") dabs | `MicroStroke::adaptive`, `kBrushSamples = 48` | on | the kernel evaluates ~48 samples across the radius at any level | the interpolated values are still written to every fine point: a 300 px dab at 1B writes millions of points (283 ms) |
+| Out of core | `MicroStore` (mmap sparse file), `PatchPageTable` | on (auto above 1/4 of RAM) | levels larger than RAM; the OS page cache is the LRU | no compression in memory, no visible-first order |
+| Compressed streamed patches | `core/FocusDetail` (`.sfdetail`, zstd, coarse level-3 grids, focus promotion 0.04 ms a tile) | prototype, off | 1.02B opens in < 1 s from 241 MB; `tileLevel(tri)` per patch | CPU array still dense; GPU doesn't use per-tile levels; not wired into projects |
+| Per-patch undo | `MicroUndo` journal (Morton-ordered tiles, delta + bit-packed) | on | 0.6-11 MB a 30-dab stroke (31 KB for a short stroke at 5M) | rounding noise of fine writes inflates it; coarse-level edits (§3) would shrink it to KBs |
+| Patch-parallel jobs | `ThreadPool::poolFor` in MicroSculpt / Micro / MicroRenderer / FocusDetail | on | deterministic block-parallel kernels | the parallel loops are fork-join per dab; dirty bits are plain words written by one thread at a time; stitching serialises at patch edges |
+| Canvas cache | perf-moonshots.md §7 (research/perf-moonshots) | design | idle frames composite only; a dab re-rasterizes its rectangle | not built |
+
+So phase 1 needs no new storage: a 200M micro level fits on today's code. What it doesn't do yet is make the GPU
+copy, the open time and the big-brush cost follow the screen and the brush. That is phases 2-5.
+
+## 1. Storage
+
+**Layout.** Each base triangle of the cage (the Part's top subdivision level) carries a regular grid of
+`n = 2^L` segments per edge: `n^2` micro triangles, `(n+1)(n+2)/2` points. Topology is implicit (index arithmetic,
+`MicroMesh::index`); only heights are stored.
+
+**Heights against the smoothed lower level.** Phase 1 stores, as today, one 16-bit height per point along the
+normal of the Phong-tessellated cage. The target layout (phase 3) is multiresolution: level `l` stores, per point
+it adds (the odd points of the level-`l` grid), a 16-bit offset from the *smoothed* level `l-1` surface (the
+Loop-style average of its neighbours, evaluated from the coarser level), along that surface's normal. Points that
+exist at `l-1` are not stored again. Total points over all levels are the same as the finest grid (each point is
+stored once, at the level that introduces it), so the memory is the same 2 B a point; what changes is that a big
+form lives in a few coarse values and the fine values stay small (and compress, §4).
+
+**Arithmetic for 200M** (Micro 5: n = 32, 1,024 triangles and 561 points a patch; 195,313 base triangles):
+
+| Item | Per | Count | Bytes |
+|---|---|---|---|
+| Micro triangles | | 195,313 x 1,024 | **200.0M** |
+| Grid points, per-patch copies (today) | 561 a patch | 109.6M | |
+| Grid points, unique (edges once) | ~triangles / 2 | 100.0M | |
+| Heights, today's layout | 2 B a point | 109.6M | **219 MB** (1.10 B a triangle) |
+| Heights, edges stored once (phase 3) | 2 B a point | 100.0M | 200 MB |
+| Base cage + BVH (195K triangles, ~90 B + BVH) | | | ~25 MB |
+| Mask, sparse 32x32-point tiles, 1 B a point | where masked | 10% of the surface | ~11 MB (0 when unused) |
+| Colour, sparse tiles, RGBA8 | where painted | 25% painted / all | ~110 MB / 440 MB |
+| Derived normals | | | 0 on the CPU (computed per patch when drawn) |
+| GPU: today (2 B height + 4 B shading, every patch) | 6 B a point | 109.6M | 658 MB |
+| GPU: pixel-bounded (§2), resident patches only | 6 B a point | ~10-20M points | 60-120 MB |
+| Undo, per-patch copy-on-write (§5), 50 steps | | | ~5-50 MB |
+| App, fonts, GL driver, UI | | | ~250 MB |
+
+- **Sculpt only, pixel-bounded GPU:** 219 + 25 + 120 + 50 + 250 = **~0.66 GB**.
+- **Mask + all-over colour:** + 11 + 440 = **~1.1 GB**.
+- **Today's renderer (phase 1 prototype):** 219 + 25 + 658 (on unified memory this is system RAM) + 250 = ~1.15 GB,
+ plus the shading pass at open. Phase 1 measures this.
+
+So 2 B a vertex for shape, 3 with a mask, 6 with colour everywhere: 2-6 B a vertex, 0.6-1.2 GB for 200M.
+
+## 2. Pixel-bounded draw
+
+- **Per-patch stride LOD.** A patch draws at stride `s = 2^k` (its grid every `s` points: `(n/s)^2` triangles),
+ chosen so its micro edge projects to about one pixel (`targetPx`), clamped by the frame's triangle budget from
+ the hardware profile. MicroRenderer does this per cluster today; phase 2 makes it per patch and makes the GPU
+ *residency* follow it: a patch's GPU grid holds only the levels the view needs (coarse level-3 grids for
+ everything, full grids for the patches whose projected edge needs them), using `FocusDetail::tileLevel(tri)`.
+ Crack-free borders: the finer side snaps its edge points to the coarser edge (as now).
+- **Budget.** At 1920x1080 about 2M pixels are covered at most: ~2-4M triangles drawn at one triangle a pixel,
+ whatever the asset size. On the floor profile 2M (1M moving).
+- **Shading on demand.** Shading (octahedral normal, curvature) is computed for resident patches at their resident
+ level only, visible first; a coarse patch shades its 45 points, not 561 (cuts the open-time shading ~12x at
+ Micro 5, ~180x at Micro 7).
+- **Canvas cache** (perf-moonshots.md §7): with the screen cached, an idle frame composites one quad and a dab
+ re-rasterizes only the patches under its dirty rectangle, so stroke frames cost the brush's pixels.
+- **Orbit:** draw the moving budget (coarser stride, lower view resolution on the floor), refine to full on release.
+
+## 3. Scale-adaptive dabs and lazy push-up
+
+- A dab is applied at the level `l` where its radius spans **64-256 samples** (`r / edge(l)` in that range), not
+ at the finest level. A 300 px brush at 200M lands on a level with ~10^4 points under it instead of ~10^6.
+- With the multiresolution layout (§1) the finer levels are offsets from the smoothed coarser one, so the detail
+ rides along with no write at all; Clay, Standard, Inflate and Move are pure coarse edits.
+- Brushes that need fine values (Smooth of fine detail, Flatten to a plane, Pinch) read the finest level under the
+ brush, so they apply at the finest level their radius allows (radius / 256 or coarser) and only there.
+- **Lazy push-up:** where a coarse edit invalidates something fine (the shading grid, a cached finest-level
+ position on the GPU, a Focus Detail tile's compressed copy), the patch is marked `stale(l)`. Visible stale patches
+ are refreshed within the frame's budget, nearest the brush first; hidden ones by a background job at idle
+ ("catch-up"), or when they become visible. Nothing is pushed into patches nobody looks at.
+- **Checkpoint numbers to beat** (docs/performance.md, today): Standard 300 px 115 ms a step at 299M Micro 4,
+ 283 ms at 1.02B; phase 3 target < 8 ms CPU a dab at 200M on the laptop, < 16 ms on the floor profile.
+
+## 4. Out-of-core compressed patches, visible-first
+
+Reuse Focus Detail (`core/FocusDetail`, docs/design/focus-detail.md): patches as quantized, row-delta coded,
+zstd-compressed tiles, a coarse level-3 grid per tile in compressed chunks, a directory, crash-safe header-last
+saves, promotion 0.04 ms a tile. What 200M adds:
+- **Visible-first open:** read the cage and the coarse chunks (a few MB), draw; then decompress the visible patches
+ nearest the camera first; the rest stream in the background or stay compressed. First frame < 1 s.
+- **Sparse CPU pool** (focus-detail.md §7 item 4): full grids only for promoted patches, indexed per patch, so RSS
+ follows the focus, not the asset. Only required past ~1B on 16 GB; for 200M the dense array (219 MB) is
+ affordable, so this is the last step, not the first.
+- **Project integration:** `.sfproj` stores or references the detail file; Save writes dirty tiles only (53 ms).
+
+## 5. Per-patch copy-on-write undo
+
+A stroke saves, the first time it touches a patch, that patch's old heights (and mask / colour tile); the step is
+the set of touched patches, delta-coded and bit-packed (the `MicroUndo` journal already does this, Morton
+ordered). With coarse-level edits (§3) a big stroke touches thousands of coarse values instead of millions of fine
+ones, so steps become **KBs per stroke** (today 0.6-11 MB for a 30-dab benchmark stroke, from rounding noise in
+fine writes). Undo and redo apply the same deltas; Focus Detail promotes the patches first (`ensureFull`).
+
+## 6. Lock-free patch-parallel jobs
+
+- Patches are the unit of work and ownership: a job owns a patch for the dab (no locks inside), interior points
+ are independent; only edge stitching reads a neighbour, done in a second pass after a barrier, edge by edge
+ (each shared edge has one owner: the patch with the lower index).
+- Dirty and stale state is an atomic bitset (`fetch_or`), so the solver, the renderer's sync and background
+ catch-up never take a lock; the renderer swaps out the dirty words it consumed.
+- A small job graph per frame (pick → dab kernels per patch → stitch → shade visible → upload) on the existing
+ `ThreadPool`, with the block-ordered determinism it already guarantees; background catch-up and decompression
+ run at low priority and yield to the stroke.
+- Floor profile: 4 workers; the stroke's jobs run first, everything else fills idle time.
+
+## 7. Phases and checkpoints
+
+Every number twice: this laptop and the floor profile (`SF_HW_SIMULATE=floor`), at load < 2.
+
+| Phase | What | Checkpoint (measurable) |
+|---|---|---|
+| **1** (this branch) | Memory-only 200M prototype on today's micro levels: `--benchmark core-200m` (off by default; writes the scene once, then opens it and orbits) | RSS, open time (project open, first frame, fully shaded), orbit p50 / p99, GPU MB: measured below |
+| 2 | Pixel-bounded GPU: per-patch resident levels (coarse grids + full where needed), shading on demand, visible first; lower view resolution while moving (helps the median, §8); find the p99 tail with GPU timer queries | GPU < 150 MB at 200M; open to fully shaded < 2 s; orbit p99 < 33 ms on the floor profile; picture equal to today's at rest (screenshot test) |
+| 3 | Multiresolution offsets + dabs at the 64-256-sample level + lazy push-up + background catch-up | 300 px dab < 8 ms CPU on the laptop, < 16 ms floor; stroke latency < 16 ms; p99 frame while sculpting < 33 ms floor; same result as the fine-level brush within quantization (test) |
+| 4 | Focus Detail for 200M: compressed patches, visible-first open, project integration, sparse pool | open < 5 s floor (first frame < 1 s); file < 300 MB; RSS with colour < 1.2 GB |
+| 5 | COW undo on coarse edits; atomic dirty/stale bits; per-frame job graph | undo < 100 KB a typical stroke; 4-thread speed-up > 3x on dab kernels; no lock on the stroke path (TSan clean) |
+| 6 | Canvas cache (perf-moonshots §7) on top; real iGPU runs by testers (Windows UHD 620 / Iris Xe first) | idle frame ~0 ms GPU; floor numbers confirmed on real hardware before anything defaults on |
+
+Nothing here merges into a release without the floor-tier numbers.
+
+## 7b. The novel track (Tony, 11-03: beyond the known playbook)
+
+Sections 1-6 are the known playbook done well (multiresolution offsets, cluster LOD to a pixel budget, a cached
+screen, scale-adaptive dabs). The novel track changes *what a stroke is*, not only how fast it runs. Each item is a
+prototype with numbers before anything ships; measured on this laptop, the floor profile and the Windows PC.
+
+**N1. Optimistic screen-space strokes.** The screen is the first thing a dab changes, the mesh the last. Each dab is
+applied at once to the cached screen (depth, normal, colour) by one GPU pass over the dab's screen rectangle: the
+surface point from depth, the brush's displacement along the dab normal, the bent normal from the kernel's gradient,
+the colour re-shaded by the ratio of the Lit Sphere lookups at the bent and the original normal (so cavity, material
+and paint stay). Cost: the brush's pixels, under 1 ms, whatever the mesh size. The true mesh is solved on the solver
+thread a few frames later and replaces the optimistic pixels; the swap is pop-free where the estimate holds (open
+surface, no silhouette change), and the residual is measured (the "pop": the per-pixel difference between the
+optimistic image and the solved mesh at the same dabs). Stroke latency stops depending on mesh size. Differs from the
+geometry preview we have (render/Ghost.h): that moves the mesh's vertices in the vertex shader, so its cost follows the
+clusters under the brush; N1 never touches geometry. Limits: silhouettes (the outline doesn't move until reconcile),
+brushes that read the surface (Smooth, Flatten: approximated from the canvas's depth), occluded surface (not on screen,
+nothing to show, nothing lost: the solver is exact).
+
+**N2. Wavelet (multi-scale) displacement.** Store each patch's heights as interpolating-wavelet coefficients (integer
+lifting on the triangle grid: a point new at level k stores its height minus the floor-average of its two parents on the
+coarser edge), losslessly invertible. A dab whose radius spans 64-256 samples at level l adds its kernel to the level-l
+coefficients only: a 300 px brush writes thousands of values instead of millions, so **cost falls as the brush grows**,
+and the fine coefficients (the detail) ride along unchanged. Reconstruction (the inverse transform) runs lazily for what
+is drawn or picked, and can move to the GPU (each level is one pass over its new points). The result is identical, bit
+for bit, to adding the coarse kernel and linearly interpolating it to the fine points (tested), which is what today's
+stride-sampled micro brushes approximate at full write cost.
+
+**N3. Procedural stroke layers (research).** A stroke stored as an operation (path, brush, parameters, the base it was
+applied to) instead of its result; detail is evaluated at any resolution on demand, so it isn't bounded by memory, and a
+stroke can be edited after the fact (strength, path, falloff). Hard parts: brushes that read the surface (order
+dependence: replay is sequential), determinism across versions, the cost of evaluating many layers (cache per patch per
+level; N2's coefficients are the cache). Prototype after N1 and N2: a layer stack of Standard / Clay strokes evaluated
+into N2 coefficients per patch on demand.
+
+**N4. Pen prediction for the last frames.** The alpha-beta-gamma predictor (core/PenPredictor.h, from the zero-latency
+work) extrapolates the pen ~25 ms; with N1 the predicted dabs are drawn optimistically too (weight < 1, as the preview
+does), hiding the last frame or two of display latency. Literature: no gain predicting past ~33 ms.
+
+**N5. Idle-time pre-refinement around the cursor.** When the pen hovers, spend idle frames preparing what the next dab
+will need under and ahead of the cursor: Focus Detail promotion, N2 reconstruction of the patches under the cursor, BVH
+and undo-tile allocations, shading. The first dab then finds everything warm (the beta measured a 965 ms first-dab stall
+on Windows at 15M; perf/beta-boost removes its cause, N5 keeps such costs off the stroke in general).
+
+## 7c. Novel track results (N1, N2)
+
+Three setups: this laptop (M1 Pro, Asahi GL 4.6, load < 2), the floor profile on it (`SF_HW_SIMULATE=floor`: 4 solver
+threads; the GPU pass isn't budgeted), and the Windows PC (RTX 3060, Ryzen 5600X, 12 threads; floor = 4).
+
+### N1, optimistic screen-space strokes (`sculptforge --bench-optimistic`)
+
+A 240 px Standard stroke of 30 dabs on the bench head, 1920x1080 canvas. The stroke is placed from the canvas alone
+(centres and area normals from depth). Pass = one GPU pass per dab over its rectangle: inverse warp (for each pixel the
+canvas point whose displaced position lands there, by fixed-point iteration) + the Lit Sphere ratio re-shade at the bent
+normal. Mesh = the same dabs by the real Standard brush on the CPU plus the upload: the latency the canvas hides.
+Pop = the per-pixel difference between the optimistic image and the solved mesh at the same dabs (0-255 levels), against
+showing nothing until the mesh catches up.
+
+| | mesh | pass per dab, median / max | mesh: brush + upload | interior pop, mean / p99 (> 8 levels) | same, doing nothing | outline pixels: pop vs nothing (mean) |
+|---|---|---|---|---|---|---|
+| laptop | 4.9M | 4.7 / 9.7 ms | 332 ms | 4.4 / 21 (15.0%) | 17.7 / 74 (60.0%) | 8.8K: 41 vs 98 |
+| laptop | 15.1M | 4.4 / 8.0 ms | 916 ms | 4.4 / 20 (15.0%) | 17.5 / 72 (59.8%) | 8.8K: 41 vs 98 |
+| laptop | 33.2M | 4.8 / 10.6 ms | 2,450 ms | 4.3 / 19 (15.2%) | 17.1 / 68 (59.4%) | 8.5K: 40 vs 99 |
+| floor | 4.9M / 15.1M / 33.2M | 4.5 / 4.2 / 4.5 ms | 595 / 1,665 / 3,667 ms | 4.4 / 21-19 | 17.7-17.1 / 74-68 | as laptop |
+| Windows | 4.9M / 15.1M / 33.2M | 3.1 / 3.0 / 6.7 ms | 1,156 / 4,282 / 5,057 ms | 4.4 / 21-19 | 17.7-17.1 / 74-68 | 41 vs 98 |
+| Windows floor | 4.9M / 15.1M / 33.2M | 1.3 / 2.2 / 1.4 ms | 1,238 / 3,948 / 8,247 ms | 4.4 / 21-19 | 17.7-17.1 / 74-68 | 41 vs 98 |
+
+- **The pass doesn't depend on the mesh:** 4.2-4.8 ms per dab on the laptop from 5M to 33M while the real brush takes
+ 0.33 s to 2.45 s for the stroke (0.6-3.7 s on the floor, 1.2-8.2 s on the Windows PC). The surface under the pen
+ changes the frame the pen moves, at any mesh size.
+- **The pop is a quarter of doing nothing:** interior mean 4.4 against 17.7 levels, p99 19-21 against 68-74; the
+ outline (where the stroke grows the silhouette) 40 against 98. Identical on every machine (the same maths).
+![N1 at 33M: before, optimistic (under 5 ms), truth (the solved mesh, 2.45 s later), pop map](core-200m-n1.jpg)
+
+- **Looked at** (screenshots before / optimistic / truth / pop map at 5M and 33M): smooth, the features in the right
+ places; the visible residuals are a slightly stair-stepped outline where the surface grows over the background, and
+ shading differences where the solver's per-dab area normals drift from the canvas's estimate.
+- **Not yet < 1 ms.** The prototype re-evaluates every dab of the stroke in every pass (30 here). Live, only the dabs
+ the solver hasn't committed are evaluated (its backlog, a few to a dozen), and accumulating into the canvas (displaced
+ depth and normal written back) makes it one dab per pass; both are the next step. Timing is CPU-side around
+ `glFinish` (an upper bound; the Windows spread 1.3-6.7 ms is that).
+- **Next:** wire it into the live frame (the canvas cache of perf-moonshots §7 A as its storage), the backlog-only
+ evaluation, then Clay / Inflate / Flatten kernels (Flatten reads the canvas plane), then pen prediction (N4) on top.
+
++### N1 live, against Background Preview (floor first)
++
++N1 runs in the app behind `SF_SCREEN_STROKE=1` (render/ScreenStroke, off by default): the dabs Background Preview would
++move in the vertex shader (the solver's backlog plus the predicted head) are applied to the resolved view instead, for
++Standard and Clay in Lit Sphere views; anything else keeps the geometry preview. Measured with proof mode on
++standard-15m, **floor profile, budget pinned** (`SF_HW_SIMULATE=floor SF_GOVERNOR=0`), this laptop, Background Preview
++on (`SF_BG_GHOST=1`) with and without N1, interleaved x2 (load 1.7-1.9; the first ghost run 3.7). N1 drew in 72-100% of
++the Clay frames (`screen_stroke_frames`); Smooth and Move keep the geometry path in both.
++
++| phase | | frame p50 / p99 | GPU p50 / p99 | preview_lag_px p50 / p99 | lag_ms p50 / p99 (committed) |
++|---|---|---|---|---|---|
++| Clay small (25 px) | ghost | 5.8-6.9 / 14.6-16.0 ms | 4.8-6.0 / 10-11 | 2-3 / 11 | 22-29 / 79-88 |
++| | N1 | 8.6-9.6 / 23-26 ms | 6.8-7.4 / 14-15 | 4-5 / 18-23 | 29-30 / 93-99 |
++| Clay large (120 px) | ghost | 9.0-9.3 / 16-22 ms | 7.3 / 13-16 | 4-5 / 13-14 | 145-171 / 228-264 |
++| | N1 | 10.2-10.3 / 16.5-16.6 ms | 8.0-8.2 / 13 | 5 / 18 | 115 / 174-177 |
++| 240 px | ghost | 10.3-13.5 / 19-48 ms | 8.8-11.0 / 14-32 | 6-7 / 20-62 | 339-472 / 532-921 |
++| | N1 | 17.8-17.9 / 25.5-27.9 ms | 15.6-15.7 / 23 | 12 / 29-30 | 238-243 / 370-383 |
++
++Offline on the same 30 dabs (`--bench-optimistic`, floor, load 3.7, indicative): the ghost adds 2.4 ms to a frame at 5M and
++7.0 ms at 15M (it grows with the mesh), N1's pass ~4.8 ms flat; reconcile pop inside the surface N1 4.4 / 21 vs the ghost
++5.5 / 29 (mean / p99 levels), at the outline N1 41 vs the ghost 12.8 (the ghost moves real geometry, so the silhouette is
++right).
++
++**Decision: N1 does not replace the geometry preview.** At 15M on the floor it costs more GPU per frame (15.6 vs 8.8-11 ms
++p50 at 240 px), trails the pointer by a few more pixels (12 vs 6-7 px p50) and is worse at the outline; it is a little
++better inside the surface and its frame p99 at 240 px is steadier. The crossover in cost is around 15-20M (the ghost grows
++with the mesh, N1 doesn't), so N1's place is the meshes the geometry preview can't draw at all: micro levels (no preview
++path today: their strokes run synchronously in the frame loop) and 30M+ meshes. That needs a pending-dab list for micro
++strokes first; until then N1 stays a research toggle and Background Preview remains the one toggle users see. The
++committed lag difference at 240 px (238-243 vs 339-472 ms) is not attributed to N1 yet (the first ghost run was at load
++3.7, and N1 changes no solver work): to repeat at load < 2 before reading anything into it.
++
+### N2, wavelet displacement (`sculptforge --bench-wavelet`)
+
+A Micro 7 head (314.6M micro triangles, 19,200 patches), one Standard dab of growing radius. Today = the adaptive micro
+brush (kernel on a stride, written to every fine point, stitched, undo tiles saved). Wavelet = the kernel added to the
+lattice where the radius spans >= 64 samples; the finer coefficients (the detail) untouched; reconstruct = the inverse
+transform of the touched patches, needed only for what is drawn or picked (deferred). Error = against the exact brush
+(every fine point evaluated), as a share of its largest change.
+
+| radius (~px) | patches | values written: today / wavelet | today: dab (laptop / floor / Win / Win floor) | wavelet: dab (same) | reconstruct (laptop / Win) | wavelet error, mean / max | today's error |
+|---|---|---|---|---|---|---|---|
+| 27 | 50 | 0.19M / 21K | 1.3 / 1.0 / 4.8 / 4.3 ms | 0.9 / 0.7 / 1.4 / 5.0 ms | 0.2 / 0.6 ms | 0.02% / 0.6% | 0.00% / 0.6% |
+| 54 | 106 | 0.51M / 22K | 2.7 / 1.9 / 6.3 / 8.2 ms | 0.4 / 0.6 / 1.6 / 1.1 ms | 0.4 / 1.1 ms | 0.04% / 0.8% | 0.01% / 0.3% |
+| 108 | 301 | 1.69M / 25K | 5.3 / 5.8 / 15.7 / 16.3 ms | 0.3 / 0.4 / 2.8 / 0.9 ms | 1.1 / 5.2 ms | 0.18% / 2.2% | 0.01% / 0.4% |
+| 216 | 1,301 | 8.24M / 40K | 17.0 / 25.6 / 71.7 / 89.4 ms | 0.5 / 0.6 / 12.5 / 1.9 ms | 4.6 / 13.3 ms | 0.04% / 0.5% | 0.01% / 0.4% |
+
+- **Cost falls as the brush grows:** a 216 px dab writes 40K values instead of 8.2M; 0.5 ms against 17 ms on the laptop
+ (35x), 1.9 ms against 89 ms on the Windows floor (47x). The detail rides along without being touched.
+- **Same result within half a percent** of the stroke height at 216 px (max 2.2% at 108 px, where the lattice is
+ coarsest relative to the radius's curvature); today's adaptive brush is within 0.4%.
+- **One anomaly:** on Windows with 12 threads the 216 px wavelet dab took 12.5 ms against 1.9 ms on 4 (and 0.5 ms on the
+ laptop's 10): the thread pool's wake-up cost for 325 tiny jobs on Windows, to fix with bigger blocks before claiming it.
+- **What it costs elsewhere:** the reconstruction (4.6 ms laptop, 13 ms Windows at 216 px) moves off the stroke: lazily,
+ visible patches first, and later on the GPU (each level is one pass over its new points). Undo of a coarse edit is the
+ touched lattice coefficients only (tens of KB). Not measured yet: shading of the reconstructed patches, and a whole
+ stroke (30 dabs) end to end.
+- **Next:** N2 inside MicroStroke behind a flag (coarse path for radii spanning > 64 samples), reconstruct-on-draw in the
+ renderer's sync, then the same idea on the multires mesh path (betaboost's scale-adaptive dabs are its safe first step).
+
+N3-N5 are designed (§7b), not built: N3 builds on N2's coefficients as its cache; N4 and N5 attach to N1 and the
+renderer.
+
+## 8. Phase 1 results
+
+Run: `sculptforge --benchmark core-200m --benchmark-no-video` (Release). The scene: the bench head at 196,608 base
+triangles (asked for 195,313; the head's cube quads round it), Micro 5, two octaves of `microNoise` (wrinkle- and pore-sized), in memory; written once as a project
+in the swap folder, then each run opens it (`loadProject`), shows it, waits until the shading is complete and
+orbits twice (10 s each, the view moving every frame).
+
+**This laptop** (MacBook Pro 16" M1 Pro, 10 cores, 32 GB unified, Asahi Mesa 26.1.8 GL 4.6, framebuffer 3408x2136;
+Release @ the branch's SHA; three runs back to back at 1-minute load 1.8 / 2.2 / 1.8, so at or just about load 2):
+
+| | run a | run b | run c |
+|---|---:|---:|---:|
+| Micro triangles (196,608 base x 1,024, Micro 5) | 201.3M | 201.3M | 201.3M |
+| Project file (written once) | 148 MB | | |
+| Open project (`loadProject`) | 0.17 s | 0.17 s | 0.17 s |
+| Open to first frame (shading and upload of every patch included) | 0.69 s | 0.69 s | 0.70 s |
+| RSS when shown | 569 MB | 567 MB | 578 MB |
+| Peak RSS (whole run) | 579 MB | 569 MB | 591 MB |
+| GPU buffers (renderer, not in RSS; on unified memory this is system RAM too) | 640 MB | 640 MB | 640 MB |
+| Orbit 1 (10 s, moving every frame): p50 / p99 | 12.4 / 51.7 ms | 12.9 / 35.9 ms | 12.6 / 32.1 ms |
+| Orbit 2: p50 / p99 | 12.2 / 37.5 ms | 12.8 / 24.4 ms | 13.3 / 37.7 ms |
+| Worst single frame | 68 ms | 66 ms | 67 ms |
+
+Reading it:
+- **Memory: met.** 0.57-0.59 GB RSS plus 0.64 GB of GPU buffers = ~1.2 GB in all for 200M, the top of the 0.6-1.2 GB
+ range of §1, as predicted for today's renderer (every patch's full grid on the GPU). Phase 2 takes the 640 MB
+ down to ~100 MB.
+- **Open: met** (0.7 s to a fully shaded view, target < 5 s). The first frame shades every patch at once
+ (~0.5 s at 110M points on 10 cores); on 4 floor cores that is ~1.3 s, still a single stall phase 2 removes.
+- **Orbit: p50 met (~80 fps), p99 not yet.** p99 24-52 ms against < 33 ms; one 60-68 ms frame per run. The p50 is
+ the per-cluster LOD doing its job (the draw follows the budget, not the 200M); the tail is not yet explained
+ (candidates: the motion-proxy switch at the start of a move, shared-machine noise at load ~2, the 7.3M-pixel
+ framebuffer). To profile in phase 2 before claiming "smooth".
+- **Floor profile:** see the next section.
+
+### Floor profile (`SF_HW_SIMULATE=floor`, research/perf-moonshots 94c9136f cherry-picked)
+
+Before the run: the micro renderer did **not** read the governed `renderTriangleBudget()`. It took
+`RenderSettings::renderTriangleBudget` (never set) or else `TierConfig::activeTriangleBudget`, which is 2M on the
+Laptop tier, so a floor run would have drawn exactly what the laptop draws. Fixed on this branch: the micro budget is
+now `min(tier budget, governed budget)`, so the governor and the floor profile can lower it and nothing ever raises
+it (the laptop's draw is unchanged). `residentCacheCapMB` (1 GB on the floor) is read only by the out-of-core trim;
+this in-memory scene never reaches it (RSS 0.58 GB), so it has no effect here.
+
+Six runs interleaved laptop / floor, each started at 1-minute load < 2 (1.49-1.96):
+
+| | laptop (3 runs) | floor (3 runs) |
+|---|---|---|
+| Open project / to fully shaded first frame | 0.16-0.19 / 0.69-0.72 s | 0.16-0.17 / 0.68-0.75 s |
+| RSS when shown / GPU buffers | 567-583 / 640 MB | 579-582 / 640 MB |
+| Governed budget at the end / triangles drawn while orbiting (p50) | 1-2M / 1.22M | 1M / 0.30-0.62M |
+| Orbit p50 | 8.1-12.6 ms | 7.1-10.9 ms |
+| Orbit p99 | 21.3-41.4 ms | 18.1-38.5 ms |
+| Worst frame | 55-71 ms | 50-68 ms |
+
+Orbit frame split (main thread, ms p50 / p99; sculpt and upload are 0.0 / <= 0.1 everywhere):
+
+| | events | UI | draw (issue) | swap wait (GPU) |
+|---|---|---|---|---|
+| laptop, 6 orbits | 0.0 / 0.1-1.8 | 0.5-1.0 / 1.7-3.3 | 1.2-2.2 / 6.3-14.6 | 6.0-8.7 / 13.7-28.8 |
+| floor, 6 orbits | 0.0 / 0.1-1.2 | 0.6-1.0 / 1.8-3.3 | 1.0-1.7 / 6.0-12.1 | 5.5-7.5 / 14.3-25.4 |
+
+**Where the time goes:** 70-80% of an orbit frame is the swap wait (the GPU finishing the frame); sculpt, upload
+and UI are negligible. The floor draws a quarter of the triangles (0.3M against 1.2M) yet its swap wait drops only
+from ~8.7 to ~6.5 ms p50, so the *median* follows the pixels (3408x2136 = 7.3M, each sampling the full-resolution
+shading grid), not the triangles. The tail is a different matter (next section).
+
+### View resolution while moving (perf-moonshots a45b06bd, `SF_MOTION_RESOLUTION`), floor profile
+
+Nine floor runs interleaved 100 / 75 (the floor default) / 50 %, each at 1-minute load < 2 (1.60-1.97). Orbit, two
+per run, ms:
+
+| Moving resolution | frame p50 | frame p99 | p99 < 33 ms | worst frame | swap wait p50 / p99 | draw issue p50 / p99 | drawn p50 |
+|---|---|---|---|---|---|---|---|
+| 100 % | 7.9-11.8 | 15.3-31.7 | 6 of 6 | 27-73 | 6.3-8.2 / 13.2-21.0 | 0.4-2.1 / 3.7-10.7 | 0.3-1.2M |
+| 75 % (default) | 9.8-12.8 | 26.7-37.5 | 4 of 6 | 48-67 | 6.9-8.4 / 14.1-24.9 | 1.6-3.2 / 10.4-15.0 | 0.7-1.4M |
+| 50 % | 5.2-9.3 | 12.3-33.9 | 5 of 6 | 23-68 | 4.4-6.0 / 11.1-22.7 | 0.3-1.6 / 2.2-15.4 | 0.6M |
+
+- **Resolution moves the median, not the tail.** 50 % takes ~25 % off the swap wait p50 (6.6 → 5.3 ms), as a
+ per-pixel cost should; the p99 and the worst frames (50-70 ms in every setting) don't follow it. **Resolution
+ alone does not get 200M reliably under 33 ms p99**; between settings the spread from run to run is larger than the
+ effect.
+- **A confound: the governor.** Triangles drawn differ between runs of the same setting (0.3M or 1.2M at 100 %) because
+ the frame governor lowers the budget during some runs; 75 % happened to run at the larger budget (1.44M), which
+ explains part of why it looks worse than 100 %. Floor A/Bs need the governor pinned (a fixed budget) to compare.
+- **The tail follows draw-issue stalls.** In every orbit the frame p99 tracks the draw p99 (the main thread inside the
+ driver): orbits with draw p99 <= 4.5 ms have frame p99 12-18 ms; those with 10-15 ms have 23-38 ms.
+- **Tested and ruled out: the per-frame level upload.** The micro renderer rewrites its small per-cluster level buffer
+ (a `GL_STATIC_DRAW` texture buffer) every frame with `glBufferSubData`, a classic implicit-sync pattern. Orphaning it
+ (a new store per frame, GL 3.3) in a 3 + 3 interleaved A/B (floor, 75 %, load 1.29-1.99): p99 29.7-43.7 ms before
+ against 24.7-37.9 ms after, draw p99 11.9-20.8 against 11.1-14.9 ms: a small shift inside the noise, not the cause,
+ so it was not kept.
+### GPU time vs frame time (governor pinned: `SF_GOVERNOR=0`, perf-moonshots eb2f2aac)
+
+Six floor runs interleaved 100 / 75 %, load 1.39-1.94; GPU time is the frame's own GL work (`GL_TIME_ELAPSED`,
+every frame had a result: gpu_frames = frames). Orbit, ms:
+
+| Moving resolution | drawn | frame p50 / p99 / max | GPU p50 / p99 / max | swap wait p99 | draw issue p99 |
+|---|---|---|---|---|---|
+| 100 % | 1.22M (fixed) | 10.7-13.1 / 30.8-37.9 / 49-83 | 7.2-8.2 / 12.6-15.7 / 32-44 | 15-28 | 11-17 |
+| 75 % | 1.44M (fixed) | 11.8-12.3 / 28.9-43.0 / 55-68 | 7.7-7.9 / 12.7-18.1 / 16-51 | 16-27 | 11-17 |
+
+**The tail is not our GPU work.** Our frames cost the GPU 8 ms (p50) and 13-18 ms (p99); the frame p99 is 29-43 ms.
+15-25 ms of the tail is outside our GL commands: presentation (the swap through the desktop compositor) and the
+driver blocking the draw calls on this shared Asahi desktop. That is this machine's stack, not the engine; the
+Windows PC (RTX 3060) run below shows the same scene on a desktop GPU and driver.
+
+
+### Windows PC (RTX 3060, NVIDIA 616.56, Ryzen 5600X, 32 GB; 1920x1080; CI Windows build of this branch)
+
+Six runs interleaved real GPU / floor 100 % / floor 75 %, governor pinned (`SF_GOVERNOR=0`); every run's log checked
+for the profile it ran with. Orbit, ms:
+
+| | drawn | frame p50 / p99 / max | GPU p50 / p99 | swap wait p99 | open / first frame |
+|---|---|---|---|---|---|
+| real GPU (x2) | 0.62M | 0.8-0.9 / 2.1-2.3 / 3-8 | 0.6 / 1.7-2.1 | 0.4-1.2 | 0.29-0.30 / 1.32-1.34 s |
+| floor 100 % (x2) | 0.62M | 0.8-0.9 / 2.2-2.3 / 3-10 | 0.6 / 1.7-2.0 | 0.3-1.1 | 0.28-0.35 / 1.36-1.41 s |
+| floor 75 % (x2) | 0.36M | 0.9 / 2.2 / 3-11 | 0.5 / 1.5-1.8 | 0.8-0.9 | 0.30-0.38 / 1.33-1.44 s |
+
+- **200M orbits at ~1,100 fps, p99 2.2 ms**, 15x under the 33 ms target, on the floor budgets too. The 29-43 ms tail of
+ the M1 laptop is its presentation stack (above), not the engine.
+- First frame 1.3-1.4 s (the first full shading of 110M grid points on 6 cores) against 0.7 s on the M1's 10; within
+ the < 5 s target, and phase 2 (shading on demand) removes it.
+- The floor profile on a 3060 tests the budgets, not an iGPU's fill rate; real iGPU runs by testers still decide.
+- RAM was not measured on Windows: `residentBytes()` read only Linux's /proc, so every Windows and macOS benchmark
+ reported 0 MB. Fixed on this branch (working set / Mach task info); remeasured below once the CI build is in.
+
+What the floor simulation does not show: a real iGPU's fill rate (it doesn't slow the GPU) and 4-core open time
+(the open stayed 0.7 s; whether the first shading runs on the capped pool is not verified). Real UHD 620 / Iris Xe
+runs by testers are what confirm it.
+
+Reproduce: `sculptforge --benchmark core-200m --benchmark-no-video` (the first run writes
+`~/.cache/sculptforge/core-200m-v1.sfproj`, about 3 s). Test: `micro_core200m_scene_small` (scene build, in memory,
+project round trip bit-exact).
diff --cc src/app/AsyncStroke.cpp
index 9d4c027c,0f117024..15b94c5a
--- a/src/app/AsyncStroke.cpp
+++ b/src/app/AsyncStroke.cpp
@@@ -404,7 -434,26 +434,27 @@@ bool App::ghostSurface(const glm::vec3
void App::buildGhost() {
ghostHeadValid_ = false;
++ renderer_.setScreenStroke(GhostStroke()); // (set again below when this frame's dabs draw on the screen)
const uint32_t id = doc_.activeSubtoolInfo().id;
+ if (liveMove_.active) { // Live Move: one "dab" per mirror, the whole move so far
+ GhostStroke g;
+ g.kind = GhostKind::Move;
+ g.focal = focalShift_;
+ std::vector<SymCopy> mirrors = Sculptor::copies(symmetry_);
+ if (mirrors.size() > GhostStroke::kMaxMirrors) mirrors.resize(GhostStroke::kMaxMirrors);
+ for (uint32_t m = 0; m < mirrors.size(); ++m) {
+ GhostDab d;
+ d.center = mirrors[m].point(liveMove_.center);
+ d.radius = liveMove_.radius;
+ d.normal = mirrors[m].m * liveMove_.delta;
+ d.strength = liveMove_.scale;
+ d.areaCenter = d.center;
+ d.mirror = m;
+ g.dabs.push_back(d);
+ }
+ renderer_.setGhost(id, g);
+ return;
+ }
static const bool noGhost = [] { // SF_GHOST=0: the solver thread without the preview (for comparison)
const char* v = std::getenv("SF_GHOST");
return v && *v == '0';
@@@ -481,6 -530,6 +531,16 @@@
d.mirror = m;
g.dabs.push_back(d);
}
++ // Research (render/ScreenStroke.h; SF_SCREEN_STROKE=1): the pending dabs drawn on the view, not the geometry.
++ static const bool screenStroke = [] {
++ const char* v = std::getenv("SF_SCREEN_STROKE");
++ return v && *v == '1';
++ }();
++ if (screenStroke && ScreenStroke::supports(g) && renderSettings_.matcap >= 0 && !renderSettings_.pbr()) {
++ renderer_.setScreenStroke(g);
++ renderer_.setGhost(id, GhostStroke());
++ return;
++ }
renderer_.setGhost(id, g);
}
diff --cc src/app/OptimisticBench.cpp
index 5d93409d,00000000..2e075f48
mode 100644,000000..100644
--- a/src/app/OptimisticBench.cpp
+++ b/src/app/OptimisticBench.cpp
@@@ -1,503 -1,0 +1,544 @@@
+// SculptForge - open source digital sculpting
+// SPDX-License-Identifier: GPL-3.0-or-later
+#include "app/OptimisticBench.h"
+
+#include "core/BVH.h"
+#include "core/Document.h"
+#include "core/HardwareProfile.h"
+#include "core/Image.h"
+#include "core/Sculpt.h"
+#include "core/Symmetry.h"
+#include "core/ThreadPool.h"
+#include "render/Camera.h"
+#include "render/GL.h"
+#include "render/Renderer.h"
+
+#include <SDL3/SDL.h>
+#include <glm/gtc/matrix_transform.hpp>
+#include <glm/gtc/type_ptr.hpp>
+
+#include <algorithm>
+#include <chrono>
+#include <cmath>
+#include <cstdio>
+#include <filesystem>
+#include <fstream>
+#include <sstream>
+
+namespace sf {
+
+namespace {
+
+using Clock = std::chrono::steady_clock;
+double msSince(Clock::time_point t) { return std::chrono::duration<double, std::milli>(Clock::now() - t).count(); }
+
+constexpr GLenum kDepthComponent = 0x1902;
+constexpr int kW = 1920, kH = 1080;
+constexpr int kMaxDabs = 64; // the pass's uniform arrays
+
+// One pass over a dab's screen rectangle: every dab of the stroke so far displaces the canvas's surface point along
+// its area normal by the Standard kernel (core/Sculpt.cpp, as render/Ghost.cpp's ghostMove), the normal bends by the
+// kernels' gradients, and the colour is re-shaded by the ratio of the Lit Sphere lookups (the mesh shader's, view
+// space) at the bent and the original normal, so cavity, material and paint stay as drawn.
+const char* kVS = R"(#version 330 core
+void main() {
+ vec2 p = vec2((gl_VertexID << 1) & 2, gl_VertexID & 2);
+ gl_Position = vec4(p * 2.0 - 1.0, 0.0, 1.0);
+}
+)";
+const char* kFS = R"(#version 330 core
+uniform sampler2D uColor, uDepth, uMatcapTex;
+uniform mat4 uInvProj, uProj;
+uniform vec2 uProjScale, uSize;
+uniform int uCount;
+uniform vec4 uDabC[64]; // view-space centre, radius
+uniform vec4 uDabN[64]; // view-space area normal, amplitude (strength x radius x 0.06)
+out vec4 fragColor;
+bool surface(ivec2 p) { return texelFetch(uDepth, clamp(p, ivec2(0), ivec2(uSize) - 1), 0).r < 1.0; }
+vec3 viewPos(ivec2 p) {
+ p = clamp(p, ivec2(0), ivec2(uSize) - 1);
+ float d = texelFetch(uDepth, p, 0).r;
+ vec4 q = uInvProj * vec4((vec2(p) + 0.5) / uSize * 2.0 - 1.0, d * 2.0 - 1.0, 1.0);
+ return q.xyz / q.w;
+}
+vec3 lit(vec3 n, vec3 v) {
+ vec3 bx = normalize(vec3(v.z, 0.0, -v.x));
+ vec3 by = cross(v, bx);
+ vec2 uv = vec2(dot(bx, n), dot(by, n)) * 0.495 + 0.5;
+ return pow(texture(uMatcapTex, uv).rgb, vec3(2.2));
+}
+// The displacement of the surface point P by every dab (the Standard kernel along each area normal), and the
+// tangential gradient that bends a normal n.
+vec3 displace(vec3 P, vec3 n, out vec3 g) {
+ vec3 m = vec3(0.0);
+ g = vec3(0.0);
+ for (int i = 0; i < uCount; ++i) {
+ vec3 o = P - uDabC[i].xyz;
+ float dist = length(o), rad = uDabC[i].w;
+ if (dist >= rad || dist < 1e-9) continue;
+ float t = 1.0 - dist / rad;
+ m += uDabN[i].xyz * (uDabN[i].w * t * t * (3.0 - 2.0 * t));
+ vec3 grad = uDabN[i].w * (-(6.0 * t - 6.0 * t * t) / rad) * o / dist;
+ g += (grad - n * dot(grad, n)) * dot(uDabN[i].xyz, n);
+ }
+ return m;
+}
+// The surface normal from depth, smoothed: central differences over baselines of 1-3 pixels summed (the canvas holds
+// the mesh's facets, the mesh shader interpolates vertex normals), each pair skipped across a depth jump.
+vec3 normalAt(ivec2 p) {
+ vec3 P = viewPos(p), sum = vec3(0.0);
+ for (int k = 1; k <= 3; ++k) {
+ vec3 l = viewPos(p - ivec2(k, 0)), r = viewPos(p + ivec2(k, 0)), d = viewPos(p - ivec2(0, k)), u = viewPos(p + ivec2(0, k));
+ float jump = 0.05 * abs(P.z);
+ if (abs(r.z - l.z) > jump || abs(u.z - d.z) > jump) continue;
+ sum += cross(r - l, u - d);
+ }
+ if (dot(sum, sum) < 1e-30) { // (at an edge: the one-pixel step on the smaller side)
+ vec3 l = viewPos(p - ivec2(1, 0)), r = viewPos(p + ivec2(1, 0)), d = viewPos(p - ivec2(0, 1)), u = viewPos(p + ivec2(0, 1));
+ sum = cross(abs(r.z - P.z) < abs(P.z - l.z) ? r - P : P - l, abs(u.z - P.z) < abs(P.z - d.z) ? u - P : P - d);
+ }
+ vec3 n = normalize(sum);
+ return dot(n, P) > 0.0 ? -n : n;
+}
+vec2 toPixel(vec3 P) {
+ vec4 c = uProj * vec4(P, 1.0);
+ return (c.xy / c.w * 0.5 + 0.5) * uSize - 0.5;
+}
+void main() {
+ vec2 p = gl_FragCoord.xy - 0.5;
+ // Inverse warp: the canvas pixel q whose displaced surface point lands on p (fixed point q = p - offset(q)),
+ // from p and, for pixels the surface may grow over, from points towards the nearest dab.
+ vec2 best = vec2(-1.0);
+ vec2 toward = vec2(0.0);
+ float near = 1e30;
+ for (int i = 0; i < uCount; ++i) {
+ vec2 c = toPixel(uDabC[i].xyz);
+ if (distance(c, p) < near) near = distance(c, p), toward = c - p;
+ }
+ float bestErr = 4.0; // (accept a landing within 2 px; the closest one found)
+ for (int s = 0; s < 4 && bestErr > 0.04; ++s) {
+ vec2 q = p + toward * (0.12 * float(s));
+ for (int k = 0; k < 16; ++k) {
+ ivec2 iq = ivec2(floor(q + 0.5));
+ if (!surface(iq)) break;
+ vec3 g;
+ vec3 P = viewPos(iq);
+ vec2 err = toPixel(P + displace(P, vec3(0.0), g)) - p; // (the bend isn't needed here)
+ float e = dot(err, err);
+ if (e < bestErr) bestErr = e, best = q - err;
+ if (e < 0.04) break;
+ q -= err * (k < 8 ? 1.0 : 0.5); // (damped later: where the warp folds, a full step can oscillate)
+ }
+ }
+ ivec2 ip = ivec2(p);
+ if (best.x < 0.0) {
+ if (!surface(ip)) { fragColor = texelFetch(uColor, ip, 0); return; } // background stays
+ best = p; // (no landing point found: shade in place)
+ }
+ ivec2 iq = ivec2(floor(best + 0.5));
+ vec3 n0 = normalAt(iq);
+ vec3 g;
+ displace(viewPos(iq), n0, g);
+ vec3 n1 = normalize(n0 - g);
+ vec2 ndc = (gl_FragCoord.xy / uSize) * 2.0 - 1.0;
+ vec3 v = normalize(vec3(-ndc / uProjScale, 1.0)); // the mesh shader's viewRay
+ vec3 ratio = lit(n1, v) / max(lit(n0, v), vec3(1e-3));
+ vec4 c = texture(uColor, (best + 0.5) / uSize); // (bilinear at the landing point: no stair-steps where it stretches)
+ fragColor = vec4(pow(pow(c.rgb, vec3(2.2)) * ratio, vec3(1.0 / 2.2)), c.a);
+}
+)";
+
+GLuint compile(GLenum type, const char* src, std::string& error) {
+ GLuint s = gl::CreateShader(type);
+ gl::ShaderSource(s, 1, &src, nullptr);
+ gl::CompileShader(s);
+ GLint ok = 0;
+ gl::GetShaderiv(s, GL_COMPILE_STATUS, &ok);
+ if (!ok) {
+ char log[2048] = {};
+ gl::GetShaderInfoLog(s, sizeof log, nullptr, log);
+ error = log;
+ }
+ return s;
+}
+
+struct Target {
+ GLuint fbo = 0, color = 0, depth = 0;
+ void make(bool withDepth) {
+ gl::GenTextures(1, &color);
+ gl::BindTexture(GL_TEXTURE_2D, color);
+ gl::TexImage2D(GL_TEXTURE_2D, 0, GLint(GL_RGBA8), kW, kH, 0, GL_RGBA, GL_UNSIGNED_BYTE, nullptr);
+ gl::TexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GLint(GL_NEAREST));
+ gl::TexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GLint(GL_NEAREST));
+ gl::GenFramebuffers(1, &fbo);
+ gl::BindFramebuffer(GL_FRAMEBUFFER, fbo);
+ gl::FramebufferTexture2D(GL_FRAMEBUFFER, GL_COLOR_ATTACHMENT0, GL_TEXTURE_2D, color, 0);
+ if (withDepth) {
+ gl::GenTextures(1, &depth);
+ gl::BindTexture(GL_TEXTURE_2D, depth);
+ gl::TexImage2D(GL_TEXTURE_2D, 0, GLint(GL_DEPTH_COMPONENT24), kW, kH, 0, kDepthComponent, GL_FLOAT, nullptr);
+ gl::TexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GLint(GL_NEAREST));
+ gl::TexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GLint(GL_NEAREST));
+ gl::FramebufferTexture2D(GL_FRAMEBUFFER, GL_DEPTH_ATTACHMENT, GL_TEXTURE_2D, depth, 0);
+ }
+ gl::BindFramebuffer(GL_FRAMEBUFFER, 0);
+ }
+ void release() {
+ gl::DeleteFramebuffers(1, &fbo);
+ gl::DeleteTextures(1, &color);
+ if (depth) gl::DeleteTextures(1, &depth);
+ *this = {};
+ }
+};
+
+std::vector<uint8_t> readColor(const Target& t) {
+ std::vector<uint8_t> px(size_t(kW) * kH * 4);
+ gl::BindFramebuffer(GL_FRAMEBUFFER, t.fbo);
+ gl::PixelStorei(GL_PACK_ALIGNMENT, 1);
+ gl::ReadPixels(0, 0, kW, kH, GL_RGBA, GL_UNSIGNED_BYTE, px.data());
+ gl::BindFramebuffer(GL_FRAMEBUFFER, 0);
+ return px;
+}
+
+void savePng(const std::vector<uint8_t>& px, const std::string& path) {
+ Image img;
+ img.width = kW, img.height = kH;
+ img.rgba.resize(px.size());
+ for (int y = 0; y < kH; ++y) // (GL rows are bottom-up)
+ std::copy_n(px.data() + size_t(kH - 1 - y) * kW * 4, size_t(kW) * 4, img.rgba.data() + size_t(y) * kW * 4);
+ std::string err;
+ if (!img.savePng(path, err)) std::fprintf(stderr, "%s\n", err.c_str());
+}
+
+struct Diff {
+ double mean = 0, p99 = 0, over8 = 0; // over the region either image changed (0-255 levels, fraction)
+ size_t pixels = 0;
+};
+// Per-pixel max channel difference of a and b over the pixels where `before` differs from either; `mask` (one per
+// pixel, optional) keeps only the pixels it marks.
+Diff diff(const std::vector<uint8_t>& a, const std::vector<uint8_t>& b, const std::vector<uint8_t>& before,
+ const std::vector<uint8_t>* mask = nullptr) {
+ std::vector<int> d;
+ for (size_t i = 0; i < a.size(); i += 4) {
+ if (mask && !(*mask)[i / 4]) continue;
+ int ca = 0, cb = 0, ab = 0;
+ for (int k = 0; k < 3; ++k) {
+ ca = std::max(ca, std::abs(int(a[i + k]) - int(before[i + k])));
+ cb = std::max(cb, std::abs(int(b[i + k]) - int(before[i + k])));
+ ab = std::max(ab, std::abs(int(a[i + k]) - int(b[i + k])));
+ }
+ if (ca > 1 || cb > 1) d.push_back(ab);
+ }
+ Diff r;
+ r.pixels = d.size();
+ if (d.empty()) return r;
+ double sum = 0;
+ size_t over = 0;
+ for (int v : d) sum += v, over += v > 8;
+ std::sort(d.begin(), d.end());
+ r.mean = sum / double(d.size());
+ r.p99 = d[std::min(d.size() - 1, size_t(double(d.size()) * 0.99))];
+ r.over8 = double(over) / double(d.size());
+ return r;
+}
+
+double median(std::vector<double> v) {
+ if (v.empty()) return 0;
+ std::sort(v.begin(), v.end());
+ return v[v.size() / 2];
+}
+
+} // namespace
+
+bool parseOptimisticBenchArg(int argc, char** argv, int& i, bool& run, OptimisticBenchOptions& o) {
+ const std::string a = argv[i];
+ auto next = [&]() -> std::string { return i + 1 < argc ? argv[++i] : std::string(); };
+ if (a == "--bench-optimistic") run = true;
+ else if (a == "--bench-optimistic-sizes") {
+ o.sizesMillions.clear();
+ std::stringstream ss(next());
+ for (std::string s; std::getline(ss, s, ',');)
+ if (!s.empty()) o.sizesMillions.push_back(std::atof(s.c_str()));
+ } else if (a == "--bench-optimistic-out") o.outPath = next();
+ else if (a == "--bench-optimistic-shots") o.shotsDir = next();
+ else return false;
+ return true;
+}
+
+int runOptimisticBench(const OptimisticBenchOptions& o) {
+ if (simulatedFloorTier()) ThreadPool::setSharedThreadCount(4); // SF_HW_SIMULATE=floor: the solver on 4 cores
+ if (!SDL_Init(SDL_INIT_VIDEO)) {
+ std::fprintf(stderr, "SDL_Init failed: %s\n", SDL_GetError());
+ return 1;
+ }
+ SDL_GL_SetAttribute(SDL_GL_CONTEXT_MAJOR_VERSION, 3);
+ SDL_GL_SetAttribute(SDL_GL_CONTEXT_MINOR_VERSION, 3);
+ SDL_GL_SetAttribute(SDL_GL_CONTEXT_PROFILE_MASK, SDL_GL_CONTEXT_PROFILE_CORE);
+ SDL_GL_SetAttribute(SDL_GL_CONTEXT_FLAGS, SDL_GL_CONTEXT_FORWARD_COMPATIBLE_FLAG);
+ SDL_Window* window = SDL_CreateWindow("SculptForge optimistic strokes", 320, 200, SDL_WINDOW_OPENGL | SDL_WINDOW_HIDDEN);
+ SDL_GLContext context = window ? SDL_GL_CreateContext(window) : nullptr;
+ if (!context) {
+ std::fprintf(stderr, "OpenGL 3.3 context creation failed: %s\n", SDL_GetError());
+ if (window) SDL_DestroyWindow(window);
+ SDL_Quit();
+ return 1;
+ }
+ SDL_GL_MakeCurrent(window, context);
+ int code = 0;
+ std::string error;
+ Renderer renderer;
+ if (const char* missing = gl::load([](const char* n) { return reinterpret_cast<gl::GenericProc>(SDL_GL_GetProcAddress(n)); })) {
+ std::fprintf(stderr, "Missing OpenGL function: %s\n", missing);
+ code = 1;
+ } else if (!renderer.init(error)) {
+ std::fprintf(stderr, "%s\n", error.c_str());
+ code = 1;
+ }
+ GLuint prog = 0, vao = 0;
+ if (code == 0) {
+ GLuint vs = compile(GL_VERTEX_SHADER, kVS, error), fs = compile(GL_FRAGMENT_SHADER, kFS, error);
+ prog = gl::CreateProgram();
+ gl::AttachShader(prog, vs);
+ gl::AttachShader(prog, fs);
+ gl::LinkProgram(prog);
+ GLint ok = 0;
+ gl::GetProgramiv(prog, GL_LINK_STATUS, &ok);
+ gl::DeleteShader(vs);
+ gl::DeleteShader(fs);
+ if (!ok) {
+ std::fprintf(stderr, "optimistic pass: %s\n", error.c_str());
+ code = 1;
+ }
+ gl::GenVertexArrays(1, &vao);
+ }
+ std::ostringstream md;
+ md << "## Optimistic screen-space strokes (N1), " << reinterpret_cast<const char*>(gl::GetString(GL_RENDERER)) << "\n\n"
+ << "Canvas " << kW << "x" << kH << ", Standard, " << o.dabs << " dabs of " << o.radiusPx << " px, strength 0.5.\n\n"
+ << "| Mesh | pass per dab (GPU, median / max) | whole stroke on the canvas | mesh: Standard dabs (CPU) + upload | "
+ "interior pop: optimistic vs truth (mean / p99 levels, > 8) | interior, doing nothing vs truth | pixels | "
+ "outline (coverage changed): pixels, pop vs doing nothing (mean) |\n"
+ << "|---|---:|---:|---:|---:|---:|---:|---:|\n";
++ std::string ghostRows;
+ for (double sizeM : o.sizesMillions) {
+ if (code) break;
+ Document doc;
+ std::fprintf(stderr, "core-200m N1: %gM head...\n", sizeM);
+ doc.mesh = makeBenchHead(size_t(sizeM * 1e6));
+ doc.bvh.build(doc.mesh);
+ Mesh& m = doc.mesh;
+ Camera cam;
+ cam.aspect = float(kW) / float(kH);
+ cam.frame(m.bounds());
+ RenderSettings rs;
+ std::vector<SceneMesh> scene{SceneMesh{1, &m, true, true}};
+ renderer.syncScene(scene);
+ Target canvas, out;
+ canvas.make(true);
+ out.make(false);
+ gl::BindFramebuffer(GL_FRAMEBUFFER, canvas.fbo);
+ gl::Viewport(0, 0, kW, kH);
+ renderer.draw(cam, kW, kH, rs);
+ gl::Finish();
+ const std::vector<uint8_t> before = readColor(canvas);
+ std::vector<float> depth(size_t(kW) * kH);
+ gl::BindFramebuffer(GL_FRAMEBUFFER, canvas.fbo);
+ gl::ReadPixels(0, 0, kW, kH, kDepthComponent, GL_FLOAT, depth.data());
+ gl::BindFramebuffer(GL_FRAMEBUFFER, 0);
+ const glm::mat4 view = cam.view(), proj = cam.projection(), invProj = glm::inverse(proj), invView = glm::inverse(view);
+ auto viewAt = [&](float x, float y) {
+ const int ix = std::clamp(int(x), 0, kW - 1), iy = std::clamp(int(y), 0, kH - 1);
+ const float d = depth[size_t(iy) * kW + ix];
+ glm::vec4 q = invProj * glm::vec4((x + 0.5f) / kW * 2 - 1, (y + 0.5f) / kH * 2 - 1, d * 2 - 1, 1);
+ return std::pair<glm::vec3, bool>(glm::vec3(q) / q.w, d < 1.0f);
+ };
+ // The stroke, from the canvas alone: a line across the face; each dab's centre from the depth under the
+ // pointer, its radius from the pixel size there, its area normal from the depth on a ring around it.
+ struct Dab {
+ glm::vec3 cView, nView;
+ float radius;
+ };
+ std::vector<Dab> dabs;
+ for (int i = 0; i < std::min(o.dabs, kMaxDabs); ++i) {
+ const float u = float(i) / float(std::max(1, o.dabs - 1));
+ const float x = kW * (0.38f + 0.24f * u), y = kH * (0.55f + 0.04f * std::sin(u * 6.2831853f));
+ auto [c, hit] = viewAt(x, y);
+ if (!hit) continue;
+ const float pxWorld = -c.z * 2.0f * std::tan(cam.fovY * 0.5f) / float(kH);
+ const float radius = o.radiusPx * pxWorld;
+ glm::vec3 nsum(0.0f);
+ for (int k = 0; k < 8; ++k) { // ring at half the radius: the area normal as the solver's averages it
+ const float a0 = 6.2831853f * k / 8, a1 = 6.2831853f * (k + 1) / 8, rr = 0.5f * o.radiusPx;
+ auto [p0, h0] = viewAt(x + rr * std::cos(a0), y + rr * std::sin(a0));
+ auto [p1, h1] = viewAt(x + rr * std::cos(a1), y + rr * std::sin(a1));
+ if (h0 && h1) nsum += glm::cross(p0 - c, p1 - c);
+ }
+ glm::vec3 n = glm::length(nsum) > 0 ? glm::normalize(nsum) : glm::vec3(0, 0, 1);
+ if (glm::dot(n, c) > 0) n = -n;
+ dabs.push_back({c, n, radius});
+ }
+ // Optimistic: each dab one pass over its rectangle (all dabs so far evaluated), timed GPU-side by Finish.
+ gl::BindFramebuffer(GL_READ_FRAMEBUFFER, canvas.fbo);
+ gl::BindFramebuffer(GL_DRAW_FRAMEBUFFER, out.fbo);
+ gl::BlitFramebuffer(0, 0, kW, kH, 0, 0, kW, kH, GL_COLOR_BUFFER_BIT, GL_NEAREST);
+ gl::UseProgram(prog);
+ gl::BindVertexArray(vao);
+ gl::Uniform1i(gl::GetUniformLocation(prog, "uColor"), 0);
+ gl::Uniform1i(gl::GetUniformLocation(prog, "uDepth"), 1);
+ gl::Uniform1i(gl::GetUniformLocation(prog, "uMatcapTex"), 2);
+ gl::UniformMatrix4fv(gl::GetUniformLocation(prog, "uInvProj"), 1, GL_FALSE, glm::value_ptr(invProj));
+ gl::UniformMatrix4fv(gl::GetUniformLocation(prog, "uProj"), 1, GL_FALSE, glm::value_ptr(proj));
+ gl::Uniform2f(gl::GetUniformLocation(prog, "uProjScale"), proj[0][0], proj[1][1]);
+ gl::Uniform2f(gl::GetUniformLocation(prog, "uSize"), float(kW), float(kH));
+ gl::ActiveTexture(GL_TEXTURE0 + 1);
+ gl::BindTexture(GL_TEXTURE_2D, canvas.depth);
+ gl::ActiveTexture(GL_TEXTURE0 + 2);
+ gl::BindTexture(GL_TEXTURE_2D, renderer.matcapTexture(rs.matcap));
+ gl::ActiveTexture(GL_TEXTURE0);
+ gl::BindTexture(GL_TEXTURE_2D, canvas.color); // (each pass re-shades its rectangle from the drawn canvas, all dabs so far)
+ gl::TexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GLint(GL_LINEAR));
+ gl::TexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GLint(GL_LINEAR));
+ std::vector<glm::vec4> uc, un;
+ std::vector<double> passMs;
+ const auto all0 = Clock::now();
+ gl::Enable(GL_SCISSOR_TEST);
+ for (size_t i = 0; i < dabs.size(); ++i) {
+ uc.push_back(glm::vec4(dabs[i].cView, dabs[i].radius));
+ un.push_back(glm::vec4(dabs[i].nView, 0.5f * dabs[i].radius * 0.06f));
+ gl::Finish();
+ const auto t = Clock::now();
+ gl::Uniform1i(gl::GetUniformLocation(prog, "uCount"), GLint(uc.size()));
+ gl::Uniform4fv(gl::GetUniformLocation(prog, "uDabC"), GLsizei(uc.size()), glm::value_ptr(uc[0]));
+ gl::Uniform4fv(gl::GetUniformLocation(prog, "uDabN"), GLsizei(un.size()), glm::value_ptr(un[0]));
+ // The dab's screen rectangle (its radius projected at its depth, plus a margin).
+ const glm::vec4 cc = proj * glm::vec4(dabs[i].cView, 1.0f);
+ const float sx = (cc.x / cc.w * 0.5f + 0.5f) * kW, sy = (cc.y / cc.w * 0.5f + 0.5f) * kH;
+ const int rp = int(std::ceil(o.radiusPx * 1.5f)) + 2; // (the surface may grow past the radius)
+ gl::BindFramebuffer(GL_FRAMEBUFFER, out.fbo);
+ gl::Viewport(0, 0, kW, kH);
+ gl::Scissor(int(sx) - rp, int(sy) - rp, 2 * rp, 2 * rp);
+ gl::DrawArrays(GL_TRIANGLES, 0, 3);
+ gl::Finish();
+ passMs.push_back(msSince(t));
+ }
+ gl::Disable(GL_SCISSOR_TEST);
+ const double allMs = msSince(all0);
+ gl::UseProgram(0);
+ const std::vector<uint8_t> optimistic = readColor(out);
++ // The geometry preview (render/Ghost.h, Background Preview): the same dabs moved in the vertex shader. Its
++ // cost is the frame with it less the frame without (median of 5 each).
++ GhostStroke ghost;
++ ghost.kind = GhostKind::Standard;
++ for (const Dab& d : dabs) {
++ GhostDab g;
++ g.center = glm::vec3(invView * glm::vec4(d.cView, 1.0f));
++ g.normal = glm::normalize(glm::vec3(invView * glm::vec4(d.nView, 0.0f)));
++ g.areaCenter = g.center;
++ g.radius = d.radius;
++ g.strength = 0.5f;
++ ghost.dabs.push_back(g);
++ }
++ auto frameMs = [&](int repeats) {
++ std::vector<double> t;
++ for (int k = 0; k < repeats; ++k) {
++ gl::BindFramebuffer(GL_FRAMEBUFFER, canvas.fbo);
++ gl::Viewport(0, 0, kW, kH);
++ gl::Finish();
++ const auto t0 = Clock::now();
++ renderer.draw(cam, kW, kH, rs);
++ gl::Finish();
++ t.push_back(msSince(t0));
++ }
++ return median(t);
++ };
++ const double plainMs = frameMs(5);
++ renderer.setGhost(1, ghost);
++ const double ghostFrameMs = frameMs(5);
++ const std::vector<uint8_t> ghostImage = readColor(canvas);
++ renderer.setGhost(1, GhostStroke());
+ // Truth: the same dabs by the Standard brush on the mesh (world space), then drawn.
+ Sculptor& sc = doc.sculptor;
+ Symmetry sym;
+ sym.x = false;
+ const auto s0 = Clock::now();
+ sc.beginStroke(m, "Standard");
+ for (const Dab& d : dabs) {
+ DabParams p;
+ p.center = glm::vec3(invView * glm::vec4(d.cView, 1.0f));
+ p.viewDir = glm::normalize(glm::vec3(invView * glm::vec4(d.cView, 0.0f)));
+ p.radius = d.radius;
+ p.strength = 0.5f;
+ sc.dab(m, doc.bvh, BrushType::Standard, p, sym);
+ }
+ sc.endStroke();
+ renderer.syncScene(scene);
+ gl::Finish();
+ const double solveMs = msSince(s0);
+ gl::BindFramebuffer(GL_FRAMEBUFFER, canvas.fbo);
+ gl::Viewport(0, 0, kW, kH);
+ renderer.draw(cam, kW, kH, rs);
+ gl::Finish();
+ const std::vector<uint8_t> truth = readColor(canvas);
+ std::vector<float> depthAfter(depth.size());
+ gl::BindFramebuffer(GL_FRAMEBUFFER, canvas.fbo);
+ gl::ReadPixels(0, 0, kW, kH, kDepthComponent, GL_FLOAT, depthAfter.data());
+ gl::BindFramebuffer(GL_FRAMEBUFFER, 0);
+ // Interior: surface before and after; outline: the stroke changed what covers the pixel (a re-shade can't).
+ std::vector<uint8_t> interior(depth.size()), outline(depth.size());
+ for (size_t i = 0; i < depth.size(); ++i) {
+ const bool a = depth[i] < 1.0f, b = depthAfter[i] < 1.0f;
+ interior[i] = a && b;
+ outline[i] = a != b;
+ }
+ const Diff pop = diff(optimistic, truth, before, &interior), none = diff(before, truth, before, &interior);
+ const Diff popEdge = diff(optimistic, truth, before, &outline), noneEdge = diff(before, truth, before, &outline);
++ const Diff ghostPop = diff(ghostImage, truth, before, &interior), ghostEdge = diff(ghostImage, truth, before, &outline);
+ char row[512];
+ std::snprintf(row, sizeof row, "| %.1fM | %.2f / %.2f ms | %.1f ms | %.0f ms | %.1f / %.0f, %.1f%% | %.1f / %.0f, %.1f%% | %zu | %zu: %.1f vs %.1f |\n",
+ double(m.triangleCount()) / 1e6, median(passMs), *std::max_element(passMs.begin(), passMs.end()), allMs,
+ solveMs, pop.mean, pop.p99, pop.over8 * 100, none.mean, none.p99, none.over8 * 100, none.pixels, popEdge.pixels, popEdge.mean, noneEdge.mean);
+ md << row;
+ std::fprintf(stderr, "%s", row);
++ char grow[256];
++ std::snprintf(grow, sizeof grow, "| %.1fM | %.2f ms (frame %.2f vs %.2f) | %.1f / %.0f, %.1f%% | %.1f |\n", double(m.triangleCount()) / 1e6,
++ ghostFrameMs - plainMs, ghostFrameMs, plainMs, ghostPop.mean, ghostPop.p99, ghostPop.over8 * 100, ghostEdge.mean);
++ ghostRows += grow;
+ if (!o.shotsDir.empty()) {
+ std::error_code ec;
+ std::filesystem::create_directories(o.shotsDir, ec);
+ char tag[32];
+ std::snprintf(tag, sizeof tag, "%gm", sizeM);
+ savePng(before, o.shotsDir + "/n1-" + tag + "-before.png");
+ savePng(optimistic, o.shotsDir + "/n1-" + tag + "-optimistic.png");
+ savePng(truth, o.shotsDir + "/n1-" + tag + "-truth.png");
+ std::vector<uint8_t> heat(truth.size(), 255); // |optimistic - truth| x 4, red on white
+ for (size_t i = 0; i < truth.size(); i += 4) {
+ int dmax = 0;
+ for (int k = 0; k < 3; ++k) dmax = std::max(dmax, std::abs(int(optimistic[i + k]) - int(truth[i + k])));
+ const uint8_t v = uint8_t(255 - std::min(255, dmax * 4));
+ heat[i + 1] = heat[i + 2] = v;
+ }
+ savePng(heat, o.shotsDir + "/n1-" + tag + "-pop.png");
++ savePng(ghostImage, o.shotsDir + "/n1-" + tag + "-ghost.png");
+ }
+ canvas.release();
+ out.release();
+ renderer.syncScene({});
+ }
++ md << "\nThe geometry preview (Background Preview's ghost) on the same 30 dabs:\n\n| Mesh | extra cost on a frame "
++ "(frame with / without) | interior pop vs truth (mean / p99, > 8) | outline pop (mean) |\n|---|---:|---:|---:|\n"
++ << ghostRows;
+ md << "\nPass: one GPU pass over the dab's rectangle evaluating every dab so far (its cost is the brush's pixels, not "
+ "the mesh). Mesh: the Standard brush on the CPU plus the upload, i.e. what the optimistic canvas hides. Pop: "
+ "per-pixel max channel difference over the pixels the stroke changed in either image.\n";
+ if (prog) gl::DeleteProgram(prog);
+ if (vao) gl::DeleteVertexArrays(1, &vao);
+ renderer.shutdown();
+ SDL_GL_DestroyContext(context);
+ SDL_DestroyWindow(window);
+ SDL_Quit();
+ if (o.outPath.empty()) std::printf("%s", md.str().c_str());
+ else std::ofstream(o.outPath) << md.str();
+ return code;
+}
+
+} // namespace sf
diff --cc src/app/ProofMode.cpp
index 9b666e24,1be2915e..eb14b07e
--- a/src/app/ProofMode.cpp
+++ b/src/app/ProofMode.cpp
@@@ -382,8 -367,6 +382,9 @@@ struct PhaseResult
size_t dabs = 0, samples = 0;
std::vector<double> frameMs, lagMs, lagPx;
std::vector<double> previewLagPx; // the predictive preview's head behind the pointer (the surface's without it)
+ std::vector<double> drawn; // triangles each frame drew (Renderer::lastDrawnTriangles)
+ std::vector<double> gpuMs; // GPU time of the phase's frames (GL_TIME_ELAPSED; empty without timer queries)
++ size_t screenStrokeFrames = 0; // frames the view showed pending dabs on the screen (render/ScreenStroke.h)
std::vector<double> split[6]; // each frame by part (App::frameSplitMs_, the frame before: the swap comes after)
};
@@@ -893,9 -860,6 +894,10 @@@ void App::proofBeforeSwap(int fbW, int
if (ph.frameMs.size() < 1000000 && now - p.stageStart > 0.0) {
ph.frameMs.push_back(frameMs);
for (int k = 0; k < 6; ++k) ph.split[k].push_back(frameSplitMs_[k]);
+ ph.drawn.push_back(double(renderer_.lastDrawnTriangles()));
++ ph.screenStrokeFrames += renderer_.screenStrokeDrawn() ? 1 : 0;
+ ph.gpuMs.insert(ph.gpuMs.end(), proofGpuMs_.begin(), proofGpuMs_.end());
+ proofGpuMs_.clear();
}
const double u = std::min(1.0, (now - p.stageStart) / spec.seconds);
if (spec.radiusPx <= 0) { // orbit: the view turns, as a drag would
@@@ -1053,12 -1012,6 +1055,13 @@@
const char* names[6] = {"events", "sculpt", "ui", "upload", "draw", "swap_wait"};
for (int k = 0; k < 6; ++k) split.set(names[k], percentilesJson(percentiles(ph.split[k])));
j.set("frame_split_ms", split);
+ j.set("triangles_drawn", percentilesJson(percentiles(ph.drawn)));
+ if (!ph.gpuMs.empty()) { // (the GPU's own work, no compositor; fewer than "frames": results that came too late)
+ j.set("gpu_ms", percentilesJson(percentiles(ph.gpuMs)));
+ j.set("gpu_frames", double(ph.gpuMs.size()));
+ }
+ j.set("render_triangle_budget", double(renderTriangleBudget()));
++ if (ph.screenStrokeFrames) j.set("screen_stroke_frames", double(ph.screenStrokeFrames));
}
if (ph.radiusPx > 0) {
if (!ph.lagMs.empty()) { // (Move drags the surface without dabs: no stroke to trail the pointer)
diff --cc src/render/Renderer.cpp
index ad315305,4f8df250..e5f60a5c
--- a/src/render/Renderer.cpp
+++ b/src/render/Renderer.cpp
@@@ -1102,7 -1101,12 +1109,13 @@@ size_t Renderer::gpuBytes() const
}
void Renderer::shutdown() {
++ screenPass_.release();
for (auto& s : slots_) freeSlot(s);
+ for (Staging& st : persist_) {
+ if (st.fence) gl::DeleteSync(st.fence);
+ if (st.buffer) gl::DeleteBuffers(1, &st.buffer); // (unmaps it)
+ st = Staging();
+ }
slots_.clear();
drawList_.clear();
if (!matcapTextures_.empty()) gl::DeleteTextures(GLsizei(matcapTextures_.size()), matcapTextures_.data());
@@@ -2633,7 -2637,7 +2646,10 @@@ int Renderer::drawView(const Camera& ca
}
}
while (samples > 1 && !viewTarget(width, height, samples)) samples /= 2;
-- if (samples <= 1) {
++ screenStrokeDrawn_ = false;
++ // A screen stroke needs the view in a target it can read back: through the single-sample one when no AA.
++ const bool screen = !screenStroke_.dabs.empty() && settings.matcap >= 0 && !settings.pbr();
++ if (samples <= 1 && !(screen && viewTarget(width, height, 1))) {
gl::BindFramebuffer(GL_FRAMEBUFFER, 0);
draw(camera, width, height, settings, viewport);
return 1;
@@@ -2645,6 -2649,6 +2661,10 @@@
gl::BindFramebuffer(GL_READ_FRAMEBUFFER, viewFbo_); // resolve: same format and size on both sides
gl::BindFramebuffer(GL_DRAW_FRAMEBUFFER, viewResolveFbo_);
gl::BlitFramebuffer(0, 0, width, height, 0, 0, width, height, GL_COLOR_BUFFER_BIT, GL_NEAREST);
++ if (screen)
++ screenStrokeDrawn_ = screenPass_.apply(screenStroke_, viewFbo_, viewResolveFbo_, width, height, frameView_, frameProj_,
++ frameViewport_, matcapTexture(settings.matcap),
++ lightRotation(settings.lightYaw, settings.lightPitch));
gl::BindFramebuffer(GL_READ_FRAMEBUFFER, viewResolveFbo_); // single-sample blit: may convert to the window's format
gl::BindFramebuffer(GL_DRAW_FRAMEBUFFER, 0);
gl::BlitFramebuffer(0, 0, width, height, 0, 0, width, height, GL_COLOR_BUFFER_BIT, GL_NEAREST);
diff --cc src/render/Renderer.h
index dc77a452,8ef00aa0..01555dc5
--- a/src/render/Renderer.h
+++ b/src/render/Renderer.h
@@@ -11,6 -11,6 +11,7 @@@
#include "render/Clusters.h"
#include "render/GL.h"
#include "render/Ghost.h"
++#include "render/ScreenStroke.h"
#include <cstdint>
#include <functional>
@@@ -178,6 -178,6 +179,11 @@@ public
// --- Strokes on heavy meshes (app/AsyncStroke.cpp) ---
// The predictive stroke preview (render/Ghost.h) drawn on SubTool `id`; an empty stroke turns it off.
void setGhost(uint32_t id, const GhostStroke& ghost);
++ // Research (render/ScreenStroke.h, SF_SCREEN_STROKE=1): the same pending dabs applied to the drawn view instead
++ // of the geometry (Lit Sphere views through drawView only); an empty stroke turns it off.
++ void setScreenStroke(const GhostStroke& stroke) { screenStroke_ = stroke; }
++ // The last drawView applied the screen stroke.
++ bool screenStrokeDrawn() const { return screenStrokeDrawn_; }
// A sculpt stroke's vertex upload made in two halves: prepareStrokeUpload packs what the mesh marked dirty
// (positions and normals only) and the culling bounds of the clusters that moved, on any thread and without
// GL, while the GL thread keeps drawing from what it has; commitStrokeUpload sends it on the GL thread.
@@@ -379,6 -396,6 +404,9 @@@ private
uint32_t ghostId_ = 0;
struct MeshProgram;
void setGhostUniforms(const MeshProgram& p);
++ GhostStroke screenStroke_;
++ ScreenStroke screenPass_;
++ bool screenStrokeDrawn_ = false;
void syncNormalMap(MeshSlot& s, const Mesh& mesh, const NormalMapView* normalMap);
// `indicesDone`: the index buffer and drawCount are already written (a full upload writes them while
// building the layout).
diff --cc src/render/ScreenStroke.cpp
index 00000000,00000000..eeb567d9
new file mode 100644
--- /dev/null
+++ b/src/render/ScreenStroke.cpp
@@@ -1,0 -1,0 +1,285 @@@
++// SculptForge - open source digital sculpting
++// SPDX-License-Identifier: GPL-3.0-or-later
++#include "render/ScreenStroke.h"
++
++#include <glm/gtc/type_ptr.hpp>
++
++#include <algorithm>
++#include <cmath>
++#include <string>
++#include <vector>
++
++namespace sf {
++
++namespace {
++
++constexpr GLenum kDepthComponent = 0x1902;
++constexpr GLbitfield kDepthBit = 0x00000100;
++
++const char* kVS = R"(#version 330 core
++void main() {
++ vec2 p = vec2((gl_VertexID << 1) & 2, gl_VertexID & 2);
++ gl_Position = vec4(p * 2.0 - 1.0, 0.0, 1.0);
++}
++)";
++
++// Keep the kernel in step with ghostMove (render/Ghost.cpp, Standard) and the shading with the mesh shader's Lit
++// Sphere branch (Renderer.cpp); tools/optimistic bench: app/OptimisticBench.cpp.
++const char* kFS = R"(#version 330 core
++uniform sampler2D uColor, uDepth, uMatcapTex;
++uniform mat4 uInvProj, uProj;
++uniform mat3 uLightRot;
++uniform vec4 uViewport; // x, y, w, h in target pixels
++uniform vec2 uProjScale, uSize;
++uniform float uFocal;
++uniform int uCount;
++uniform int uKind; // 1 Standard, 2 Clay (GhostKind order is not used: the shader's own)
++uniform vec4 uDabC[64]; // view-space centre, radius
++uniform vec4 uDabN[64]; // view-space area normal, signed strength (strength, negative inverted)
++uniform vec4 uDabA[64]; // view-space area centre, weight
++out vec4 fragColor;
++bool surface(ivec2 p) { return texelFetch(uDepth, clamp(p, ivec2(0), ivec2(uSize) - 1), 0).r < 1.0; }
++vec3 viewPos(ivec2 p) {
++ p = clamp(p, ivec2(0), ivec2(uSize) - 1);
++ float d = texelFetch(uDepth, p, 0).r;
++ vec2 ndc = (vec2(p) + 0.5 - uViewport.xy) / uViewport.zw * 2.0 - 1.0;
++ vec4 q = uInvProj * vec4(ndc, d * 2.0 - 1.0, 1.0);
++ return q.xyz / q.w;
++}
++vec2 toPixel(vec3 P) {
++ vec4 c = uProj * vec4(P, 1.0);
++ return uViewport.xy + (c.xy / c.w * 0.5 + 0.5) * uViewport.zw - 0.5;
++}
++float falloff(float dist, float rad) {
++ float t = clamp(1.0 - dist / rad, 0.0, 1.0);
++ if (uFocal != 0.0) t = pow(t, exp2(2.0 * clamp(uFocal, -1.0, 1.0)));
++ return t * t * (3.0 - 2.0 * t);
++}
++// How far dab i moves P along its area normal (ghostMove's Standard and Clay).
++float amount(int i, vec3 P) {
++ float dist = length(P - uDabC[i].xyz), rad = uDabC[i].w;
++ if (dist >= rad) return 0.0;
++ float f = falloff(dist, rad) * uDabA[i].w, s = uDabN[i].w;
++ if (uKind == 1) return s * rad * 0.06 * f;
++ float h = dot(P - (uDabA[i].xyz + uDabN[i].xyz * (rad * 0.05 * s)), uDabN[i].xyz); // Clay: up to its plane
++ return (s > 0.0 ? h < 0.0 : h > 0.0) ? -h * f : 0.0;
++}
++// The dabs' displacement of P, and (bend) the tangential gradient of each move that bends the normal n.
++vec3 displace(vec3 P, vec3 n, bool bend, out vec3 g) {
++ vec3 m = vec3(0.0);
++ g = vec3(0.0);
++ vec3 t1 = normalize(abs(n.x) < 0.9 ? cross(n, vec3(1.0, 0.0, 0.0)) : cross(n, vec3(0.0, 1.0, 0.0))), t2 = cross(n, t1);
++ for (int i = 0; i < uCount; ++i) {
++ if (distance(P, uDabC[i].xyz) >= uDabC[i].w) continue;
++ m += uDabN[i].xyz * amount(i, P);
++ if (bend) {
++ float e = uDabC[i].w * 2e-3;
++ vec3 grad = t1 * (amount(i, P + t1 * e) - amount(i, P - t1 * e)) / (2.0 * e) +
++ t2 * (amount(i, P + t2 * e) - amount(i, P - t2 * e)) / (2.0 * e);
++ g += grad * dot(uDabN[i].xyz, n);
++ }
++ }
++ return m;
++}
++// The surface normal from depth, smoothed over baselines of 1-3 pixels (the view holds facets, the mesh shader
++// interpolates vertex normals), each pair skipped across a depth jump.
++vec3 normalAt(ivec2 p) {
++ vec3 P = viewPos(p), sum = vec3(0.0);
++ for (int k = 1; k <= 3; ++k) {
++ vec3 l = viewPos(p - ivec2(k, 0)), r = viewPos(p + ivec2(k, 0)), d = viewPos(p - ivec2(0, k)), u = viewPos(p + ivec2(0, k));
++ float jump = 0.05 * abs(P.z);
++ if (abs(r.z - l.z) > jump || abs(u.z - d.z) > jump) continue;
++ sum += cross(r - l, u - d);
++ }
++ if (dot(sum, sum) < 1e-30) {
++ vec3 l = viewPos(p - ivec2(1, 0)), r = viewPos(p + ivec2(1, 0)), d = viewPos(p - ivec2(0, 1)), u = viewPos(p + ivec2(0, 1));
++ sum = cross(abs(r.z - P.z) < abs(P.z - l.z) ? r - P : P - l, abs(u.z - P.z) < abs(P.z - d.z) ? u - P : P - d);
++ }
++ vec3 n = normalize(sum);
++ return dot(n, P) > 0.0 ? -n : n;
++}
++vec3 lit(vec3 n, vec3 v) {
++ vec3 bx = normalize(vec3(v.z, 0.0, -v.x));
++ vec3 by = cross(v, bx);
++ vec3 ln = transpose(uLightRot) * n;
++ vec2 uv = vec2(dot(bx, ln), dot(by, ln)) * 0.495 + 0.5;
++ return pow(texture(uMatcapTex, uv).rgb, vec3(2.2));
++}
++void main() {
++ vec2 p = gl_FragCoord.xy - 0.5;
++ ivec2 ip = ivec2(p);
++ // Inverse warp: the drawn pixel q whose displaced surface point lands on p (fixed point q = p - offset(q)), from
++ // p and from points towards the nearest dab (where the surface grows over the background); the closest landing.
++ vec2 toward = vec2(0.0);
++ float near = 1e30;
++ for (int i = 0; i < uCount; ++i) {
++ vec2 c = toPixel(uDabC[i].xyz);
++ if (distance(c, p) < near) near = distance(c, p), toward = c - p;
++ }
++ vec2 best = vec2(-1.0);
++ float bestErr = 4.0;
++ vec3 g;
++ for (int s = 0; s < 4 && bestErr > 0.04; ++s) {
++ vec2 q = p + toward * (0.12 * float(s));
++ for (int k = 0; k < 16; ++k) {
++ ivec2 iq = ivec2(floor(q + 0.5));
++ if (!surface(iq)) break;
++ vec3 P = viewPos(iq);
++ vec2 err = toPixel(P + displace(P, vec3(0.0), false, g)) - p;
++ float e = dot(err, err);
++ if (e < bestErr) bestErr = e, best = q - err;
++ if (e < 0.04) break;
++ q -= err * (k < 8 ? 1.0 : 0.5);
++ }
++ }
++ if (best.x < 0.0) {
++ if (!surface(ip)) discard; // background stays as drawn
++ best = p;
++ }
++ ivec2 iq = ivec2(floor(best + 0.5));
++ vec3 n0 = normalAt(iq);
++ displace(viewPos(iq), n0, true, g);
++ vec3 n1 = normalize(n0 - g);
++ vec2 ndc = (gl_FragCoord.xy - uViewport.xy) / uViewport.zw * 2.0 - 1.0;
++ vec3 v = normalize(vec3(-ndc / uProjScale, 1.0)); // the mesh shader's viewRay
++ vec3 ratio = lit(n1, v) / max(lit(n0, v), vec3(1e-3));
++ vec4 c = texture(uColor, (best + 0.5) / uSize);
++ fragColor = vec4(pow(pow(c.rgb, vec3(2.2)) * ratio, vec3(1.0 / 2.2)), 1.0);
++}
++)";
++
++GLuint compile(GLenum type, const char* src) {
++ GLuint s = gl::CreateShader(type);
++ gl::ShaderSource(s, 1, &src, nullptr);
++ gl::CompileShader(s);
++ return s;
++}
++
++} // namespace
++
++ScreenStroke::~ScreenStroke() = default; // (GL objects go in release(), with the context current)
++
++void ScreenStroke::release() {
++ if (prog_) gl::DeleteProgram(prog_);
++ if (vao_) gl::DeleteVertexArrays(1, &vao_);
++ if (fbo_) gl::DeleteFramebuffers(1, &fbo_);
++ if (color_) gl::DeleteTextures(1, &color_);
++ if (depth_) gl::DeleteTextures(1, &depth_);
++ prog_ = vao_ = fbo_ = color_ = depth_ = 0;
++ w_ = h_ = 0;
++}
++
++bool ScreenStroke::ensure(int width, int height) {
++ if (failed_) return false;
++ if (!prog_) {
++ GLuint vs = compile(GL_VERTEX_SHADER, kVS), fs = compile(GL_FRAGMENT_SHADER, kFS);
++ prog_ = gl::CreateProgram();
++ gl::AttachShader(prog_, vs);
++ gl::AttachShader(prog_, fs);
++ gl::LinkProgram(prog_);
++ GLint ok = 0;
++ gl::GetProgramiv(prog_, GL_LINK_STATUS, &ok);
++ gl::DeleteShader(vs);
++ gl::DeleteShader(fs);
++ if (!ok) {
++ failed_ = true;
++ return false;
++ }
++ gl::GenVertexArrays(1, &vao_);
++ }
++ if (fbo_ && width == w_ && height == h_) return true;
++ if (fbo_) {
++ gl::DeleteFramebuffers(1, &fbo_);
++ gl::DeleteTextures(1, &color_);
++ gl::DeleteTextures(1, &depth_);
++ }
++ gl::GenTextures(1, &color_);
++ gl::BindTexture(GL_TEXTURE_2D, color_);
++ gl::TexImage2D(GL_TEXTURE_2D, 0, GLint(GL_RGBA8), width, height, 0, GL_RGBA, GL_UNSIGNED_BYTE, nullptr);
++ gl::TexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GLint(GL_LINEAR));
++ gl::TexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GLint(GL_LINEAR));
++ gl::TexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GLint(GL_CLAMP_TO_EDGE));
++ gl::GenTextures(1, &depth_);
++ gl::BindTexture(GL_TEXTURE_2D, depth_);
++ gl::TexImage2D(GL_TEXTURE_2D, 0, GLint(GL_DEPTH_COMPONENT24), width, height, 0, kDepthComponent, GL_FLOAT, nullptr);
++ gl::TexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GLint(GL_NEAREST));
++ gl::TexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GLint(GL_NEAREST));
++ gl::BindTexture(GL_TEXTURE_2D, 0);
++ gl::GenFramebuffers(1, &fbo_);
++ gl::BindFramebuffer(GL_FRAMEBUFFER, fbo_);
++ gl::FramebufferTexture2D(GL_FRAMEBUFFER, GL_COLOR_ATTACHMENT0, GL_TEXTURE_2D, color_, 0);
++ gl::FramebufferTexture2D(GL_FRAMEBUFFER, GL_DEPTH_ATTACHMENT, GL_TEXTURE_2D, depth_, 0);
++ const bool ok = gl::CheckFramebufferStatus(GL_FRAMEBUFFER) == GL_FRAMEBUFFER_COMPLETE;
++ gl::BindFramebuffer(GL_FRAMEBUFFER, 0);
++ w_ = width, h_ = height;
++ if (!ok) failed_ = true;
++ return ok;
++}
++
++bool ScreenStroke::apply(const GhostStroke& g, GLuint drawFbo, GLuint resolveFbo, int width, int height, const glm::mat4& view,
++ const glm::mat4& proj, const glm::vec4& viewport, GLuint matcap, const glm::mat3& lightRot) {
++ if (!supports(g) || !matcap || !ensure(width, height)) return false;
++ // The pass's inputs: the resolved colour and the view's depth (a multisample depth resolves by nearest sample).
++ gl::BindFramebuffer(GL_READ_FRAMEBUFFER, resolveFbo);
++ gl::BindFramebuffer(GL_DRAW_FRAMEBUFFER, fbo_);
++ gl::BlitFramebuffer(0, 0, width, height, 0, 0, width, height, GL_COLOR_BUFFER_BIT, GL_NEAREST);
++ gl::BindFramebuffer(GL_READ_FRAMEBUFFER, drawFbo);
++ gl::BlitFramebuffer(0, 0, width, height, 0, 0, width, height, kDepthBit, GL_NEAREST);
++ // The dabs in view space, and the screen rectangle they reach (grown: the surface may move past the radius).
++ std::vector<glm::vec4> c, n, a;
++ float x0 = 1e30f, y0 = 1e30f, x1 = -1e30f, y1 = -1e30f;
++ const float sign = g.invert ? -1.0f : 1.0f;
++ for (const GhostDab& d : g.dabs) {
++ if (c.size() >= 64) break;
++ const glm::vec3 cv = glm::vec3(view * glm::vec4(d.center, 1.0f));
++ const glm::vec3 nv = glm::normalize(glm::mat3(view) * d.normal);
++ c.emplace_back(cv, d.radius);
++ n.emplace_back(nv, sign * d.strength);
++ a.emplace_back(glm::vec3(view * glm::vec4(d.areaCenter, 1.0f)), d.weight);
++ const glm::vec4 cc = proj * glm::vec4(cv, 1.0f);
++ if (cc.w <= 0.0f) continue;
++ const float sx = viewport.x + (cc.x / cc.w * 0.5f + 0.5f) * viewport.z, sy = viewport.y + (cc.y / cc.w * 0.5f + 0.5f) * viewport.w;
++ const float rp = 1.5f * d.radius * proj[1][1] / cc.w * 0.5f * viewport.w + 2.0f;
++ x0 = std::min(x0, sx - rp), y0 = std::min(y0, sy - rp), x1 = std::max(x1, sx + rp), y1 = std::max(y1, sy + rp);
++ }
++ if (c.empty() || x1 <= x0) return false;
++ gl::BindFramebuffer(GL_FRAMEBUFFER, resolveFbo);
++ gl::Viewport(0, 0, width, height);
++ gl::Enable(GL_SCISSOR_TEST);
++ const int sx0 = std::max(0, int(x0)), sy0 = std::max(0, int(y0));
++ gl::Scissor(sx0, sy0, std::min(width, int(x1) + 1) - sx0, std::min(height, int(y1) + 1) - sy0);
++ gl::Disable(GL_DEPTH_TEST);
++ gl::UseProgram(prog_);
++ auto at = [&](const char* name) { return gl::GetUniformLocation(prog_, name); };
++ gl::Uniform1i(at("uColor"), 0);
++ gl::Uniform1i(at("uDepth"), 1);
++ gl::Uniform1i(at("uMatcapTex"), 2);
++ const glm::mat4 invProj = glm::inverse(proj);
++ gl::UniformMatrix4fv(at("uInvProj"), 1, GL_FALSE, glm::value_ptr(invProj));
++ gl::UniformMatrix4fv(at("uProj"), 1, GL_FALSE, glm::value_ptr(proj));
++ gl::UniformMatrix3fv(at("uLightRot"), 1, GL_FALSE, glm::value_ptr(lightRot));
++ gl::Uniform4fv(at("uViewport"), 1, glm::value_ptr(viewport));
++ gl::Uniform2f(at("uProjScale"), proj[0][0], proj[1][1]);
++ gl::Uniform2f(at("uSize"), float(width), float(height));
++ gl::Uniform1f(at("uFocal"), g.focal);
++ gl::Uniform1i(at("uCount"), GLint(c.size()));
++ gl::Uniform4fv(at("uDabC"), GLsizei(c.size()), glm::value_ptr(c[0]));
++ gl::Uniform4fv(at("uDabN"), GLsizei(n.size()), glm::value_ptr(n[0]));
++ gl::Uniform4fv(at("uDabA"), GLsizei(a.size()), glm::value_ptr(a[0]));
++ gl::Uniform1i(at("uKind"), g.kind == GhostKind::Clay ? 2 : 1);
++ gl::ActiveTexture(GL_TEXTURE0 + 2);
++ gl::BindTexture(GL_TEXTURE_2D, matcap);
++ gl::ActiveTexture(GL_TEXTURE0 + 1);
++ gl::BindTexture(GL_TEXTURE_2D, depth_);
++ gl::ActiveTexture(GL_TEXTURE0);
++ gl::BindTexture(GL_TEXTURE_2D, color_);
++ gl::BindVertexArray(vao_);
++ gl::DrawArrays(GL_TRIANGLES, 0, 3);
++ gl::BindVertexArray(0);
++ gl::UseProgram(0);
++ gl::Disable(GL_SCISSOR_TEST);
++ gl::BindFramebuffer(GL_FRAMEBUFFER, 0);
++ return true;
++}
++
++} // namespace sf
diff --cc src/render/ScreenStroke.h
index 00000000,00000000..a5c90d44
new file mode 100644
--- /dev/null
+++ b/src/render/ScreenStroke.h
@@@ -1,0 -1,0 +1,43 @@@
++// SculptForge - open source digital sculpting
++// SPDX-License-Identifier: GPL-3.0-or-later
++//
++// Optimistic screen-space strokes (research, docs/design/core-200m.md §7b N1; SF_SCREEN_STROKE=1, off by default).
++//
++// The dabs of a stroke the solver hasn't placed yet (the same list the geometry preview draws, render/Ghost.h) are
++// applied to the drawn view instead of to the geometry: after the view is resolved, one pass over the dabs' screen
++// rectangles finds for each pixel the drawn surface point whose displaced position lands there (inverse warp over the
++// view's depth), bends its normal by the kernels' gradients and re-shades its colour by the ratio of the Lit Sphere
++// lookups at the bent and the original normal. Its cost is the brush's pixels, not the mesh. When the solver's result
++// is uploaded those dabs leave the list, so the real surface takes over. Standard and Clay for now, Lit Sphere
++// shading only; anything else draws the geometry preview as before.
++#pragma once
++
++#include "render/GL.h"
++#include "render/Ghost.h"
++
++#include <glm/glm.hpp>
++
++namespace sf {
++
++class ScreenStroke {
++public:
++ ~ScreenStroke();
++ void release();
++ // True for the strokes this pass can draw (the rest keep the geometry preview).
++ static bool supports(const GhostStroke& g) {
++ return (g.kind == GhostKind::Standard || g.kind == GhostKind::Clay) && !g.dabs.empty();
++ }
++ // Applies `g` to the resolved view `resolveFbo` (single-sample colour) using the depth of `drawFbo` (the view's
++ // target, any sample count), both `width` x `height`. `view`, `proj`, `viewport` as the frame drew them;
++ // `matcap` the Lit Sphere texture, `lightRot` the shader's uLightRot. False when it couldn't (nothing drawn).
++ bool apply(const GhostStroke& g, GLuint drawFbo, GLuint resolveFbo, int width, int height, const glm::mat4& view,
++ const glm::mat4& proj, const glm::vec4& viewport, GLuint matcap, const glm::mat3& lightRot);
++
++private:
++ bool ensure(int width, int height);
++ GLuint prog_ = 0, vao_ = 0, fbo_ = 0, color_ = 0, depth_ = 0;
++ int w_ = 0, h_ = 0;
++ bool failed_ = false;
++};
++
++} // namespace sf