Stream 4: form and light for solids
Branch form. This stream answers fresh-painter findings 5 and 10: rocks read
as "macarons, loaves, haystacks, beetles and soap bars", mountains as "weird
sea with hard edges", and painters had to build their own height fields and
shading. The engine now gives a painting program a solid to reason about.
Each point of it has planes turned toward or away from one light, a core
shadow, reflected light, cast shadows and a distance for aerial perspective.
It also gives stroke-direction fields and masks derived from that solid.
The engine still paints nothing: the rock and range motifs live in
paintings/src/rocks.rs as one painter's example.
What changed
crates/paint/src/form.rs(new)Formis a depth buffer over the canvas. Each pixel stores the nearest solid'sz(units toward the viewer), its exact normal, a part id, a facet id and a distance.Sdfdescribes 3-D bodies as signed distance functions, sphere-traced orthographically (a bareellipsoidis hit in closed form). When tracing crawls, as it does near the edge of a thin body, it continues in steps of at least 0.25 units and bisects the crossing, so running out of steps is never reported as a miss. A hit is then refined along the ray with a few Newton steps, which keeps depth accurate even where the distance estimate is poor (tested at 10:1 and 20:1 ellipsoids).- masses:
ellipsoidandblock(a rounded box whose faces are facets 1–6); - operations:
.turn(c, yaw, pitch, roll)(positive yaw brings the right side toward the viewer, positive pitch the top, so we look down on it; positive roll turns it clockwise; tested on the basis vectors; bounds come from all eight turned corners, so a pivot outside the body is safe),.cut(at, n, facet, round)(a fracture plane that becomes its own facet),.rough(amp, period, seed, ridged)(weathering, soft lumps or pitted grain),unionandsubtract.
- masses:
Ridgeis a mountain face or cliff below a crest line.- The face leans back (
lean) and flattens at the foot. - Gullies start just under the crest and follow the fall lines back to it, so they fan out from the peaks. Downhill, fine gullies merge into wider ones.
- Spurs are rounded; strata (
strata) and a base line (base: beach, valley floor) are optional.
- The face leans back (
Relieftakes any height function.Lightsets the direction and how far it comes from the viewer's side. A negativefrontis contre-jour. It also sets ambient sky light, reflected light (default: from below and the far side), penumbra, reach, occluder thickness andacross_parts(whether one part shadows another).Shadegivesturn(n·L),direct,cast,bounce,skyand a combinedvalue.lit(soft)sorts a point into the light or shadow family with a halftone band. The core shadow falls out of the model: just past the terminator, neither direct nor reflected light reaches.- Fields:
fall(gravity projected onto the plane: the way water runs);across(around the form);edge_angle(along a plane break or an overlap);bend(+ convex arris or spur, − concave joint or gully);dist,part,sample.
- Masks:
mask(|s| …), any rule over samples;silhouette(parts, |s| soft), an edge whose softness varies per point (crisp near, lost in haze, softer where the form turns away);edges(turn, step, span), plane breaks and overlaps. The turn is measured per unit of 3-D surface distance, so the limb of a rounded form isn't taken for a break.
aerial(dist, visibility)gives the aerial-perspective fraction.
crates/paint/src/mask.rs(additions)- An exact Euclidean distance transform (Felzenszwalb & Huttenlocher).
distance()(signed, units),offset,dilate,erode,rim(width, soft),band(lo, hi, soft),soften(|x, y| width)(re-edge with varying softness) and bilinearsample(x, y).
lib.rs:pub mod formand re-exports ofForm, Light, Ridge, Relief, Sdf, Shade, Solid.paintings/src/lib.rs:pub mod rocks.paintings/src/rocks.rs(new, the painter's side)- Geometry:
ground,boulder(a lumpy granite mass with five fracture planes and ridged grain),outcrop(stacked Elbe-sandstone beds with a recessed core showing in the joints) andchalk_cliff(Rügen: a near-vertical fluted face, pinnacles, flint bands, a scree foot and a farther cliff). It also hasranges(three receding ranges: rounder and finer in form the farther they are) andskyline. Stone: colors per family (light, half, shadow, core, bounce, crevice), with presets for granite, sandstone, chalk and mountain.Stone::at(&shade).Air { color, visibility }.paint_solidpaints dark planes first and lights last, in this order:- block in the whole mass in its shadow colors, thin, strokes down the planes (across on tops that face the sky);
- the shadow planes again, with core and reflected light;
- the lit planes in stiffer paint, each stroked its own way, so the breaks come out abrupt;
- a soft clean brush fuses each plane and the turning halftones, stopping at the breaks;
- dark accents along the big concave breaks (
edges×bend< 0), strokes alongedge_angle; - last, a few touches of the brightest lights.
paint_rangesworks far to near:- silhouette softness grows with aerial distance;
- a body pass runs down the fall lines, then the lit spurs, then dark strokes in the deepest gullies (near ranges only);
- a level mist veil at each foot is fused with the badger.
- Geometry:
paintings/src/bin/study_form.rs: the evidence sheet (below).--only boulder|outcrop|cliff|rangespaints one motif over the whole canvas.--grisailleshows the light model's values unpainted (a diagnostic).
API, briefly
use paint::{Form, Light, Ridge, Sdf};
use paint::form::aerial;
let mut form = Form::new(c.frame());
// a boulder: a mass, turned, weathered, then broken by fracture planes
let rock = Sdf::ellipsoid(c3, [150.0, 110.0, 120.0])
.turn(c3, 0.3, 0.1, -0.12)
.rough(17.0, 150.0, 1, false) // soft lumps
.cut(top_pt, [-0.35, -1.0, 0.45], 10, 4.0) // a sloping top: facet 10
.cut(side_pt, [1.0, -0.15, 0.3], 11, 3.0) // the flank away from the light
.rough(0.9, 25.0, 2, true); // pitted grain
let id = form.add(&rock, 0.5); // dist 0.5 (aerial perspective)
let range = Ridge::new(0.0, 1000.0, |x| crest(x), 400.0, 7)
.lean(0.9, 0.7).gullies(45.0, 0.5).base(valley_y);
let far = form.add_at(&range, &|_, _, z| 3.0 - 0.002 * z);
form.light(Light::new((-1.0, -0.7), 0.5).ambient(0.2).penumbra(0.05));
// then paint with fields from the form
let lit = form.mask(|s| if s.part == id { s.shade.lit(0.12) } else { 0.0 });
let edge = form.silhouette(&[id], |s| 0.4 + 5.0 * aerial(s.dist, 6.0).powi(2));
let hd = st.body()
.color(|x, y| form.sample(x, y).map_or(sky(x, y), |s| stone.at(&s.shade)))
.angle(|x, y| form.fall(x, y))
.clip(true);
c.work(&lit.mul(&edge), &hd, 1);
let joints = form.edges(0.8, 3.0, 2.5).mul(&Mask::from_fn(f, |x, y| smoothstep(0.3, 0.7, -form.bend(x, y, 2.5))));
Evidence
out/study_form.png(1000px sheet, ~20 s),out/study_form_full.png(3200px, ~2 min),out/study_form_gris.png(grisaille, ~4 s). The PNGs are git-ignored; regenerate withcargo paint study_form [-- --full | --grisaille].- JPEG previews in
[local path redacted]:sheet_1000.jpg,gris_final.jpg, and the 3200 cropsf_boulder.jpgandf_ranges.jpg.
What I saw, judged as a painter:
- Ranges (bottom right): the clearest win. They read as mountains lit from the left. Lit spurs alternate with shadowed gullies that fan down from the peaks. There are three layers, each paler and softer-edged in the air, with mist lying at the feet between them. There are no horizontal bands. The near range is heavy and dark, and the peaks are still a little too regular.
- Boulder (top left): a solid lit from the upper left, with a lit top plane (lichen), a light front, a dark flank and a soft cast shadow on the ground to the right. Its foot is sunk in the grass. It reads as a rock, not a loaf.
- Sandstone outcrop (top right): reads as stacked, weathered beds with dark joints, lit tops and shadowed undersides, casting shadows on the ground. It is a little too tidy and too yellow.
- Chalk cliff (bottom left): reads as a white fluted wall with a green brink over the sea, with a farther cliff beyond. The light and shadow on the face are subtle; the fluting could be stronger.
- At 3200px the big light structure holds, but the handling doesn't. Each plane is a field of uniform short dashes, and the ground specks through in the shadows (white flecks). These are fresh-painter issues 7 and 8 (coverage and "beads at 3200") showing up here. The motif passes use short strokes to follow the planes; they need longer, more varied strokes and better coverage at the edges.
Known issues and next steps
- Handling at full size: uniform dash texture and ground specks in dark passages (see above). This belongs partly to stream 2 (stroke entropy) and partly to
paint_solid's pass settings. - Cast shadows are traced in screen space over the depth buffer. Occluders more than
Light::thicknessin front are ignored, but a thin solid far in front can still shadow things far behind it. Useacross_parts(false)for distant layers. Ridgeis a bas-relief: it has no overhangs. Its fall lines are estimated from the smoothed crest, not integrated, so gullies on complex crests only roughly follow the true fall lines.- There is no hydraulic erosion. Gullies are merged fixed-scale noise, which reads well at a distance, but a close range would benefit from a real drainage network.
- Memory. Build one form per motif and drop it after painting. A
Formis always whole-canvas:Form::new(c.frame())in a--croprender is as big as in a whole one. Measured with a counting allocator on a 3200×2133 frame (3:2, 6.8 Mpx):- persistent: 28 bytes/px, 191 MB;
add/add_at: nothing extra. Hits are written row by row straight into the buffers (it used to collect a frame-sizedVec<Option<(Hit, f32)>>: peak 382 MB);light: nothing extra. Shadows are traced in place;silhouette(andMask::soften/offset/rim/distance): +17 bytes/px during the distance transform (a region bitmap, the column pass, its nearest rows, the result and the nearest-inside index; the two passes share their buffers), 307 MB peak with the form. It used to be 423 MB;- every mask the form returns: +4 bytes/px (27 MB) for as long as the painter keeps it.
- So budget ≈45 bytes/px at peak per live form, plus the masks you keep: ≈310 MB at 3200px for 3:2, ≈350 MB for 4:3 (7.7 Mpx), ≈460 MB for a 1:1 3200² canvas. That comes on top of the canvas itself and any other motif's masks.
- Pitch sign fixed (it used to tip the top away, against the documented contract).
rocks::outcropnow pitches the whole stack about its foot by 0.32 rad, so the beds show their tops as intended. Pitching each block about its own center broke the stack apart. - Next: a
Form::simplify(radius)normal blur (the painter's squint) so color fields can follow the big planes while texture is added on purpose; lit-rim helpers for contre-jour; snow and vegetation lying on up-facing planes (s.shade.sky,s.n[1]) as a documented pattern; and use the rocks in a real composition (the Cross in the Mountains rock, the Wanderer's crags). mask.rs:106(mul) andbox_rowsclippy warnings predate this stream.
Commits
fa669e7mask: signed distance (exact EDT), offset/dilate/erode, rim, band, soften, sample7ea2b63form: depth buffer of solids, Light/Shade, fields and masks; tests566e039rocks: stone and range painting passes; study_form sheet + grisaille; Ridge fixes50c3dc0rocks: plane fusing, accents only at big breaks, seated boulder, ranges lighting and mist- (final) clippy fixes, notes