Render Anything Engine: tell your AI what to make. Videos, motion graphics, 3D and games as React and TypeScript, rendered on your own GPU. Rust + Bevy, macOS, Linux and Windows.
TypeScript 3dagent-skillsai-agentsai-videobevyclaude-codegame-enginegpulinuxmacosmotion-designmotion-graphicsreactrusttypescriptvideo-editingvideo-renderingwgpuwindows
FO1-FO13: raea-sys-foliage, trees grown by species for the 1917 city (in progress: not a workspace member yet)
shinyobjectz371a406507c4
diff --git a/docs/foliage.feature b/docs/foliage.featurenew file mode 100644index 00000000..8f01d4c3--- /dev/null+++ b/docs/foliage.feature@@ -0,0 +1,120 @@+@spec+Feature: raea/foliage, plants grown from their species and drawn through the year+ Shane, 2026-11-17: "full seasonal foliage, researching native tree/plant/flower types and try to build procedural+ foliage systems, wild, overgrowth, ivy (if applicable), residential gardens or parks ... hyper realistic city wide+ procedural generation". Every season and weather is drawn (docs/wear.feature WR9; docs/realism.feature D17, LT16),+ so a plant is grown once and the year is drawn over it: leaves come, colour and fall, flowers open, snow lies on+ the branches, all from uniforms, nothing grown again per season.++ raea's plants so far are a stylized meadow (systems/grass, <Grass>), a field-made tree (raea/render grow.tree, an SDF+ solid with no leaves) and props placed round a room (raea/room plants.tsx). None knows a species, a leaf or a+ season. The method here is the literature's:+ - Trees grow by space colonization (Runions, Lane and Prusinkiewicz, "Modeling Trees with a Space Colonization+ Algorithm", 2007): attraction points fill the species' crown, and branches grow toward the points near them and+ remove them, so branches compete for space as real ones do. Branch radii follow the pipe model (a parent's+ radius to the power n is the sum of its children's).+ - Climbers grow by Luft's ivy generator (2006): a stem steps along its last direction, pulled to the nearest+ surface (adhesion), up toward light, down by gravity when it lets go, with some chance in each step.+ - Seasons follow phenology: each species' dates of leaf unfolding, flowering, colouring and leaf fall, as the+ DWD's observers record them (CC BY 4.0), sourced per place and era by the project that uses them.+ Leaves and bark are made in code (a leaf's outline, teeth, veins and blotches from its shape's rules; bark's+ fissures from noise in the shader), never photographed, so a species is a table of numbers and a seed.++ Rule: 1. Plants++ Scenario: FO1. A tree grown from its species+ Given a request: a species (FO4), a height, a crown width, a clear trunk (the height of the first limb), and a+ seed+ When raea-sys-foliage grows it+ Then a trunk rises to the crown's base, the crown's envelope (the species' profile, its widest point and its+ squareness) is filled with attraction points (denser near the surface, where light reaches), and the tree is+ grown into it by space colonization with the species' step, reach, kill distance and tropism (up for an+ ascending lime, down at the tips for a sweeping chestnut)+ And short twigs sprout from the outer shoots, so a bare tree in December shows its fine twig haze+ And radii follow the pipe model from a twig's radius at every tip, and each branch is one tube from its parent's+ surface to its tip, its sides fewer as it thins+ And the same request gives the same bytes+ And the output is one .glb with material "bark" and eight leaf groups "leaf-0" to "leaf-7" (FO3), in the+ plant's local frame: y up, metres, the origin at the foot of the trunk++ Scenario: FO2. Leaves and bark made in code+ Then each leaf kind is drawn into an atlas by rules: a blade's width along its midrib (cordate, ovate,+ lanceolate, obovate), its teeth, its lobes (palmate, oak's rounded ones) or its leaflets (palmate compound as a+ chestnut's, pinnate as a black locust's), its veins and its blotches, with sixteen variants a species+ And the atlas's channels are what the season needs, not a colour: alpha is the blade, red the veins, green the+ blotches, blue the distance to the edge (autumn colours from the edge inward)+ And each leaf is a card on a shoot, turned toward the light and out from the crown, its normal bent outward so+ the crown shades as a volume; its vertex colour holds its own random number, how exposed it is and how far+ along its shoot it is+ And bark is shaded in a surface hook: fissures from noise along the branch, the species' pattern (a plane's+ flaking patches, a birch's white with dark bands, a locust's ropes), soot, wet and snow on what faces up++ Scenario: FO3. The year on one tree+ Given the day of the year, the species' phenology and the weather+ Then leaves unfold from bud in order along each shoot, grow to full size, darken through summer, colour from+ their edges inward in the species' autumn colours (lime yellow, maple orange to red, plane brown), and fall+ in the order their random numbers give+ And a leaf group whose leaves have all fallen, or not yet come out, is hidden through its material (its base+ colour's alpha 0 with alpha mask), so its shadow goes too; a surface hook's discard can't do this, as the+ prepass and shadows draw the standard material's (systems/shader: only the main pass runs a hook)+ And flowers (a chestnut's candles, a lime's yellow clusters) and fruit come and go by the same dates+ And snow lies on the tops of branches, bark darkens when wet, and a frost whitens the twigs++ Scenario: FO4. The species+ Then each species is a row of numbers: crown profile, growth, leaf kind and size, leaves a shoot, bark, height+ to width, autumn colours, and its sources+ | species | crown | leaf |+ | lime (Tilia cordata, x europaea) | dense ovoid, ascending limbs | cordate, toothed, 6-10 cm |+ | elm (Ulmus minor, laevis) | broad, vase | ovate, lopsided base, toothed, 7-12 cm |+ | plane (Platanus x acerifolia) | broad dome, big limbs | palmate, 3-5 lobes, 12-25 cm |+ | Norway maple (Acer platanoides) | round, dense | palmate, 5-7 pointed lobes, 10-15 cm |+ | horse chestnut (Aesculus hippocastanum) | broad dome, sweeping | palmate compound, 5-7 leaflets |+ | black locust (Robinia pseudoacacia) | open, irregular | pinnate, 9-19 leaflets |+ | pedunculate oak (Quercus robur) | broad, crooked limbs | rounded lobes, 7-14 cm |+ | silver birch (Betula pendula) | narrow, weeping twigs | triangular, toothed, 3-7 cm |+ | Lombardy poplar (Populus nigra 'Italica') | column | rhombic, 5-10 cm |+ | white willow (Salix alba) | broad, hanging twigs by water | lanceolate, 5-12 cm |+ | lilac, elder (shrubs) | many stems | cordate; pinnate |++ Rule: 2. Climbers and the ground++ Scenario: FO5. Climbers grown over a model+ Given a model (a city tile or a house) and roots where a wall meets soil+ Then a climber grows over it as Luft's ivy does, clinging to walls and sills, turning at a cornice, thinning+ toward its top, and kept off the openings tenants cut it from (ASSUMED 0.3 m)+ And ivy keeps its leaves all year; wild vine colours red in autumn and is bare in winter, its stems showing++ Scenario: FO6. The ground's plants by their causes+ Then weeds grow in paving's joints and at walls' feet where feet rarely tread and it stays damp (the wear bake's+ touch, ground and sky), lawns and beds where the map says garden, vegetable rows and allotments where it says+ so, each as instanced tufts near the camera and a shaded ground beyond++ Scenario: FO7. Shrubs and wild growth+ Then shrubs grow from the same generator with many stems, and ground left alone fills by how long it was left:+ grasses and mugwort in the first year, elder and locust saplings after a few++ Rule: 3. A city++ Scenario: FO8. Wind+ Then branches and leaves sway by their order and distance from the trunk; this needs a vertex hook the surface+ shader doesn't have yet (an engine gap: docs/shaders.feature)++ Scenario: FO9. Levels of detail+ Then a tree near the camera has every leaf; farther, its leaves are cards of leaf clusters; farther still, an+ impostor; each level's triangles and bytes are measured against the frame budget (docs/realism.feature LT20)++ Scenario: FO10. `foliage.grow`, `raea foliage grow` and raea/foliage+ Then a composition grows a plant with a native call, a shell with the verb, and raea/foliage gives the leaf and+ bark hooks and a season's uniforms from a day, a species and the weather++ Scenario: FO11. A city planted from data+ Given a tree layer (points with crown widths), a register of trees with species and planting years, the streets+ and the gardens+ Then each tree takes its species from the register where an old tree stands near it, else from its street's or+ park's weights, and its size from its crown; climbers take walls by rule; the ground takes its plants by+ cause; and each tile gets a placement file of plants by kind++ Scenario: FO12. Proof+ Then one tree of each species is rendered through the year (bud, full leaf, autumn, bare, under snow) beside+ public-domain photographs of the species, and a street, a square and a court are rendered in four seasons,+ with each species' triangles, bytes and growth time printeddiff --git a/systems/foliage/Cargo.toml b/systems/foliage/Cargo.tomlnew file mode 100644index 00000000..5bcaf265--- /dev/null+++ b/systems/foliage/Cargo.toml@@ -0,0 +1,13 @@+[package]+name = "raea-sys-foliage"+version = "0.1.0"+edition = "2024"+license = "FSL-1.1-ALv2"+publish = false+description = "Plants grown from their species (space colonization, the pipe model, leaves and an atlas made in code), as .glb (docs/foliage.feature)"++[dependencies]+parry3d = "0.31"+serde_json = "1"+image = { version = "0.25", default-features = false, features = ["png"] }+raea-sys-glb = { path = "../glb" }diff --git a/systems/foliage/src/atlas.rs b/systems/foliage/src/atlas.rsnew file mode 100644index 00000000..88b2ee1b--- /dev/null+++ b/systems/foliage/src/atlas.rs@@ -0,0 +1,289 @@+//! A species' leaves drawn by rules into an atlas of CELLS x CELLS variants (docs/foliage.feature FO2). A leaf is a+//! stalk and blades: each blade has a midrib from an origin at an angle, a width along it (u^p (1-u)^q, its widest at+//! p/(p+q), so p small is a broad base and q small a broad tip), teeth (a saw along the margin), lobes (a wave that+//! cuts into the margin) and veins (secondaries leaving the midrib at an angle). Palmate leaves are several blades from+//! one point over a disc; compound and pinnate ones are leaflets on a stalk. In a cell the leaf stands on its stalk's+//! foot at the bottom middle, x across in leaf lengths (the species' aspect wide), y up from 0 to 1.+//! The channels are what the leaf hook needs, not a colour (stored in a picture the engine reads as sRGB, so the hook+//! re-encodes red, green and blue; alpha is linear):+//! alpha the blade, anti-aliased red veins+//! green blotches (two octaves of noise) blue the distance in from the edge (autumn comes from the edge)++use image::RgbaImage;++use crate::Rng;+use crate::species::{LeafKind, Species};++pub const CELLS: u32 = 4;+const CELL: u32 = 256;+/// the alpha is a signed distance to the blade's edge: 0.5 on it, 0 and 1 SPREAD/2 texels out and in, so a hook can+/// widen a leaf as its texels shrink below a pixel (no mipmaps) and a magnified edge stays sharp+pub const SPREAD: f32 = 12.0;++#[derive(Clone, Copy)]+struct Blade {+ o: [f32; 2],+ ang: f32,+ len: f32,+ w: f32,+ p: f32,+ q: f32,+ t0: f32,+ teeth: f32,+ depth: f32,+ lobes: f32,+ veins: f32,+ vein_ang: f32,+ asym: f32,+ sinus: bool,+}++const B: Blade = Blade { o: [0.0, 0.0], ang: 0.0, len: 0.8, w: 0.3, p: 0.5, q: 0.8, t0: 0.0, teeth: 0.0, depth: 0.0, lobes: 0.0, veins: 8.0, vein_ang: 0.8, asym: 0.0, sinus: false };++fn shape(u: f32, p: f32, q: f32) -> f32 {+ let m = (p / (p + q)).powf(p) * (q / (p + q)).powf(q);+ u.powf(p) * (1.0 - u).powf(q) / m+}++fn smooth(a: f32, b: f32, x: f32) -> f32 {+ let t = ((x - a) / (b - a)).clamp(0.0, 1.0);+ t * t * (3.0 - 2.0 * t)+}++impl Blade {+ /// How far inside the blade (x, y) is (leaf lengths; negative outside), and its vein strength 0-1.+ fn at(&self, x: f32, y: f32) -> (f32, f32) {+ let (dx, dy) = (x - self.o[0], y - self.o[1]);+ let (s, c) = self.ang.sin_cos();+ let along = dx * s + dy * c;+ let cross = dx * c - dy * s;+ let t = along / self.len;+ if t < self.t0 - 0.05 || t > 1.05 {+ return (-1.0, 0.0);+ }+ let u = ((t - self.t0) / (1.0 - self.t0)).clamp(0.0, 1.0);+ let side = if cross > 0.0 { 1.0 + self.asym } else { 1.0 - self.asym };+ let mut w = self.w * self.len * shape(u, self.p, self.q) * side;+ if self.lobes > 0.0 {+ w *= 0.42 + 0.58 * (std::f32::consts::PI * u * self.lobes).sin().abs().powf(0.6);+ }+ if self.teeth > 0.0 {+ w *= 1.0 - self.depth * (u * self.teeth).fract() * smooth(0.0, 0.2, u);+ }+ let mut inside = w - cross.abs();+ if self.sinus && t < 0.04 {+ inside = inside.min(cross.abs() - (0.04 - t) * self.len * 1.2);+ }+ let mid = (1.0 - cross.abs() / (self.len * 0.012 * (1.3 - u))).clamp(0.0, 1.0);+ let k = 1.0 / self.vein_ang.tan();+ let root = t - cross.abs() / self.len * k;+ let f = (root * self.veins + 0.5).fract();+ let d = f.min(1.0 - f) / self.veins * self.len * self.vein_ang.sin();+ let sec = (1.0 - d / (self.len * 0.006)).clamp(0.0, 1.0) * if cross.abs() < w * 0.9 && root > self.t0 + 0.04 { 1.0 } else { 0.0 };+ (inside, mid.max(0.65 * sec))+ }+}++/// A leaf: a stalk (from the foot to `stalk`, its half-width), blades and discs (centre, radius).+struct Leaf {+ stalk: [f32; 2],+ stalk_w: f32,+ blades: Vec<Blade>,+ discs: Vec<([f32; 2], f32)>,+}++impl Leaf {+ fn at(&self, x: f32, y: f32) -> (f32, f32) {+ let (sx, sy) = (self.stalk[0], self.stalk[1]);+ let l2 = sx * sx + sy * sy;+ let h = ((x * sx + y * sy) / l2.max(1e-6)).clamp(0.0, 1.0);+ let stalk = self.stalk_w - (x - sx * h).hypot(y - sy * h);+ let mut best = (stalk, if stalk > 0.0 { 1.0 } else { 0.0 });+ for b in &self.blades {+ let (i, v) = b.at(x, y);+ if i > best.0 {+ best = (i, if i > 0.0 { v } else { 0.0 });+ } else if i > 0.0 {+ best.1 = best.1.max(v);+ }+ }+ for &(c, r) in &self.discs {+ best.0 = best.0.max(r - (x - c[0]).hypot(y - c[1]));+ }+ best+ }+}++/// The leaf of `kind`, varied by `j` (-1..1 numbers).+fn leaf(kind: LeafKind, j: [f32; 4]) -> Leaf {+ let tilt = j[0] * 0.06;+ let one = |stalk: f32, b: Blade| Leaf { stalk: [0.0, stalk], stalk_w: 0.009, blades: vec![Blade { o: [0.0, stalk], ang: tilt, ..b }], discs: vec![] };+ match kind {+ LeafKind::Cordate => one(0.17, Blade { len: 0.8, w: 0.5 + 0.04 * j[1], p: 0.38, q: 0.85, t0: -0.12, teeth: 24.0, depth: 0.07, veins: 6.0, vein_ang: 0.75, asym: 0.08 * j[2], sinus: true, ..B }),+ LeafKind::Ovate => one(0.08, Blade { len: 0.9, w: 0.3 + 0.03 * j[1], p: 0.55, q: 0.8, t0: -0.02, teeth: 28.0, depth: 0.09, veins: 12.0, vein_ang: 0.7, asym: 0.12 + 0.04 * j[2], ..B }),+ LeafKind::Lanceolate => one(0.06, Blade { len: 0.93, w: 0.11 + 0.015 * j[1], p: 0.65, q: 0.7, teeth: 45.0, depth: 0.04, veins: 14.0, vein_ang: 0.9, ..B }),+ LeafKind::Triangular => one(0.22, Blade { len: 0.78, w: 0.44 + 0.03 * j[1], p: 0.3, q: 1.1, teeth: 16.0, depth: 0.12, veins: 7.0, vein_ang: 0.8, ..B }),+ LeafKind::Rhombic => one(0.24, Blade { len: 0.76, w: 0.5 + 0.04 * j[1], p: 0.45, q: 0.85, teeth: 18.0, depth: 0.06, veins: 6.0, vein_ang: 0.8, ..B }),+ LeafKind::Oak => one(0.05, Blade { len: 0.95, w: 0.32 + 0.03 * j[1], p: 0.6, q: 0.6, t0: -0.03, lobes: 4.5 + 0.5 * j[2], veins: 5.0, vein_ang: 0.8, ..B }),+ LeafKind::Palmate | LeafKind::Plane => {+ let maple = kind == LeafKind::Palmate;+ let (foot, angs, lens, w, teeth, depth, disc) = if maple {+ (0.36, [0.0, 0.75, -0.75, 1.45, -1.45], [0.62, 0.55, 0.55, 0.33, 0.33], 0.26, 3.5, 0.35, 0.2)+ } else {+ (0.3, [0.0, 0.8, -0.8, 1.5, -1.5], [0.66, 0.58, 0.58, 0.3, 0.3], 0.34, 5.0, 0.2, 0.24)+ };+ let blades = angs.iter().zip(lens).map(|(&a, l)| Blade { o: [0.0, foot], ang: a + tilt, len: l * (1.0 + 0.05 * j[1]), w, p: 0.3, q: if maple { 1.0 } else { 0.9 }, teeth, depth, veins: 4.0, vein_ang: 0.9, ..B }).collect();+ Leaf { stalk: [0.0, foot], stalk_w: 0.009, blades, discs: vec![([0.0, foot + 0.06], disc)] }+ }+ LeafKind::Compound => {+ let blades = [(0.0, 0.68), (0.5, 0.62), (-0.5, 0.62), (1.0, 0.5), (-1.0, 0.5), (1.5, 0.32), (-1.5, 0.32)]+ .iter()+ .map(|&(a, l)| Blade { o: [0.0, 0.3], ang: a + tilt, len: l * (1.0 + 0.05 * j[1]), w: 0.15, p: 1.1, q: 0.6, t0: 0.05, teeth: 30.0, depth: 0.04, veins: 14.0, vein_ang: 0.8, ..B })+ .collect();+ Leaf { stalk: [0.0, 0.3], stalk_w: 0.01, blades, discs: vec![] }+ }+ LeafKind::Pinnate => {+ let pairs = 6;+ let mut blades: Vec<Blade> = (0..pairs)+ .flat_map(|k| {+ let y = 0.18 + 0.6 * k as f32 / (pairs - 1) as f32;+ [1.0f32, -1.0].map(|s| Blade { o: [0.0, y], ang: s * (1.2 + 0.1 * j[2]), len: 0.2, w: 0.32, p: 0.7, q: 0.7, veins: 6.0, ..B })+ })+ .collect();+ blades.push(Blade { o: [0.0, 0.78], ang: tilt, len: 0.2, w: 0.32, p: 0.7, q: 0.7, veins: 6.0, ..B });+ Leaf { stalk: [0.0, 0.9], stalk_w: 0.006, blades, discs: vec![] }+ }+ }+}++fn hash2(x: i32, y: i32, s: u32) -> f32 {+ let mut h = (x as u32).wrapping_mul(0x8da6_b343) ^ (y as u32).wrapping_mul(0xd816_3841) ^ s.wrapping_mul(0xcb1a_b31f);+ h ^= h >> 13;+ h = h.wrapping_mul(0x5bd1_e995);+ (h ^ (h >> 15)) as f32 / u32::MAX as f32+}++fn noise(x: f32, y: f32, s: u32) -> f32 {+ let (ix, iy) = (x.floor() as i32, y.floor() as i32);+ let (fx, fy) = (x - ix as f32, y - iy as f32);+ let (ux, uy) = (fx * fx * (3.0 - 2.0 * fx), fy * fy * (3.0 - 2.0 * fy));+ let a = hash2(ix, iy, s) + (hash2(ix + 1, iy, s) - hash2(ix, iy, s)) * ux;+ let b = hash2(ix, iy + 1, s) + (hash2(ix + 1, iy + 1, s) - hash2(ix, iy + 1, s)) * ux;+ a + (b - a) * uy+}++/// A card's length over a leaf's, and its width over its length. One leaf fills its card; a sprig (a twig and its+/// leaves) fills a card about 1.5 + 0.22 a leaf leaf-lengths long and 0.85 of that wide; its twig takes the lower 0.58 of it and its tip leaf the rest.+pub(crate) fn card(sp: &Species) -> (f32, f32) {+ if sp.sprig <= 1 { (1.0, sp.aspect) } else { (1.5 + 0.22 * sp.sprig as f32, 0.85) }+}++/// A leaf on a card: its stalk's foot, its angle off straight up (toward +x), its size (card lengths), its own tone.+struct Placed {+ at: [f32; 2],+ ang: f32,+ scale: f32,+ leaf: Leaf,+ tone: f32,+}++/// A card's leaves and its twig's tip (the twig runs from the foot, the cell's bottom middle). The twig's leaves come+/// alternately left and right, or in opposite pairs, below a leaf at its tip; the lower ones smaller and spread wider.+fn sprig(sp: &Species, rng: &mut Rng) -> (Vec<Placed>, [f32; 2]) {+ let mut j = || [rng.range(-1.0, 1.0), rng.range(-1.0, 1.0), rng.range(-1.0, 1.0), rng.range(-1.0, 1.0)];+ if sp.sprig <= 1 {+ let jj = j();+ return (vec![Placed { at: [0.0, 0.0], ang: 0.0, scale: 1.0, leaf: leaf(sp.leaf, jj), tone: 0.5 + 0.5 * jj[3] }], [0.0, 0.0]);+ }+ let unit = 1.0 / card(sp).0;+ let bend = 0.06 * j()[0];+ let along = |t: f32| [bend * t * t, 0.58 * t];+ let tip = along(1.0);+ let mut out = Vec::new();+ let lateral = sp.sprig as usize - 1;+ let rows = if sp.opposite { lateral.div_ceil(2) } else { lateral };+ for k in 0..lateral {+ let row = if sp.opposite { k / 2 } else { k };+ let t = 0.1 + 0.8 * row as f32 / rows.max(1) as f32;+ let side = if k % 2 == 0 { 1.0 } else { -1.0 };+ let jj = j();+ out.push(Placed { at: along(t), ang: side * (1.25 - 0.5 * t) + 0.15 * jj[0], scale: unit * (0.8 + 0.25 * t) * (1.0 + 0.08 * jj[1]), leaf: leaf(sp.leaf, jj), tone: 0.5 + 0.5 * jj[3] });+ }+ let jj = j();+ out.push(Placed { at: tip, ang: 2.0 * bend + 0.1 * jj[0], scale: unit * 0.9, leaf: leaf(sp.leaf, jj), tone: 0.5 + 0.5 * jj[3] });+ (out, tip)+}++/// The species' atlas: CELLS x CELLS cards, each varied from the seed.+pub fn atlas(sp: &Species, seed: u64) -> RgbaImage {+ let size = CELLS * CELL;+ let mut img = RgbaImage::new(size, size);+ let mut rng = Rng::new(seed ^ 0xa71a5);+ let aspect = card(sp).1;+ let px = aspect.max(1.0) / CELL as f32;+ for cell in 0..CELLS * CELLS {+ let (leaves, tip) = sprig(sp, &mut rng);+ let s = rng.next() as u32;+ let (cx, cy) = ((cell % CELLS) * CELL, (cell / CELLS) * CELL);+ let tl = (tip[0] * tip[0] + tip[1] * tip[1]).max(1e-6);+ for py in 0..CELL {+ for pxi in 0..CELL {+ let x = ((pxi as f32 + 0.5) / CELL as f32 - 0.5) * aspect;+ let y = 1.0 - (py as f32 + 0.5) / CELL as f32;+ // the twig: a vein-coloured line from the foot to its tip+ let h = ((x * tip[0] + y * tip[1]) / tl).clamp(0.0, 1.0);+ let twig = 0.007 - (x - tip[0] * h).hypot(y - tip[1] * h);+ let (mut inside, mut vein, mut own, mut tone, mut local) = (twig, if twig > 0.0 { 1.0 } else { 0.0 }, 0.0f32, 0.5, [x, y]);+ for p in &leaves {+ let (dx, dy) = (x - p.at[0], y - p.at[1]);+ let (sa, ca) = p.ang.sin_cos();+ let l = [(dx * ca - dy * sa) / p.scale, (dx * sa + dy * ca) / p.scale];+ let (i, v) = p.leaf.at(l[0], l[1]);+ if i * p.scale > inside {+ (inside, vein, own, tone, local) = (i * p.scale, if i > 0.0 { v } else { 0.0 }, i, p.tone, l);+ }+ }+ let a = (0.5 + inside / (SPREAD * px)).clamp(0.0, 1.0);+ let blot = 0.6 * (0.65 * noise(local[0] * 10.0, local[1] * 10.0, s) + 0.35 * noise(local[0] * 26.0, local[1] * 26.0, s ^ 7)) + 0.4 * tone;+ let edge = (own / 0.08).clamp(0.0, 1.0);+ img.put_pixel(cx + pxi, cy + py, image::Rgba([(vein * 255.0) as u8, (blot * 255.0) as u8, (edge * 255.0) as u8, (a * 255.0) as u8]));+ }+ }+ }+ img+}++pub(crate) fn png(img: &RgbaImage) -> Result<Vec<u8>, String> {+ let mut out = Vec::new();+ img.write_to(&mut std::io::Cursor::new(&mut out), image::ImageFormat::Png).map_err(|e| e.to_string())?;+ Ok(out)+}++/// The share of a cell's pixels that are leaf.+pub(crate) fn coverage(img: &RgbaImage, cell: u32) -> f32 {+ let (cx, cy) = ((cell % CELLS) * CELL, (cell / CELLS) * CELL);+ let n = (0..CELL).flat_map(|y| (0..CELL).map(move |x| (x, y))).filter(|&(x, y)| img.get_pixel(cx + x, cy + y)[3] > 127).count();+ n as f32 / (CELL * CELL) as f32+}++/// The share of a card the species' leaves cover, over its atlas's cells: the leaf area a card carries is its quad's+/// times this (a lime's sprig about a third, a willow's narrow leaves about a tenth).+pub(crate) fn cover(img: &RgbaImage) -> f32 {+ (0..CELLS * CELLS).map(|c| coverage(img, c)).sum::<f32>() / (CELLS * CELLS) as f32+}++/// Whether a cell's card covers a point (x across in card lengths, y up).+#[cfg(test)]+pub(crate) fn covers(sp: &Species, img: &RgbaImage, cell: u32, x: f32, y: f32) -> bool {+ let (cx, cy) = ((cell % CELLS) * CELL, (cell / CELLS) * CELL);+ let px = ((x / card(sp).1 + 0.5) * CELL as f32) as u32;+ let py = ((1.0 - y) * CELL as f32) as u32;+ img.get_pixel(cx + px.min(CELL - 1), cy + py.min(CELL - 1))[3] > 127+}++/// How far inside a plain leaf of a kind a point is (for the tests).+#[cfg(test)]+pub(crate) fn leaf_at(kind: LeafKind) -> impl Fn(f32, f32) -> f32 {+ let l = leaf(kind, [0.0; 4]);+ move |x, y| l.at(x, y).0+}diff --git a/systems/foliage/src/grow.rs b/systems/foliage/src/grow.rsnew file mode 100644index 00000000..0bd0f35b--- /dev/null+++ b/systems/foliage/src/grow.rs@@ -0,0 +1,268 @@+//! A tree's skeleton by space colonization (Runions, Lane and Prusinkiewicz 2007; docs/foliage.feature FO1).+//! 1. the crown's envelope: from the clear trunk to the top, a profile widest at `widest`, `square` its+//! superellipse exponent, made lumpy by a few low waves round it; attraction points fill it, most in its outer+//! shell, where light reaches+//! 2. a trunk rises, leaning a little, into the crown+//! 3. colonization: each point pulls the node nearest it within reach; each pulled node grows one step toward the+//! mean of its pulls (bent by the species' tropism), and a point any node comes within kill of is used up.+//! Each point keeps its nearest node and only the new nodes are checked against it, so a step costs the points+//! times the new nodes near them, not the whole tree+//! 4. twigs sprout from the tips; thin shoots droop by the species' droop; the chains are smoothed+//! 5. radii by the pipe model, scaled so the trunk has the species' radius for its height++use std::collections::HashMap;++use parry3d::glamx::Vec3;++use crate::species::Species;+use crate::{Request, Rng};++/// A node of the skeleton: where, its parent (usize::MAX for the root), its radius, whether it's a twig.+#[derive(Clone, Debug)]+pub struct Node {+ pub p: Vec3,+ pub parent: usize,+ pub r: f32,+ pub twig: bool,+}++pub(crate) const NONE: usize = usize::MAX;+const MAX_NODES: usize = 80_000;+const MAX_STEPS: usize = 500;++/// The crown's envelope: its radius at a height and bearing.+pub(crate) struct Envelope {+ pub base: f32,+ pub top: f32,+ pub rad: f32,+ widest: f32,+ square: f32,+ low: f32,+ waves: [(f32, f32, f32); 3],+}++impl Envelope {+ pub(crate) fn new(sp: &Species, req: &Request, rng: &mut Rng) -> Envelope {+ let waves = [1.0f32, 2.0, 3.0].map(|k| (k, rng.range(0.0, std::f32::consts::TAU), sp.lumps * rng.range(0.4, 1.0) / k.sqrt()));+ Envelope { base: req.clear, top: req.height, rad: req.width / 2.0, widest: sp.widest, square: sp.square, low: sp.low, waves }+ }+ /// The crown's radius at height y on bearing a (radians); 0 outside its heights.+ pub(crate) fn r(&self, y: f32, a: f32) -> f32 {+ let t = (y - self.base) / (self.top - self.base);+ if !(0.0..=1.0).contains(&t) {+ return 0.0;+ }+ let s = if t < self.widest { (self.widest - t) / self.widest } else { (t - self.widest) / (1.0 - self.widest) };+ let e = if t < self.widest { self.low } else { self.square };+ let prof = (1.0 - s.powf(e)).max(0.0).powf(1.0 / e);+ let lump: f32 = self.waves.iter().map(|&(k, ph, amp)| amp * (k * a + ph + 2.0 * t).cos()).sum();+ self.rad * prof * (1.0 + lump)+ }+ pub(crate) fn centre(&self) -> Vec3 {+ Vec3::new(0.0, self.base + (self.top - self.base) * self.widest, 0.0)+ }+}++type Cell = (i32, i32, i32);++fn cell(p: Vec3, s: f32) -> Cell {+ ((p.x / s).floor() as i32, (p.y / s).floor() as i32, (p.z / s).floor() as i32)+}++pub(crate) fn grow(sp: &Species, req: &Request, rng: &mut Rng) -> (Vec<Node>, Envelope) {+ let env = Envelope::new(sp, req, rng);+ // a bigger crown takes bigger steps, so a street lime and a park plane cost about the same+ let step = sp.step * (env.rad / 5.0).clamp(0.6, 1.6);+ let (reach, kill) = (sp.reach * step, sp.kill * step);++ // 1. attraction points, in the crown's lobes and their bumps (lobes.rs)+ let volume = std::f32::consts::PI * env.rad * env.rad * (env.top - env.base) * 0.55;+ let want = ((sp.points * volume * (1.0 - (1.0 - sp.shell).powi(3))) as usize).clamp(400, 24_000);+ let crown = crate::lobes::lobes(sp, &env, rng);+ let mut pts: Vec<(Vec3, usize, f32)> = crate::lobes::points(sp, &env, &crown, want, rng).into_iter().map(|p| (p, NONE, f32::INFINITY)).collect();++ // 2. the trunk, on up the crown as a leader as far as the species carries one, wandering a little; then the big+ // limbs a forking species splits into there, spread round and leaning out (colonization grows from all of it,+ // so scaffold branches leave the leader at every height)+ let lean = Vec3::new(rng.range(-1.0, 1.0), 0.0, rng.range(-1.0, 1.0)) * 0.035;+ let mut nodes = vec![Node { p: Vec3::ZERO, parent: NONE, r: 0.0, twig: false }];+ let into = env.base + (env.top - env.base) * sp.leader.max(0.12);+ let mut wander = Vec3::ZERO;+ while nodes.last().unwrap().p.y < into {+ wander = (wander + Vec3::new(rng.range(-1.0, 1.0), 0.0, rng.range(-1.0, 1.0)) * 0.04) * 0.85;+ let d = (Vec3::Y + lean + wander).normalize();+ let last = nodes.len() - 1;+ nodes.push(Node { p: nodes[last].p + d * step, parent: last, r: 0.0, twig: false });+ }+ let fork = nodes.len() - 1;+ let spin = rng.range(0.0, std::f32::consts::TAU);+ for k in 0..sp.forks {+ let a = spin + std::f32::consts::TAU * (k as f32 + rng.range(-0.2, 0.2)) / sp.forks as f32;+ let tilt = rng.range(0.45, 0.8);+ let mut d = Vec3::new(a.cos() * tilt.sin(), tilt.cos(), a.sin() * tilt.sin());+ let mut at = fork;+ let len = (env.top - env.base) * rng.range(0.22, 0.32);+ for _ in 0..(len / step) as usize {+ d = (d + Vec3::Y * 0.04 + rng.unit() * 0.05).normalize();+ nodes.push(Node { p: nodes[at].p + d * step, parent: at, r: 0.0, twig: false });+ at = nodes.len() - 1;+ }+ }+ // each big lobe's scaffold limb, from the frame so far+ let frame: Vec<Vec3> = nodes.iter().map(|n| n.p).collect();+ for (p, parent) in crate::lobes::scaffolds(sp, &crown, &frame, step, rng) {+ nodes.push(Node { p, parent, r: 0.0, twig: false });+ }++ // 3. colonization+ let mut kids: Vec<Vec<usize>> = vec![Vec::new(); nodes.len()];+ for i in 1..nodes.len() {+ kids[nodes[i].parent].push(i);+ }+ let mut fresh: Vec<usize> = (0..nodes.len()).collect();+ let mut leader = fork;+ for _ in 0..MAX_STEPS {+ // each point's nearest node, from the nodes new since the last step+ let mut grid: HashMap<Cell, Vec<usize>> = HashMap::new();+ for &i in &fresh {+ grid.entry(cell(nodes[i].p, reach)).or_default().push(i);+ }+ for (p, near, dist) in pts.iter_mut() {+ let c = cell(*p, reach);+ for dx in -1..=1 {+ for dy in -1..=1 {+ for dz in -1..=1 {+ for &i in grid.get(&(c.0 + dx, c.1 + dy, c.2 + dz)).into_iter().flatten() {+ let d = (nodes[i].p - *p).length();+ if d < *dist && d < reach {+ (*near, *dist) = (i, d);+ }+ }+ }+ }+ }+ }+ pts.retain(|&(_, _, d)| d > kill);+ if pts.is_empty() || nodes.len() >= MAX_NODES {+ break;+ }+ let mut pull: HashMap<usize, Vec3> = HashMap::new();+ for &(p, near, _) in &pts {+ if near != NONE {+ *pull.entry(near).or_insert(Vec3::ZERO) += (p - nodes[near].p).normalize();+ }+ }+ let mut order: Vec<_> = pull.into_iter().collect();+ order.sort_by_key(|&(i, _)| i);+ fresh.clear();+ // nothing in reach yet: the trunk climbs on+ if order.is_empty() && nodes[leader].p.y < env.top {+ let p = nodes[leader].p + (Vec3::Y + lean).normalize() * step;+ nodes.push(Node { p, parent: leader, r: 0.0, twig: false });+ kids.push(Vec::new());+ kids[leader].push(nodes.len() - 1);+ leader = nodes.len() - 1;+ fresh.push(leader);+ continue;+ }+ for (i, sum) in order {+ if sum.length() < 1e-3 {+ continue;+ }+ let d = (sum.normalize() + Vec3::Y * sp.up * 0.35 + rng.unit() * sp.crook * 0.5).normalize();+ let p = nodes[i].p + d * step;+ if kids[i].iter().any(|&k| (nodes[k].p - p).length() < step * 0.15) {+ continue;+ }+ nodes.push(Node { p, parent: i, r: 0.0, twig: false });+ kids.push(Vec::new());+ kids[i].push(nodes.len() - 1);+ fresh.push(nodes.len() - 1);+ }+ if fresh.is_empty() {+ break;+ }+ }++ // 4. twigs from the tips+ let tips: Vec<usize> = (1..nodes.len()).filter(|&i| kids[i].is_empty()).collect();+ for &t in &tips {+ let n = (sp.twigs + rng.f()) as usize;+ let dir = (nodes[t].p - nodes[nodes[t].parent].p).normalize_or_zero();+ for _ in 0..n {+ let mut at = t;+ let mut d = (dir * 0.6 + rng.unit() * 0.7 + Vec3::Y * sp.up * 0.3).normalize();+ for _ in 0..3 {+ let p = nodes[at].p + d * (sp.twig_len / 3.0) * rng.range(0.7, 1.2);+ nodes.push(Node { p, parent: at, r: 0.0, twig: true });+ kids.push(Vec::new());+ kids[at].push(nodes.len() - 1);+ at = nodes.len() - 1;+ d = (d + rng.unit() * 0.25).normalize();+ }+ }+ }++ radii(sp, req, &mut nodes, &kids);+ droop(sp, &mut nodes);+ smooth(&mut nodes, &kids, if sp.crook < 0.15 { 2 } else { 1 });+ (nodes, env)+}++/// The pipe model: a parent's radius^n is the sum of its children's. A model has far fewer tips than a real tree, so+/// one exponent can't give both a real twig and a real trunk: n is fitted per tree so the tips have the species' twig+/// radius and the trunk's foot its radius for the tree's height (clamped to 1.5-3.5, the trunk kept exact).+fn radii(sp: &Species, req: &Request, nodes: &mut [Node], kids: &[Vec<usize>]) {+ let mut a = vec![0f32; nodes.len()];+ for i in (0..nodes.len()).rev() {+ a[i] = if kids[i].is_empty() { 1.0 } else { kids[i].iter().map(|&k| a[k]).sum() };+ }+ let trunk = sp.trunk * req.height;+ let n = (a[0].ln() / (trunk / sp.tip).ln().max(1e-3)).clamp(1.5, 3.5);+ let k = trunk / a[0].powf(1.0 / n);+ for (node, a) in nodes.iter_mut().zip(&a) {+ node.r = k * a.powf(1.0 / n);+ }+}++/// Thin shoots hang: each segment turns down by droop x its length x how thin it is, carried out to its children.+fn droop(sp: &Species, nodes: &mut [Node]) {+ if sp.droop <= 0.0 {+ return;+ }+ let tip_r = nodes.iter().map(|n| n.r).fold(f32::INFINITY, f32::min);+ let orig: Vec<Vec3> = nodes.iter().map(|n| n.p).collect();+ for i in 1..nodes.len() {+ let par = nodes[i].parent;+ let off = orig[i] - orig[par];+ let len = off.length();+ if len < 1e-6 {+ continue;+ }+ let thin = (tip_r / nodes[i].r).powf(0.6);+ let turn = (sp.droop * len * thin).min(1.2);+ let d = (off / len - Vec3::Y * turn.tan()).normalize();+ nodes[i].p = nodes[par].p + d * len;+ }+}++/// Two passes of a chain's middles toward their neighbours (branch points, tips and the root held).+fn smooth(nodes: &mut [Node], kids: &[Vec<usize>], passes: usize) {+ for _ in 0..passes {+ let was: Vec<Vec3> = nodes.iter().map(|n| n.p).collect();+ for i in 1..nodes.len() {+ if let [k] = kids[i][..] {+ nodes[i].p = was[i] * 0.5 + (was[nodes[i].parent] + was[k]) * 0.25;+ }+ }+ }+}++/// Each node's children.+pub(crate) fn children(nodes: &[Node]) -> Vec<Vec<usize>> {+ let mut kids = vec![Vec::new(); nodes.len()];+ for (i, n) in nodes.iter().enumerate().skip(1) {+ kids[n.parent].push(i);+ }+ kids+}diff --git a/systems/foliage/src/leaves.rs b/systems/foliage/src/leaves.rsnew file mode 100644index 00000000..c17d8ba9--- /dev/null+++ b/systems/foliage/src/leaves.rs@@ -0,0 +1,151 @@+//! Leaves on the outer shoots (docs/foliage.feature FO2): along each shoot within `leafy` m of a tip and thin enough to+//! bear them, at the species' leaves a metre (thinned to the request's budget). Each leaf is a card from its stalk's+//! foot (the atlas cell's bottom middle) to its tip:+//! - its direction: out from the shoot (a golden-angle turn a leaf), forward along it, out of the crown, and down by+//! the species' hang;+//! - its face: toward up and out of the crown, made square to its direction, its tip curled a little;+//! - its shading normal bent from its face toward out of the crown, so a crown shades as a volume (the leaf hook+//! uses this normal on both sides);+//! - its size: shade leaves (deep in the crown) are larger, as they are on a real tree;+//! - its shading normal: from its face toward where its sky is (light.rs's bent normal), so clumps shade as clumps.+//! Its colour: r its own random number (its group, its fall and its tint), g its sky view through the crown's leaves+//! (light.rs: the hook's ambient occlusion; sunlit leaves colour first), b where it sits on its shoot (1 at the tip:+//! it unfolds last).++use parry3d::glamx::Vec3;++use crate::grow::{Envelope, Node, children};+use crate::species::Species;+use crate::{CELLS, GROUPS, Mesh, Request, Rng, across};++const GOLDEN: f32 = 2.399_963;+/// a shoot thicker than this (m) bears no leaves+const BEARS: f32 = 0.02;+/// `cover` is the share of a card its leaves cover (atlas.rs cover), so the cards carry the species' leaf area.+pub(crate) fn leaves(sp: &Species, req: &Request, nodes: &[Node], env: &Envelope, cover: f32, rng: &mut Rng) -> Vec<Mesh> {+ let kids = children(nodes);+ // each node's distance (along the tree) to its nearest tip+ let mut to_tip = vec![f32::INFINITY; nodes.len()];+ for i in (0..nodes.len()).rev() {+ if kids[i].is_empty() {+ to_tip[i] = 0.0;+ }+ if i > 0 {+ let p = nodes[i].parent;+ to_tip[p] = to_tip[p].min(to_tip[i] + (nodes[i].p - nodes[p].p).length());+ }+ }+ let bears = |i: usize| i > 0 && to_tip[i] < sp.leafy && nodes[i].r < BEARS && nodes[i].p.y > req.clear * 0.9;+ // clumps and sky holes: a card is kept by a low noise through the crown (about 1.5 m across), and the rest are+ // thickened to hold the leaf area+ let keep = |p: Vec3| smooth(sp.gaps - 0.12, sp.gaps + 0.12, 0.65 * noise3(p / 1.5, req.seed) + 0.35 * noise3(p / 0.6, req.seed ^ 9));+ let mid = |i: usize| (nodes[i].p + nodes[nodes[i].parent].p) * 0.5;+ let length: f32 = (1..nodes.len()).filter(|&i| bears(i)).map(|i| (nodes[i].p - nodes[nodes[i].parent].p).length()).sum();+ let kept: f32 = (1..nodes.len()).filter(|&i| bears(i)).map(|i| (nodes[i].p - nodes[nodes[i].parent].p).length() * keep(mid(i))).sum();+ // the crown carries its species' leaf area (leaf area index x the crown's ground area), on cards of a sprig each+ // `cover` full; a budget under that gets fewer, bigger cards (up to 2.5 times as long, or 5 on a pruned level:+ // one seen from far off, where a crown short of its leaf area reads as see-through and a big card does not show)+ let (card_len, card_w) = crate::atlas::card(sp);+ let card_area = (sp.leaf_len * card_len).powi(2) * card_w * cover;+ // leaf area index is over the crown's ground area, which undercounts a column: a crown deeper than 1.3 times its+ // width (a poplar's) carries more in proportion (leaf area density times its volume)+ let column = ((req.height - req.clear) / req.width / 1.3).max(1.0);+ let want = sp.lai * column * std::f32::consts::PI * (req.width / 2.0).powi(2) / card_area;+ let cards = want.min(req.leaves as f32);+ let bigger = (want / cards.max(1.0)).sqrt().min(if req.prune > 0.0 { 5.0 } else { 2.5 });+ let per_m = cards / kept.max(0.05 * length).max(1.0);++ let centre = env.centre();+ // every card first, then their light (light.rs), then the meshes+ struct Card {+ at: Vec3,+ dir: Vec3,+ face: Vec3,+ len: f32,+ own: f32,+ shoot: f32,+ cell: u32,+ }+ let mut cards: Vec<Card> = Vec::new();+ let mut turn = 0.0f32;+ for i in (1..nodes.len()).filter(|&i| bears(i)) {+ let (a, b) = (nodes[nodes[i].parent].p, nodes[i].p);+ let seg = (b - a).length();+ if seg < 1e-4 {+ continue;+ }+ let axis = (b - a) / seg;+ let count = (per_m * seg + rng.f()) as usize;+ for _ in 0..count {+ let at = a + (b - a) * rng.f();+ if rng.f() > keep(at) {+ continue;+ }+ turn += GOLDEN;+ let r0 = across(axis);+ let radial = r0 * turn.cos() + axis.cross(r0) * turn.sin();+ let off = at - centre;+ let out_of = Vec3::new(off.x, off.y * 0.5, off.z).normalize_or_zero();+ let dir = (radial * 0.8 + axis * 0.45 + out_of * 0.35 + Vec3::Y * 0.15 - Vec3::Y * sp.leaf_droop + rng.unit() * 0.2).normalize();+ // leaves face up and out of the crown, but no two alike: from the side a crown still shows faces, not edges+ let face = Vec3::Y * 0.6 + out_of * 0.5 + rng.unit() * 0.7;+ let face = (face - dir * face.dot(dir)).normalize_or_zero();+ if face == Vec3::ZERO {+ continue;+ }+ let len = bigger * sp.leaf_len * card_len * rng.range(0.8, 1.2);+ let (own, shoot) = (rng.f(), 1.0 - (to_tip[i] / sp.leafy).min(1.0));+ let cell = (rng.f() * (CELLS * CELLS) as f32) as u32 % (CELLS * CELLS);+ cards.push(Card { at, dir, face, len, own, shoot, cell });+ }+ }+ let mid: Vec<Vec3> = cards.iter().map(|c| c.at + c.dir * (c.len * 0.5)).collect();+ let area: Vec<f32> = cards.iter().map(|c| c.len * c.len * card_w * cover).collect();+ let (sky, bent) = crate::light::light(&mid, &area);++ let mut out = vec![Mesh::default(); GROUPS];+ for (k, c) in cards.iter().enumerate() {+ // exposure is the leaf's sky view; shade leaves (deep in the crown) are larger, as on a real tree+ let exposed = sky[k].clamp(0.0, 1.0);+ let len = c.len * (1.0 + 0.3 * (1.0 - exposed));+ let w = len * card_w;+ let side = c.face.cross(c.dir);+ // the shading normal leans from the leaf's face to where its sky is (its bent normal)+ let bend = (c.face * 0.35 + bent[k] * 0.65).normalize_or(bent[k]);+ let tip = c.at + c.dir * len - c.face * (len * 0.15);+ let (cu, cv) = ((c.cell % CELLS) as f32 / CELLS as f32, (c.cell / CELLS) as f32 / CELLS as f32);+ let step = 1.0 / CELLS as f32;+ let m = &mut out[((c.own * GROUPS as f32) as usize).min(GROUPS - 1)];+ let base = m.pos.len() as u32;+ for (q, u, v) in [(c.at - side * (w / 2.0), 0.0, 0.0), (c.at + side * (w / 2.0), 1.0, 0.0), (tip - side * (w / 2.0), 0.0, 1.0), (tip + side * (w / 2.0), 1.0, 1.0)] {+ m.pos.push(q.to_array());+ m.nrm.push(bend.to_array());+ // the atlas's rows run top down; a cell's bottom row is the stalk's foot+ m.uv.push([cu + u * step, cv + (1.0 - v) * step]);+ m.col.push([c.own, exposed, c.shoot, 1.0]);+ }+ m.idx.extend_from_slice(&[base, base + 2, base + 1, base + 1, base + 2, base + 3]);+ }+ out+}++fn smooth(a: f32, b: f32, x: f32) -> f32 {+ let t = ((x - a) / (b - a)).clamp(0.0, 1.0);+ t * t * (3.0 - 2.0 * t)+}++/// Value noise in 3D, 0 to 1, from a seed.+fn noise3(p: Vec3, seed: u64) -> f32 {+ let h = |x: i32, y: i32, z: i32| {+ let mut k = (x as u64).wrapping_mul(0x9e37_79b9_7f4a_7c15) ^ (y as u64).wrapping_mul(0xc2b2_ae3d_27d4_eb4f) ^ (z as u64).wrapping_mul(0x1656_67b1_9e37_79f9) ^ seed;+ k ^= k >> 31;+ k = k.wrapping_mul(0xbf58_476d_1ce4_e5b9);+ (k >> 40) as f32 / (1u64 << 24) as f32+ };+ let (i, f) = (p.floor(), p - p.floor());+ let u = f * f * (Vec3::splat(3.0) - f * 2.0);+ let (x, y, z) = (i.x as i32, i.y as i32, i.z as i32);+ let lerp = |a: f32, b: f32, t: f32| a + (b - a) * t;+ let c = |dy: i32, dz: i32| lerp(h(x, y + dy, z + dz), h(x + 1, y + dy, z + dz), u.x);+ lerp(lerp(c(0, 0), c(1, 0), u.y), lerp(c(0, 1), c(1, 1), u.y), u.z)+}diff --git a/systems/foliage/src/lib.rs b/systems/foliage/src/lib.rsnew file mode 100644index 00000000..262538ed--- /dev/null+++ b/systems/foliage/src/lib.rs@@ -0,0 +1,141 @@+//! Plants grown from their species (docs/foliage.feature FO1-FO4): a request (a species, a height, a crown width, a+//! clear trunk and a seed) grows a tree by space colonization in the species' crown (grow.rs), gives its branches the+//! pipe model's radii and tubes (tube.rs), sets its leaves on its outer shoots as cards in eight groups by the order+//! they fall (leaves.rs), draws the species' leaf atlas by rules (atlas.rs) and writes one .glb (out.rs).+//!+//! Nothing here knows a season: a leaf's vertex colour carries its own random number, how exposed it is and how far+//! along its shoot it sits, and a surface hook draws the day over them (raea/foliage). The same request gives the+//! same bytes.++use parry3d::glamx::Vec3;++mod atlas;+mod grow;+mod leaves;+mod light;+mod lobes;+mod out;+mod roots;+mod shape;+pub mod species;+mod tube;+#[cfg(test)]+mod tests;++pub use atlas::{CELLS, atlas};+pub use grow::Node;+pub use shape::silhouette;+pub use species::{LeafKind, Species, species};++pub const VERSION: &str = "raea-sys-foliage 3";++/// The leaf groups: a leaf's group is its random number's eighth, so a group goes when its leaves have fallen.+pub const GROUPS: usize = 8;++/// What to grow. Sizes in metres; the height is the whole tree's, the clear trunk is up to the crown's base.+#[derive(Clone, Debug)]+pub struct Request {+ pub species: String,+ pub height: f32,+ pub width: f32,+ pub clear: f32,+ pub seed: u64,+ /// at most this many leaves (a level of detail's budget); the species' density is thinned to fit+ pub leaves: u32,+ /// the thinnest branch drawn as a tube (m; 0 all of them): a far level of detail drops its twigs and keeps its+ /// leaves where they were+ pub prune: f32,+}++/// Triangles with what the hooks read: position, normal, uv, a second uv (bark: the pattern's period round the+/// branch and the radius), a colour (bark: height, thinness; leaf: its random number, exposure, place on its shoot).+#[derive(Clone, Debug, Default)]+pub struct Mesh {+ pub pos: Vec<[f32; 3]>,+ pub nrm: Vec<[f32; 3]>,+ pub uv: Vec<[f32; 2]>,+ pub uv1: Vec<[f32; 2]>,+ pub col: Vec<[f32; 4]>,+ pub idx: Vec<u32>,+}++impl Mesh {+ pub fn tris(&self) -> usize {+ self.idx.len() / 3+ }+}++/// A grown plant: its skeleton, its bark and its leaf groups.+pub struct Plant {+ pub nodes: Vec<Node>,+ pub bark: Mesh,+ pub leaves: Vec<Mesh>,+}++impl Plant {+ pub fn leaf_count(&self) -> usize {+ self.leaves.iter().map(|m| m.idx.len() / 6).sum()+ }+}++/// Grow a plant.+pub fn grow(req: &Request) -> Result<Plant, String> {+ let sp = species(&req.species).ok_or_else(|| format!("no species {:?}; known: {}", req.species, species::ALL.iter().map(|s| s.id).collect::<Vec<_>>().join(", ")))?;+ if !(req.height > 1.0 && req.width > 0.5 && req.clear >= 0.0 && req.clear < req.height) {+ return Err(format!("a tree needs a height over 1 m, a width over 0.5 m and a clear trunk under its height, got {req:?}"));+ }+ let mut rng = Rng::new(req.seed ^ hash_str(sp.id));+ let (nodes, env) = grow::grow(sp, req, &mut rng);+ let mut bark = tube::bark(sp, req, &nodes);+ roots::foot(sp, req, &nodes, &mut bark);+ let cover = atlas::cover(&atlas(sp, req.seed)).max(0.05);+ let leaves = leaves::leaves(sp, req, &nodes, &env, cover, &mut rng);+ Ok(Plant { nodes, bark, leaves })+}++/// The plant as a .glb: material "bark", and "leaf-0" to "leaf-7" over the species' atlas (alpha mask, both sides).+pub fn glb(req: &Request, plant: &Plant) -> Result<Vec<u8>, String> {+ let sp = species(&req.species).ok_or("no species")?;+ let png = atlas::png(&atlas(sp, req.seed))?;+ Ok(out::glb(sp, plant, &png))+}++/// A seeded stream (splitmix64): the same plant on every machine.+pub(crate) struct Rng(u64);++impl Rng {+ pub(crate) fn new(seed: u64) -> Rng {+ Rng(seed ^ 0x9e37_79b9_7f4a_7c15)+ }+ pub(crate) fn next(&mut self) -> u64 {+ self.0 = self.0.wrapping_add(0x9e37_79b9_7f4a_7c15);+ let mut z = self.0;+ z = (z ^ (z >> 30)).wrapping_mul(0xbf58_476d_1ce4_e5b9);+ z = (z ^ (z >> 27)).wrapping_mul(0x94d0_49bb_1331_11eb);+ z ^ (z >> 31)+ }+ /// in [0, 1)+ pub(crate) fn f(&mut self) -> f32 {+ (self.next() >> 40) as f32 / (1u64 << 24) as f32+ }+ pub(crate) fn range(&mut self, a: f32, b: f32) -> f32 {+ a + (b - a) * self.f()+ }+ /// a direction, evenly over the sphere+ pub(crate) fn unit(&mut self) -> Vec3 {+ let z = self.range(-1.0, 1.0);+ let a = self.range(0.0, std::f32::consts::TAU);+ let s = (1.0 - z * z).max(0.0).sqrt();+ Vec3::new(s * a.cos(), z, s * a.sin())+ }+}++pub(crate) fn hash_str(s: &str) -> u64 {+ s.bytes().fold(0xcbf2_9ce4_8422_2325u64, |h, b| (h ^ b as u64).wrapping_mul(0x0100_0000_01b3))+}++/// A unit vector across `d`.+pub(crate) fn across(d: Vec3) -> Vec3 {+ let t = if d.y.abs() < 0.9 { Vec3::Y } else { Vec3::X };+ (t - d * t.dot(d)).normalize()+}diff --git a/systems/foliage/src/light.rs b/systems/foliage/src/light.rsnew file mode 100644index 00000000..087594c8--- /dev/null+++ b/systems/foliage/src/light.rs@@ -0,0 +1,72 @@+//! What each leaf sees of the sky through the crown's own leaves (docs/foliage.feature FO2). The crown's leaf area is+//! put in a grid of CELL m cells as leaf area density (m2 of leaf a m3); from each leaf, rays go out along 19+//! directions through it, and each lets through e^(-G * LAD * path) of the light (Beer and Lambert, with G = 0.5 for+//! leaves at random angles: Monsi and Saeki 1953). A leaf's sky view is the upper rays' light, weighted by their sine+//! of elevation (a cloudy sky's light on a level leaf); its bent normal is the rays' directions weighted by what they+//! let through. So a clump's outer face is bright and faces out of the clump, the hollows between clumps and the+//! crown's core are dark, and the crown shades as many masses, not as one ball.++use parry3d::glamx::Vec3;++const CELL: f32 = 0.5;+const G: f32 = 0.5;++fn dirs() -> Vec<(Vec3, f32)> {+ let mut out = vec![(Vec3::Y, 1.0)];+ for (elev, off) in [(60f32, 0.0f32), (20.0, 30.0), (-25.0, 0.0)] {+ for k in 0..6 {+ let (e, a) = (elev.to_radians(), (off + 60.0 * k as f32).to_radians());+ out.push((Vec3::new(e.cos() * a.cos(), e.sin(), e.cos() * a.sin()), e.sin()));+ }+ }+ out+}++/// For leaves at `at` with leaf area `area` (m2): each one's sky view (0-1) and bent normal.+pub(crate) fn light(at: &[Vec3], area: &[f32]) -> (Vec<f32>, Vec<Vec3>) {+ if at.is_empty() {+ return (Vec::new(), Vec::new());+ }+ let lo = at.iter().fold(Vec3::splat(f32::INFINITY), |a, &p| a.min(p)) - Vec3::splat(CELL);+ let hi = at.iter().fold(Vec3::splat(f32::NEG_INFINITY), |a, &p| a.max(p)) + Vec3::splat(CELL);+ let n = ((hi - lo) / CELL).ceil();+ let (nx, ny, nz) = (n.x as usize, n.y as usize, n.z as usize);+ let index = |p: Vec3| -> Option<usize> {+ let q = (p - lo) / CELL;+ (q.x >= 0.0 && q.y >= 0.0 && q.z >= 0.0 && (q.x as usize) < nx && (q.y as usize) < ny && (q.z as usize) < nz).then(|| (q.x as usize * ny + q.y as usize) * nz + q.z as usize)+ };+ let mut lad = vec![0f32; nx * ny * nz];+ for (&p, &a) in at.iter().zip(area) {+ if let Some(i) = index(p) {+ lad[i] += a / (CELL * CELL * CELL);+ }+ }+ let dirs = dirs();+ let up: f32 = dirs.iter().filter(|d| d.1 > 0.0).map(|d| d.1).sum();+ let step = CELL * 0.5;+ let mut sky = Vec::with_capacity(at.len());+ let mut bent = Vec::with_capacity(at.len());+ for &p in at {+ let (mut s, mut b) = (0.0, Vec3::ZERO);+ for &(d, w) in &dirs {+ // from just outside the leaf's own cell share, out to the grid's edge+ let mut q = p + d * (CELL * 0.6);+ let mut tau = 0.0;+ while let Some(i) = index(q) {+ tau += G * lad[i] * step;+ q += d * step;+ if tau > 8.0 {+ break;+ }+ }+ let t = (-tau).exp();+ b += d * t;+ if w > 0.0 {+ s += w * t;+ }+ }+ sky.push(s / up);+ bent.push(b.normalize_or(Vec3::Y));+ }+ (sky, bent)+}diff --git a/systems/foliage/src/lobes.rs b/systems/foliage/src/lobes.rsnew file mode 100644index 00000000..a5f12738--- /dev/null+++ b/systems/foliage/src/lobes.rs@@ -0,0 +1,149 @@+//! The crown's masses (docs/foliage.feature FO1): a broadleaf crown seen from a street is a few clouds of foliage,+//! each the leafy end of one scaffold limb, with sky in the notches between them, and each cloud is itself bumped by+//! the shoots on its outer face. So the crown is drawn as big lobes set round its envelope (the species' profile, now+//! only the crown's reach), each carrying smaller bumps on the side that faces out, and the attraction points that+//! grow the branches are put in the bumps' outer shells, where light reaches, with a few through each lobe's inside.++use std::f32::consts::TAU;++use parry3d::glamx::Vec3;++use crate::grow::Envelope;+use crate::species::Species;+use crate::Rng;++/// A cloud of foliage: its centre, its radius across and how much taller than wide it is.+/// how far apart two big lobes' centres are kept, of their radii summed: under 1 they overlap, so the crown is one+/// mass with notches, not separate balls+const APART: f32 = 0.48;++#[derive(Clone, Debug)]+pub(crate) struct Lobe {+ pub c: Vec3,+ pub r: f32,+ pub tall: f32,+}++impl Lobe {+ /// where p is in the lobe: 0 at its centre, 1 on its surface+ fn depth(&self, p: Vec3) -> f32 {+ let d = p - self.c;+ Vec3::new(d.x, d.y / self.tall, d.z).length() / self.r+ }+}++/// The big lobes, and each one's bumps.+pub(crate) fn lobes(sp: &Species, env: &Envelope, rng: &mut Rng) -> Vec<(Lobe, Vec<Lobe>)> {+ // more lobes on a bigger crown and up a taller one (a poplar's column is a stack of them)+ let column = ((env.top - env.base) / (2.0 * env.rad)).max(1.0);+ let n = (sp.lobes * (env.rad / 5.0).sqrt().clamp(0.7, 1.5) * column).round().max(1.0) as usize;+ let tall = (sp.height_per_width / 1.4).clamp(0.85, 1.7);+ let lean = Vec3::new(rng.range(-1.0, 1.0), 0.0, rng.range(-1.0, 1.0)).normalize_or_zero() * sp.skew * env.rad;+ let h = env.top - env.base;+ let mut big: Vec<Lobe> = Vec::new();+ // the top first: every crown has one+ let r = sp.lobe * env.rad * rng.range(0.8, 1.05);+ big.push(Lobe { c: Vec3::new(0.0, env.top - r * tall * 0.85, 0.0) + lean, r, tall });+ let mut tries = 0;+ while big.len() < n && tries < n * 80 {+ tries += 1;+ let r = sp.lobe * env.rad * rng.range(0.7, 1.15);+ let t = rng.range(0.1, 0.85);+ let a = rng.range(0.0, TAU);+ let y = env.base + h * t;+ let rr = env.r(y, a);+ // more lobes where the crown is broad+ if rr < r * 0.5 || rng.f() > rr / env.rad {+ continue;+ }+ let d = (rr - r * rng.range(0.55, 0.9)).max(0.0);+ let c = Vec3::new(a.cos() * d, y.clamp(env.base + r * tall * 0.45, env.top - r * tall * 0.5), a.sin() * d) + lean * t;+ // apart enough that a notch shows between neighbours+ if big.iter().any(|l| (Vec3::new(l.c.x - c.x, (l.c.y - c.y) / tall, l.c.z - c.z)).length() < (l.r + r) * APART) {+ continue;+ }+ big.push(Lobe { c, r, tall });+ }+ let core = env.centre();+ big.into_iter()+ .map(|l| {+ let out = Vec3::new(l.c.x - core.x, (l.c.y - core.y) * 0.6 + 0.3 * l.r, l.c.z - core.z).normalize_or(Vec3::Y);+ // enough bumps to cover the lobe's outer face (each a disc of about half the lobe's radius)+ let m = 12 + (rng.f() * 7.0) as usize;+ let bumps = (0..m)+ .filter_map(|_| {+ let d = (out * 0.9 + rng.unit()).normalize_or(out);+ if d.dot(out) < -0.1 {+ return None;+ }+ let r = l.r * rng.range(0.38, 0.62);+ let c = l.c + Vec3::new(d.x, d.y * l.tall, d.z) * (l.r - r * rng.range(0.2, 0.6));+ Some(Lobe { c, r, tall: l.tall })+ })+ .collect();+ (l, bumps)+ })+ .collect()+}++/// `want` attraction points: in the bumps' outer shells, by their size, few on a lobe's side facing the crown's+/// core (it's shaded); `interior` of them through the big lobes; none under the clear trunk or far out of the+/// envelope.+pub(crate) fn points(sp: &Species, env: &Envelope, crown: &[(Lobe, Vec<Lobe>)], want: usize, rng: &mut Rng) -> Vec<Vec3> {+ let all: Vec<(&Lobe, &Lobe)> = crown.iter().flat_map(|(l, bs)| bs.iter().map(move |b| (l, b))).collect();+ let total: f32 = all.iter().map(|(_, b)| b.r * b.r).sum();+ let core = env.centre();+ let mut pts = Vec::with_capacity(want);+ let mut tries = 0;+ while pts.len() < want && tries < want * 20 && !all.is_empty() {+ tries += 1;+ let mut pick = rng.f() * total;+ let &(big, bump) = all.iter().find(|(_, b)| {+ pick -= b.r * b.r;+ pick <= 0.0+ }).unwrap_or(&all[all.len() - 1]);+ let p = if rng.f() < sp.interior {+ let u = rng.unit() * rng.f().cbrt();+ big.c + Vec3::new(u.x, u.y * big.tall, u.z) * big.r+ } else {+ let u = rng.unit();+ let out = (bump.c - core).normalize_or(Vec3::Y);+ if u.dot(out) < -0.2 && rng.f() < 0.75 {+ continue;+ }+ bump.c + Vec3::new(u.x, u.y * bump.tall, u.z) * bump.r * (1.0 - sp.shell * rng.f())+ };+ let reach = env.r(p.y.clamp(env.base, env.top), p.z.atan2(p.x)).max(0.3);+ if p.y < env.base + 0.2 || p.x.hypot(p.z) > reach * 1.2 + 0.5 || p.y > env.top + 0.5 {+ continue;+ }+ pts.push(p);+ }+ pts+}++/// Each big lobe's scaffold limb: from the frame grown so far (trunk, leader, fork limbs), from the node nearest a+/// point on the axis below the lobe (so limbs leave at about 50 degrees from upright), toward the lobe's centre,+/// turning a little each step, stopping inside it. Returns the new nodes as (position, parent).+pub(crate) fn scaffolds(sp: &Species, crown: &[(Lobe, Vec<Lobe>)], frame: &[Vec3], step: f32, rng: &mut Rng) -> Vec<(Vec3, usize)> {+ let mut out: Vec<(Vec3, usize)> = Vec::new();+ for (l, _) in crown {+ let across = l.c.x.hypot(l.c.z);+ let from = Vec3::new(0.0, l.c.y - across * 0.85, 0.0);+ let Some(start) = (0..frame.len()).filter(|&i| frame[i].y < l.c.y - 0.3 * l.r).min_by(|&a, &b| (frame[a] - from).length().total_cmp(&(frame[b] - from).length())) else {+ continue;+ };+ let (mut p, mut at) = (frame[start], start);+ let mut d = ((l.c - p).normalize_or(Vec3::Y) + Vec3::Y * 0.3).normalize();+ for _ in 0..400 {+ if l.depth(p) < 0.4 {+ break;+ }+ d = (d * 0.75 + (l.c - p).normalize_or(Vec3::Y) * 0.25 + rng.unit() * sp.crook).normalize();+ p += d * step;+ out.push((p, at));+ at = frame.len() + out.len() - 1;+ }+ }+ out+}diff --git a/systems/foliage/src/out.rs b/systems/foliage/src/out.rsnew file mode 100644index 00000000..cfc10893--- /dev/null+++ b/systems/foliage/src/out.rs@@ -0,0 +1,97 @@+//! The plant as one .glb: one node, one mesh, a primitive for the bark and one for each leaf group that has leaves.+//! Materials: "bark" (the species' colour, rough) and "leaf-0" to "leaf-7" over the atlas (alpha mask at 0.1, both+//! sides drawn: the atlas's alpha is a distance, 0.5 on the edge, and the hook cuts at 0.5 near and lower far). A group is hidden by giving its material an opacity of 0 (its shadow goes with it).++use serde_json::{Value, json};++use crate::species::Species;+use crate::{GROUPS, Mesh, Plant};++struct Bin {+ bytes: Vec<u8>,+ views: Vec<Value>,+ accessors: Vec<Value>,+}++impl Bin {+ fn view(&mut self, data: &[u8], target: Option<u32>) -> usize {+ while self.bytes.len() % 4 != 0 {+ self.bytes.push(0);+ }+ let mut v = json!({ "buffer": 0, "byteOffset": self.bytes.len(), "byteLength": data.len() });+ if let Some(t) = target {+ v["target"] = json!(t);+ }+ self.bytes.extend_from_slice(data);+ self.views.push(v);+ self.views.len() - 1+ }+ fn floats<const N: usize>(&mut self, xs: &[[f32; N]], kind: &str, bounds: bool) -> usize {+ let data: Vec<u8> = xs.iter().flat_map(|x| x.iter().flat_map(|f| f.to_le_bytes())).collect();+ let view = self.view(&data, Some(34962));+ let mut a = json!({ "bufferView": view, "componentType": 5126, "count": xs.len(), "type": kind });+ if bounds {+ let lo: Vec<f32> = (0..N).map(|k| xs.iter().map(|x| x[k]).fold(f32::INFINITY, f32::min)).collect();+ let hi: Vec<f32> = (0..N).map(|k| xs.iter().map(|x| x[k]).fold(f32::NEG_INFINITY, f32::max)).collect();+ a["min"] = json!(lo);+ a["max"] = json!(hi);+ }+ self.accessors.push(a);+ self.accessors.len() - 1+ }+ fn indices(&mut self, idx: &[u32]) -> usize {+ let data: Vec<u8> = idx.iter().flat_map(|i| i.to_le_bytes()).collect();+ let view = self.view(&data, Some(34963));+ self.accessors.push(json!({ "bufferView": view, "componentType": 5125, "count": idx.len(), "type": "SCALAR" }));+ self.accessors.len() - 1+ }+ fn primitive(&mut self, m: &Mesh, material: usize) -> Value {+ let mut attrs = json!({+ "POSITION": self.floats(&m.pos, "VEC3", true),+ "NORMAL": self.floats(&m.nrm, "VEC3", false),+ "TEXCOORD_0": self.floats(&m.uv, "VEC2", false),+ });+ if !m.uv1.is_empty() {+ attrs["TEXCOORD_1"] = json!(self.floats(&m.uv1, "VEC2", false));+ }+ if !m.col.is_empty() {+ attrs["COLOR_0"] = json!(self.floats(&m.col, "VEC4", false));+ }+ json!({ "attributes": attrs, "indices": self.indices(&m.idx), "material": material })+ }+}++pub(crate) fn glb(sp: &Species, plant: &Plant, atlas_png: &[u8]) -> Vec<u8> {+ let mut b = Bin { bytes: Vec::new(), views: Vec::new(), accessors: Vec::new() };+ let mut prims = vec![b.primitive(&plant.bark, 0)];+ for (k, m) in plant.leaves.iter().enumerate() {+ if !m.idx.is_empty() {+ prims.push(b.primitive(m, 1 + k));+ }+ }+ let image = b.view(atlas_png, None);+ let [r, g, bl] = sp.bark;+ let mut materials = vec![json!({ "name": "bark", "pbrMetallicRoughness": { "baseColorFactor": [r, g, bl, 1.0], "metallicFactor": 0.0, "roughnessFactor": 0.92 } })];+ for k in 0..GROUPS {+ materials.push(json!({+ "name": format!("leaf-{k}"),+ "pbrMetallicRoughness": { "baseColorTexture": { "index": 0 }, "metallicFactor": 0.0, "roughnessFactor": 0.6 },+ "alphaMode": "MASK", "alphaCutoff": 0.1, "doubleSided": true,+ }));+ }+ let j = json!({+ "asset": { "version": "2.0", "generator": crate::VERSION },+ "scene": 0,+ "scenes": [{ "nodes": [0] }],+ "nodes": [{ "name": sp.id, "mesh": 0 }],+ "meshes": [{ "name": sp.id, "primitives": prims }],+ "materials": materials,+ "images": [{ "bufferView": image, "mimeType": "image/png" }],+ "samplers": [{ "magFilter": 9729, "minFilter": 9987, "wrapS": 33071, "wrapT": 33071 }],+ "textures": [{ "source": 0, "sampler": 0 }],+ "buffers": [{ "byteLength": b.bytes.len() }],+ "bufferViews": b.views,+ "accessors": b.accessors,+ });+ raea_sys_glb::glb_bytes(&j, &b.bytes)+}diff --git a/systems/foliage/src/roots.rs b/systems/foliage/src/roots.rsnew file mode 100644index 00000000..68215bfd--- /dev/null+++ b/systems/foliage/src/roots.rs@@ -0,0 +1,226 @@+//! The tree's foot (docs/foliage.feature FO13): the trunk flares where it meets the ground, ridged toward its+//! structural roots, and on the nearest level the roots run out from it: high where they leave the flare, a low hump+//! along the soil, then down into it.+//!+//! What's measured: a temperate tree has 5-15 structural roots that taper fast within 1-2 m of the trunk (Day et al.+//! 2010, Arboriculture & Urban Forestry 36(4), after Wilson 1964); an urban tree's trunk flare is 1.3-1.9 times its+//! diameter at breast height and its roots show 0.48-0.87 m out from it (Lee 2022, AUF 48(4), the flare after North+//! 2015 and Hilbert 2020). The rest is ASSUMED and named where it's set: how high the flare reaches, the furrows+//! between its ridges, a root's size, how high it stands by the trunk, its section (a buttress taller than wide by+//! the trunk, flattened further out).+//!+//! It draws from a stream of its own, so a level with roots and one without keep the same leaves.++use std::f32::consts::{PI, TAU};++use parry3d::glamx::Vec3;++use crate::grow::Node;+use crate::species::Species;+use crate::tube::{BARK, branches};+use crate::{Mesh, Request, Rng, hash_str};++/// How far the foot goes on under the ground (m), so it meets any ground with no edge showing+const DEPTH: f32 = 0.3;+/// How steeply a root dives once it's under the soil (m down a metre out)+const DIVE: f32 = 0.8;++struct Root {+ a: f32,+ size: f32,+}++/// One root to draw: from `start` (on the ground) along `heading` (radians round y, as the flare's angle), `r0`+/// thick, its top `t0` above the soil where it starts and meeting the soil `show` metres out.+struct Run {+ start: Vec3,+ heading: f32,+ r0: f32,+ t0: f32,+ show: f32,+}++/// The foot onto the bark: the flare on every level, the roots on the nearest (a request with no pruning).+pub(crate) fn foot(sp: &Species, req: &Request, nodes: &[Node], m: &mut Mesh) {+ let Some(trunk) = branches(nodes).into_iter().next() else { return };+ if trunk.len() < 2 || sp.roots == 0 {+ return;+ }+ let mut rng = Rng::new(req.seed ^ hash_str(sp.id) ^ hash_str("roots"));+ let n = sp.roots as usize;+ let roots: Vec<Root> = (0..n).map(|i| Root { a: TAU * (i as f32 + rng.range(-0.3, 0.3)) / n as f32, size: rng.range(0.55, 1.0) }).collect();+ flare(sp, req, nodes, &trunk, &roots, m);+ if req.prune > 0.0 {+ return;+ }+ let r_dbh = nodes[trunk[0]].r;+ let (c, _) = along_trunk(nodes, &trunk, 0.0);+ let mut forks = vec![];+ for root in &roots {+ let dir = Vec3::new(root.a.cos(), 0.0, -root.a.sin());+ let surf = (sp.surface * rng.range(0.6, 1.4)).clamp(0.05, 0.7);+ // half the trunk's radius at its biggest (ASSUMED); its top stands up to twice its own half-height by the+ // trunk on the species that show their roots most (ASSUMED); it meets the soil 1.6-3 trunk radii out, longer+ // on those species (0.5-0.9 m on a 0.32 m radius, Lee 2022's range)+ let r0 = 0.5 * r_dbh * root.size;+ let tall0 = r0 * ASPECT.0.sqrt();+ let run = Run {+ start: Vec3::new(c.x, 0.0, c.z) + dir * (0.5 * r_dbh),+ heading: root.a,+ r0,+ t0: (3.0 * surf * tall0).min(2.0 * tall0),+ show: (r_dbh * (1.6 + 1.4 * root.size) * (0.55 + surf) * rng.range(0.85, 1.15)).clamp(0.25, 1.4),+ };+ let fork = draw(m, &run, &mut rng);+ if root.size > 0.75 {+ forks.push(fork);+ }+ }+ // a big root forks once on its way out, the fork thinner and under the soil sooner+ for f in forks {+ let turn = if rng.f() < 0.5 { -1.0 } else { 1.0 } * rng.range(0.5, 0.9);+ draw(m, &Run { heading: f.heading + turn, r0: 0.6 * f.r0, show: f.show * rng.range(0.5, 0.8), ..f }, &mut rng);+ }+}++/// A root's section, height over width: where it leaves the trunk and where it meets the soil (ASSUMED)+const ASPECT: (f32, f32) = (1.8, 0.8);++/// One root: it halves its radius by where it meets the soil (ASSUMED, inside Day et al.'s fast taper), its top falls+/// steeply off the flare, runs low along the soil and goes under at `show`, then dives. It wanders a little. Returns+/// where a fork leaves it (two fifths of the way to the soil) with what's left of it there.+fn draw(m: &mut Mesh, r: &Run, rng: &mut Rng) -> Run {+ let len = r.show + 0.35;+ let steps = ((len / 0.05).ceil() as usize).clamp(6, 40);+ let x = |d: f32| (d / r.show).clamp(0.0, 1.4);+ let rad = |d: f32| r.r0 * (1.0 - 0.5 * x(d));+ let aspect = |d: f32| ASPECT.0 + (ASPECT.1 - ASPECT.0) * x(d).min(1.0);+ let tall = |d: f32| rad(d) * aspect(d).sqrt();+ let top = |d: f32| {+ let u = 1.0 - (d / r.show).min(1.0);+ r.t0 * (0.65 * u.powi(3) + 0.35 * u.powf(0.7)) - DIVE * (d - r.show).max(0.0)+ };+ let mut path = Vec::with_capacity(steps + 1);+ let (mut p, mut h) = (r.start, r.heading);+ for k in 0..=steps {+ let d = len * k as f32 / steps as f32;+ path.push((Vec3::new(p.x, top(d) - tall(d), p.z), d, h));+ h += rng.range(-1.0, 1.0) * 0.07;+ p += Vec3::new(h.cos(), 0.0, -h.sin()) * (len / steps as f32);+ }+ let sides = ((r.r0 * 40.0).round() as usize + 5).clamp(6, 12);+ let rep = (TAU * r.r0 / BARK).round().max(1.0);+ let mut along = 0.0;+ let at = (0.4 * r.show / len * steps as f32).round() as usize;+ let mut fork = Run { start: r.start, heading: r.heading, r0: r.r0, t0: r.t0, show: r.show };+ for (k, &(c, d, h)) in path.iter().enumerate() {+ let prev = path[k.saturating_sub(1)].0;+ let next = path[(k + 1).min(steps)].0;+ let t = (next - prev).normalize_or_zero();+ let up = (Vec3::Y - t * t.y).normalize_or_zero();+ let side = t.cross(up);+ if k > 0 {+ along += (c - prev).length();+ }+ if k == at {+ fork = Run { start: Vec3::new(c.x, 0.0, c.z), heading: h, r0: rad(d), t0: top(d), show: r.show - d };+ }+ let (rh, rw) = (tall(d), rad(d) / aspect(d).sqrt());+ let base = m.pos.len() as u32;+ for s in 0..=sides {+ let a = TAU * s as f32 / sides as f32;+ let q = c + up * (a.cos() * rh) + side * (a.sin() * rw);+ let n = (up * (a.cos() / rh) + side * (a.sin() / rw)).normalize_or_zero();+ m.pos.push(q.to_array());+ m.nrm.push(n.to_array());+ m.uv.push([rep * s as f32 / sides as f32, along / BARK]);+ m.uv1.push([rep, rad(d)]);+ }+ if k > 0 {+ quads(m, base - (sides as u32 + 1), base, sides as u32);+ }+ }+ fork+}++/// The trunk's centre and its tube's radius at height `y` (below the foot, straight down from it), as tube.rs rings it.+fn along_trunk(nodes: &[Node], trunk: &[usize], y: f32) -> (Vec3, f32) {+ let ring = |k: usize| if k == 0 && nodes[trunk[0]].r > nodes[trunk[1]].r { nodes[trunk[1]].r } else { nodes[trunk[k]].r };+ let foot = nodes[trunk[0]].p;+ if y <= foot.y {+ return (Vec3::new(foot.x, y, foot.z), ring(0));+ }+ for k in 1..trunk.len() {+ let (a, b) = (nodes[trunk[k - 1]].p, nodes[trunk[k]].p);+ if b.y >= y {+ let t = ((y - a.y) / (b.y - a.y).max(1e-6)).clamp(0.0, 1.0);+ return (a + (b - a) * t, ring(k - 1) + (ring(k) - ring(k - 1)) * t);+ }+ }+ let k = trunk.len() - 1;+ (nodes[trunk[k]].p, ring(k))+}++/// The flare: rings from under the ground to where it's the trunk again, its radius the trunk's grown by the species'+/// flare at the ground and falling off with height, ridged toward each root.+fn flare(sp: &Species, req: &Request, nodes: &[Node], trunk: &[usize], roots: &[Root], m: &mut Mesh) {+ let r_dbh = nodes[trunk[0]].r;+ let (sides, rings) = if req.prune <= 0.0 { (40, 16) } else if req.prune < 0.05 { (18, 8) } else { (10, 5) };+ // the flare falls to 1/e of itself in 0.15 m + 0.6 of the trunk's radius (0.34 m on a 0.32 m radius), ASSUMED,+ // and ends where it's under 3% of that+ let h = 0.15 + 0.6 * r_dbh;+ let top = 3.5 * h;+ let fall = |y: f32| (((-y.max(0.0) / h).exp() - (-top / h).exp()) / (1.0 - (-top / h).exp())).max(0.0);+ // a ridge toward each root, the furrows between at 0.3 of a ridge (ASSUMED), averaging 1 round the trunk; the+ // ridges are sharper low down, where they become the roots+ let ridge = |a: f32, y: f32| {+ let width = (0.22 + 0.25 * (y.max(0.0) / top)) * TAU / roots.len() as f32;+ let s: f32 = roots.iter().map(|r| {+ let d = (a - r.a + PI).rem_euclid(TAU) - PI;+ r.size * (-(d / width).powi(2)).exp()+ }).sum();+ 0.3 + 0.7 * s.min(1.2)+ };+ // its top sits just inside the trunk's tube, whose faces are its rings' chords+ let st = ((r_dbh * 40.0).round() as usize + 3).clamp(3, 14);+ let inset = (PI / st as f32).cos();+ let rep = (TAU * r_dbh / BARK).round().max(1.0);+ let mut grid = Vec::with_capacity((rings + 1) * (sides + 1));+ let mut ys = Vec::with_capacity(rings + 1);+ for j in 0..=rings {+ // one ring under the ground, the rest closest where the flare turns fastest+ let y = if j == 0 { -DEPTH } else { top * ((j - 1) as f32 / (rings - 1) as f32).powf(1.6) };+ let (c, rt) = along_trunk(nodes, trunk, y);+ let mean = (0..90).map(|i| ridge(TAU * i as f32 / 90.0, y)).sum::<f32>() / 90.0;+ for s in 0..=sides {+ let a = TAU * s as f32 / sides as f32;+ let out = Vec3::new(a.cos(), 0.0, -a.sin());+ grid.push(c + out * rt * (inset + (sp.flare - inset) * fall(y) * ridge(a, y) / mean));+ }+ ys.push(y);+ }+ let at = |j: usize, s: usize| grid[j * (sides + 1) + s];+ let base = m.pos.len() as u32;+ for j in 0..=rings {+ for s in 0..=sides {+ let around = at(j, (s + 1) % sides) - at(j, (s + sides - 1) % sides);+ let up = at((j + 1).min(rings), s) - at(j.saturating_sub(1), s);+ let n = around.cross(up).normalize_or_zero();+ m.pos.push(at(j, s).to_array());+ m.nrm.push(if n == Vec3::ZERO { [0.0, 1.0, 0.0] } else { n.to_array() });+ m.uv.push([rep * s as f32 / sides as f32, ys[j] / BARK]);+ m.uv1.push([rep, r_dbh]);+ }+ if j > 0 {+ quads(m, base + ((j - 1) * (sides + 1)) as u32, base + (j * (sides + 1)) as u32, sides as u32);+ }+ }+}++/// The quads between two rings of `sides` + 1 vertices, wound as tube.rs winds them.+fn quads(m: &mut Mesh, lo: u32, hi: u32, sides: u32) {+ for s in 0..sides {+ let (a, b, c, d) = (lo + s, lo + s + 1, hi + s, hi + s + 1);+ m.idx.extend_from_slice(&[a, b, c, b, d, c]);+ }+}diff --git a/systems/foliage/src/shape.rs b/systems/foliage/src/shape.rsnew file mode 100644index 00000000..b1b3e31d--- /dev/null+++ b/systems/foliage/src/shape.rs@@ -0,0 +1,62 @@+//! A plant seen from the side as a mask (docs/foliage.feature FO12): its leaves through the atlas's alpha and its+//! bark's triangles, white on black, the ground at the bottom row. The project's crown check measures this and+//! photographs of real trees the same way (outline against its hull, sky inside), so a crown is held to real ones.++use image::{GrayImage, Luma, RgbaImage};++use crate::{Plant, Request, atlas, species};++/// The side view from `bearing` (radians round the trunk), `px` tall.+pub fn silhouette(req: &Request, plant: &Plant, px: u32, bearing: f32) -> Result<GrayImage, String> {+ let sp = species(&req.species).ok_or("no species")?;+ let sheet = atlas(sp, req.seed);+ let (c, s) = (bearing.cos(), bearing.sin());+ let flat = |p: [f32; 3]| (p[0] * c + p[2] * s, p[1]);+ let all = || std::iter::once(&plant.bark).chain(&plant.leaves).flat_map(|m| m.pos.iter().map(|&p| flat(p)));+ let (x0, x1) = all().fold((f32::INFINITY, f32::NEG_INFINITY), |(a, b), (x, _)| (a.min(x), b.max(x)));+ let top = all().fold(0.0f32, |a, (_, y)| a.max(y));+ let scale = (px as f32 - 4.0) / top.max(1e-3);+ let mut img = GrayImage::new(((x1 - x0) * scale) as u32 + 5, px);+ let to = |p: [f32; 3]| {+ let (x, y) = flat(p);+ ((x - x0) * scale + 2.0, px as f32 - 2.0 - y * scale)+ };+ for (k, m) in std::iter::once(&plant.bark).chain(&plant.leaves).enumerate() {+ for t in m.idx.chunks_exact(3) {+ let v = [t[0] as usize, t[1] as usize, t[2] as usize];+ let uv = (k > 0).then(|| v.map(|i| m.uv[i]));+ fill(&mut img, v.map(|i| to(m.pos[i])), uv, &sheet);+ }+ }+ Ok(img)+}++fn fill(img: &mut GrayImage, t: [(f32, f32); 3], uv: Option<[[f32; 2]; 3]>, sheet: &RgbaImage) {+ let area = (t[1].0 - t[0].0) * (t[2].1 - t[0].1) - (t[2].0 - t[0].0) * (t[1].1 - t[0].1);+ if area.abs() < 1e-9 {+ return;+ }+ let (w, h) = (img.width() as i32, img.height() as i32);+ let lo = |f: fn(&(f32, f32)) -> f32| t.iter().map(f).fold(f32::INFINITY, f32::min).floor() as i32;+ let hi = |f: fn(&(f32, f32)) -> f32| t.iter().map(f).fold(f32::NEG_INFINITY, f32::max).ceil() as i32;+ for y in lo(|p| p.1).max(0)..=hi(|p| p.1).min(h - 1) {+ for x in lo(|p| p.0).max(0)..=hi(|p| p.0).min(w - 1) {+ let (px, py) = (x as f32 + 0.5, y as f32 + 0.5);+ let w0 = ((t[1].0 - px) * (t[2].1 - py) - (t[2].0 - px) * (t[1].1 - py)) / area;+ let w1 = ((t[2].0 - px) * (t[0].1 - py) - (t[0].0 - px) * (t[2].1 - py)) / area;+ let w2 = 1.0 - w0 - w1;+ if w0 < 0.0 || w1 < 0.0 || w2 < 0.0 {+ continue;+ }+ if let Some(uv) = uv {+ let u = w0 * uv[0][0] + w1 * uv[1][0] + w2 * uv[2][0];+ let v = w0 * uv[0][1] + w1 * uv[1][1] + w2 * uv[2][1];+ let (sw, sh) = (sheet.width() as f32, sheet.height() as f32);+ if sheet.get_pixel((u * sw).clamp(0.0, sw - 1.0) as u32, (v * sh).clamp(0.0, sh - 1.0) as u32)[3] < 128 {+ continue;+ }+ }+ img.put_pixel(x as u32, y as u32, Luma([255]));+ }+ }+}diff --git a/systems/foliage/src/species.rs b/systems/foliage/src/species.rsnew file mode 100644index 00000000..974ae49e--- /dev/null+++ b/systems/foliage/src/species.rs@@ -0,0 +1,167 @@+//! The species (docs/foliage.feature FO4): each a row of numbers. Leaf sizes and crown habits follow the floras'+//! descriptions; the growth numbers (step, reach, kill, points, tropism) are tuned by eye against photographs and are+//! ASSUMED until a species' sheet beside its photographs says otherwise (FO12).++/// A leaf's outline rules (atlas.rs).+#[derive(Clone, Copy, Debug, PartialEq, Eq)]+pub enum LeafKind {+ /// heart-shaped, oblique, finely toothed: lime+ Cordate,+ /// egg-shaped, lopsided base, double-toothed: elm+ Ovate,+ /// long and narrow: willow+ Lanceolate,+ /// broad-based, pointed, double-toothed: birch+ Triangular,+ /// diamond: poplar+ Rhombic,+ /// rounded lobes, small ears at the base: oak+ Oak,+ /// five pointed lobes with few big teeth: Norway maple+ Palmate,+ /// three to five broad lobes, coarse teeth: plane+ Plane,+ /// five to seven leaflets from one point: horse chestnut+ Compound,+ /// leaflets in pairs along a stalk: black locust+ Pinnate,+}++#[derive(Clone, Debug)]+pub struct Species {+ pub id: &'static str,+ pub name: &'static str,+ /// the crown: where it's widest (0 its base, 1 its top), its squareness (2 an ellipse), the leafy shell's depth+ /// (of the radius), how lumpy it is, height over width when only a width is known (the median of Berlin's trees+ /// of 50 years or more in the Baumbestand, dl-de/zero-2.0; the poplar's is a Lombardy's, ASSUMED), trunk radius a+ /// metre of height+ pub widest: f32,+ pub square: f32,+ /// the squareness below the widest point (1 a cone, an elm's vase; 3 a skirt, a chestnut's)+ pub low: f32,+ pub shell: f32,+ pub lumps: f32,+ pub height_per_width: f32,+ pub trunk: f32,+ /// growth: step (m), reach and kill (in steps), attraction points a cubic metre of shell, the share of points+ /// kept inside the shell, tropism up (+) or down (-), droop of thin shoots (radians a metre at a twig's radius),+ /// a tip's radius (the pipe model is fitted to it and the trunk), twigs sprouted a tip and their length (m)+ pub step: f32,+ pub reach: f32,+ pub kill: f32,+ pub points: f32,+ pub interior: f32,+ pub up: f32,+ pub droop: f32,+ pub tip: f32,+ pub twigs: f32,+ pub twig_len: f32,+ /// leaves: kind, length (m, with its stalk), width over length, leaf area index (leaf area over the crown's ground area; ASSUMED typical values), how far back from a+ /// tip shoots carry leaves (m), how much a leaf hangs+ pub leaf: LeafKind,+ pub leaf_len: f32,+ pub aspect: f32,+ pub lai: f32,+ pub leafy: f32,+ pub leaf_droop: f32,+ /// leaves drawn on one card (a sprig: a twig with its leaves), and whether they grow in opposite pairs+ pub sprig: u32,+ pub opposite: bool,+ /// how much of the crown is sky holes between clumps of foliage (ASSUMED by eye)+ pub gaps: f32,+ /// architecture: how far up the crown the trunk carries on as a leader (0 to 1), and how many big limbs it forks+ /// into there (0: none; elms, oaks and willows fork, poplars and birches keep a leader)+ pub leader: f32,+ pub forks: u32,+ /// the crown's masses: how many big lobes it is (each on a scaffold limb from the trunk, for a 10 m crown; more+ /// on a bigger one), their radius (of the crown's), how crooked the limbs grow (a step's random turn) and how far+ /// the crown leans off its trunk (of its radius): a real crown is a few clouds with sky between, not one ball+ pub lobes: f32,+ pub lobe: f32,+ pub crook: f32,+ pub skew: f32,+ /// bark: linear colour, and its pattern (0 fissured, 1 a plane's flakes, 2 a birch's white, 3 a locust's ropes)+ pub bark: [f32; 3],+ pub bark_kind: u32,+ /// the foot (roots.rs): the trunk's flare, its diameter at the ground over its diameter at breast height (1.3-1.9+ /// on urban trees, North 2015 and Hilbert 2020 as cited by Lee 2022, AUF 48(4)); its structural roots (5-15,+ /// Day et al. 2010 after Wilson 1964); and how much of a root's height shows above the soil by the trunk (0 none,+ /// 1 all), higher for the species known for surface roots (maple, plane, elm and willow, WSU Extension C137; birch,+ /// Forest Research) and lower for oak and lime, which C137 names as good choices. Each species' values ASSUMED+ /// inside those ranges.+ pub flare: f32,+ pub roots: u32,+ pub surface: f32,+}++const fn sp(id: &'static str, name: &'static str) -> Species {+ Species {+ id,+ name,+ widest: 0.45,+ square: 2.2,+ low: 2.2,+ shell: 0.38,+ lumps: 0.15,+ height_per_width: 1.4,+ trunk: 0.021,+ step: 0.24,+ reach: 13.0,+ kill: 2.5,+ points: 20.0,+ interior: 0.35,+ up: 0.3,+ droop: 0.08,++ tip: 0.003,+ twigs: 2.0,+ twig_len: 0.45,+ leaf: LeafKind::Cordate,+ leaf_len: 0.09,+ aspect: 1.0,+ lai: 5.0,+ leafy: 0.9,+ leaf_droop: 0.1,+ sprig: 5,+ opposite: false,+ gaps: 0.3,+ leader: 0.4,+ forks: 0,+ lobes: 7.0,+ lobe: 0.5,+ crook: 0.12,+ skew: 0.08,+ bark: [0.18, 0.16, 0.14],+ bark_kind: 0,+ flare: 1.5,+ roots: 7,+ surface: 0.3,+ }+}++pub static ALL: [Species; 10] = [+ // small-leaved lime: a dense ovoid of ascending limbs, red-brown twigs, leaves 3-10 cm, heart-shaped and oblique+ Species { widest: 0.42, square: 1.7, low: 2.0, lumps: 0.2, height_per_width: 1.39, trunk: 0.02, step: 0.22, reach: 14.0, kill: 2.6, points: 22.5, up: 0.35, droop: 0.05, twigs: 2.5, leaf_len: 0.085, aspect: 0.95, lai: 7.0, sprig: 7, leader: 0.55, forks: 0, lobes: 13.0, lobe: 0.4, crook: 0.1, skew: 0.06, gaps: 0.12, leafy: 1.4, flare: 1.5, roots: 9, surface: 0.2, ..sp("lime", "Tilia cordata") },+ // field and fluttering elm: a broad vase, widest high, leaves 6-12 cm, lopsided at the base+ Species { widest: 0.62, square: 2.4, low: 1.1, shell: 0.32, lumps: 0.2, height_per_width: 1.92, trunk: 0.022, step: 0.25, reach: 14.0, kill: 2.4, points: 17.5, up: 0.55, droop: 0.12, twigs: 2.2, twig_len: 0.5, leaf: LeafKind::Ovate, leaf_len: 0.1, aspect: 0.62, lai: 5.0, leafy: 1.2, sprig: 7, leader: 0.15, forks: 3, gaps: 0.2, bark: [0.17, 0.15, 0.13], lobes: 6.0, lobe: 0.52, crook: 0.16, skew: 0.12, flare: 1.8, roots: 7, surface: 0.45, ..sp("elm", "Ulmus minor") },+ // London plane: a broad dome on big limbs, 20-30 m by 15-20 m (berlin.de), leaves 12-25 cm, flaking bark+ Species { widest: 0.45, square: 2.6, low: 2.2, shell: 0.35, lumps: 0.18, height_per_width: 1.15, trunk: 0.025, step: 0.3, reach: 13.0, kill: 2.5, points: 15.0, up: 0.2, droop: 0.08, twigs: 1.6, twig_len: 0.5, leaf: LeafKind::Plane, leaf_len: 0.2, aspect: 1.1, lai: 5.5, leafy: 1.3, sprig: 2, leader: 0.3, forks: 3, gaps: 0.12, bark: [0.42, 0.40, 0.32], bark_kind: 1, lobes: 6.0, lobe: 0.52, crook: 0.22, skew: 0.12, flare: 1.7, roots: 8, surface: 0.45, ..sp("plane", "Platanus x acerifolia") },+ // Norway maple: round and dense, leaves 10-15 cm with five to seven pointed lobes+ Species { widest: 0.45, square: 2.4, low: 2.4, shell: 0.4, lumps: 0.1, height_per_width: 1.42, trunk: 0.021, step: 0.22, reach: 13.0, kill: 2.5, points: 22.5, up: 0.3, droop: 0.05, twigs: 2.0, twig_len: 0.4, leaf: LeafKind::Palmate, leaf_len: 0.13, aspect: 1.15, lai: 6.0, leafy: 1.3, sprig: 4, leader: 0.35, forks: 0, gaps: 0.1, opposite: true, bark: [0.22, 0.21, 0.19], lobes: 11.0, lobe: 0.43, crook: 0.12, skew: 0.07, flare: 1.6, roots: 8, surface: 0.45, ..sp("maple", "Acer platanoides") },+ // horse chestnut: a broad dome, lower limbs sweeping down and up at the tips, leaves of 5-7 leaflets 10-25 cm+ Species { widest: 0.4, square: 2.2, low: 3.0, shell: 0.42, lumps: 0.12, height_per_width: 1.27, trunk: 0.024, step: 0.25, reach: 13.0, kill: 2.5, points: 20.0, up: 0.05, droop: 0.35, twigs: 1.4, twig_len: 0.35, leaf: LeafKind::Compound, leaf_len: 0.32, aspect: 1.1, lai: 7.0, leafy: 1.1, sprig: 1, leader: 0.3, forks: 0, gaps: 0.06, leaf_droop: 0.35, bark: [0.25, 0.22, 0.19], lobes: 9.0, lobe: 0.46, crook: 0.12, skew: 0.08, flare: 1.5, roots: 7, surface: 0.3, ..sp("chestnut", "Aesculus hippocastanum") },+ // black locust: open and irregular, leaves 15-30 cm of 9-19 leaflets, deep rope-like bark+ Species { widest: 0.55, square: 1.8, low: 1.6, shell: 0.3, lumps: 0.3, height_per_width: 1.89, trunk: 0.02, step: 0.3, reach: 12.0, kill: 2.2, points: 12.5, up: 0.4, droop: 0.08, twigs: 1.2, twig_len: 0.5, leaf: LeafKind::Pinnate, leaf_len: 0.25, aspect: 0.6, lai: 3.0, leafy: 1.0, sprig: 2, leader: 0.3, forks: 2, gaps: 0.35, leaf_droop: 0.25, bark: [0.27, 0.24, 0.2], bark_kind: 3, lobes: 5.0, lobe: 0.5, crook: 0.3, skew: 0.16, flare: 1.4, roots: 6, surface: 0.3, ..sp("locust", "Robinia pseudoacacia") },+ // pedunculate oak: broad, on crooked limbs, leaves 7-14 cm with rounded lobes+ Species { widest: 0.5, square: 3.2, low: 2.0, shell: 0.32, lumps: 0.3, height_per_width: 1.5, trunk: 0.028, step: 0.3, reach: 12.0, kill: 2.3, points: 15.0, up: 0.15, droop: 0.05, twigs: 1.8, twig_len: 0.4, leaf: LeafKind::Oak, leaf_len: 0.11, aspect: 0.62, lai: 5.0, leafy: 1.0, sprig: 6, leader: 0.15, forks: 4, gaps: 0.32, bark: [0.2, 0.18, 0.15], lobes: 6.0, lobe: 0.5, crook: 0.35, skew: 0.15, flare: 1.6, roots: 6, surface: 0.2, ..sp("oak", "Quercus robur") },+ // silver birch: narrow, its twigs hanging, leaves 3-7 cm, white bark+ Species { widest: 0.4, square: 1.6, low: 1.6, shell: 0.35, height_per_width: 1.71, trunk: 0.014, step: 0.2, reach: 14.0, kill: 2.6, points: 17.5, up: 0.45, droop: 0.45, twigs: 3.0, twig_len: 0.6, leaf: LeafKind::Triangular, leaf_len: 0.055, aspect: 0.75, lai: 3.5, leafy: 1.2, sprig: 9, leader: 0.75, forks: 0, gaps: 0.28, leaf_droop: 0.2, bark: [0.75, 0.74, 0.7], bark_kind: 2, lobes: 9.0, lobe: 0.42, crook: 0.12, skew: 0.1, flare: 1.3, roots: 7, surface: 0.4, ..sp("birch", "Betula pendula") },+ // Lombardy poplar: a column, leaves 5-10 cm, diamond-shaped+ Species { widest: 0.3, square: 1.4, low: 1.5, shell: 0.5, lumps: 0.08, height_per_width: 4.5, trunk: 0.018, step: 0.22, reach: 10.0, kill: 2.4, points: 25.0, up: 2.4, droop: 0.0, twigs: 2.0, twig_len: 0.35, leaf: LeafKind::Rhombic, leaf_len: 0.07, aspect: 0.9, lai: 3.5, leafy: 0.8, sprig: 7, leader: 0.85, forks: 0, gaps: 0.12, bark: [0.24, 0.23, 0.2], lobes: 8.0, lobe: 0.55, crook: 0.05, skew: 0.03, flare: 1.6, roots: 8, surface: 0.4, ..sp("poplar", "Populus nigra 'Italica'") },+ // white willow: broad, its twigs hanging by the water, leaves 5-12 cm, narrow+ Species { widest: 0.5, square: 2.4, low: 1.4, shell: 0.4, lumps: 0.2, height_per_width: 1.19, trunk: 0.03, step: 0.25, reach: 13.0, kill: 2.4, points: 17.5, up: 0.3, droop: 0.7, twigs: 3.0, twig_len: 0.8, leaf: LeafKind::Lanceolate, leaf_len: 0.09, aspect: 0.3, lai: 3.5, leafy: 1.6, sprig: 9, leader: 0.1, forks: 3, leaf_droop: 0.3, bark: [0.24, 0.22, 0.19], lobes: 6.0, lobe: 0.5, crook: 0.2, skew: 0.12, gaps: 0.22, flare: 1.7, roots: 9, surface: 0.5, ..sp("willow", "Salix alba") },+];++pub fn species(id: &str) -> Option<&'static Species> {+ ALL.iter().find(|s| s.id == id)+}diff --git a/systems/foliage/src/tests.rs b/systems/foliage/src/tests.rsnew file mode 100644index 00000000..c14c2209--- /dev/null+++ b/systems/foliage/src/tests.rs@@ -0,0 +1,177 @@+//! Trees checked by number: a lime fills its crown and keeps its trunk clear, radii thin toward the tips, leaves split+//! evenly into their groups, every leaf kind draws a leaf (a lime's with its notch), and the same request gives the+//! same bytes. `grow_files` (ignored) grows a list of requests to .glb files: RAEA_FOLIAGE_REQ a JSON list of+//! { id, species, height, width, clear, seed, leaves }, RAEA_FOLIAGE_OUT the folder.++use crate::species::ALL;+use crate::{CELLS, GROUPS, Request, atlas, glb, grow};++fn lime() -> Request {+ Request { species: "lime".into(), height: 16.0, width: 10.0, clear: 3.5, seed: 1, leaves: 30_000, prune: 0.0 }+}++#[test]+fn a_lime_fills_its_crown_and_keeps_its_trunk_clear() {+ let req = lime();+ let t = grow(&req).unwrap();+ let top = t.nodes.iter().map(|n| n.p.y).fold(0.0, f32::max);+ // its width as a crown is measured: the spread across it, averaged over bearings (a lobe may reach further)+ let spread = |a: f32| {+ let d = (a.cos(), a.sin());+ let s = t.nodes.iter().map(|n| n.p.x * d.0 + n.p.z * d.1);+ s.clone().fold(f32::MIN, f32::max) - s.fold(f32::MAX, f32::min)+ };+ let across = (0..8).map(|k| spread(std::f32::consts::PI * k as f32 / 8.0)).sum::<f32>() / 8.0;+ let wide = t.nodes.iter().map(|n| n.p.x.hypot(n.p.z)).fold(0.0, f32::max);+ assert!(top > 0.85 * req.height && top < 1.15 * req.height, "top {top}");+ assert!(across > 0.8 * req.width && across < 1.2 * req.width, "spread {across} for a width of {}", req.width);+ assert!(wide < 0.8 * req.width, "half-width {wide}");+ for n in t.nodes.iter().filter(|n| n.p.y < req.clear * 0.9) {+ assert!(n.p.x.hypot(n.p.z) < 0.5, "only the trunk below the crown: {:?}", n.p);+ }+ for m in &t.leaves {+ assert!(m.pos.iter().all(|p| p[1] > req.clear * 0.8), "no leaves on the clear trunk");+ }+ assert!((t.nodes[0].r - 0.02 * req.height).abs() < 1e-3, "the trunk's foot: {}", t.nodes[0].r);+ for n in t.nodes.iter().skip(1) {+ assert!(n.r <= t.nodes[n.parent].r + 1e-6, "radii thin toward the tips");+ }+ println!("lime: spread {across:.1} m, {} nodes, {} bark triangles, {} leaves", t.nodes.len(), t.bark.tris(), t.leaf_count());+}++#[test]+fn leaves_split_evenly_into_their_groups_within_the_budget() {+ let req = Request { leaves: 3_000, ..lime() };+ let t = grow(&req).unwrap();+ let all = t.leaf_count() as f32;+ assert!(all > 0.5 * req.leaves as f32 && all < 1.1 * req.leaves as f32, "{all} leaves for a budget of {}", req.leaves);+ for (k, m) in t.leaves.iter().enumerate() {+ let share = (m.idx.len() / 6) as f32 / all;+ assert!((share - 1.0 / GROUPS as f32).abs() < 0.04, "group {k}: {share}");+ }+}++#[test]+fn every_leaf_kind_draws_a_leaf() {+ for sp in &ALL {+ let img = atlas(sp, 3);+ for cell in [0, CELLS * CELLS - 1] {+ let c = crate::atlas::coverage(&img, cell);+ assert!(c > 0.06 && c < 0.75, "{}: cell {cell} covers {c}", sp.id);+ }+ }+ let lime = crate::atlas::leaf_at(crate::LeafKind::Cordate);+ assert!(lime(0.0, 0.19) < 0.0, "a lime's blade has its notch where the stalk meets it");+ assert!(lime(0.15, 0.3) > 0.0, "and its lobes either side");+ let sp = crate::species("lime").unwrap();+ assert!(crate::atlas::covers(sp, &atlas(sp, 3), 0, 0.0, 0.3), "a lime's sprig has its twig up the middle");+}++#[test]+fn the_same_request_gives_the_same_bytes_and_a_glb_with_its_groups() {+ let req = Request { leaves: 4_000, ..lime() };+ let (a, b) = (glb(&req, &grow(&req).unwrap()).unwrap(), glb(&req, &grow(&req).unwrap()).unwrap());+ assert_eq!(a, b);+ let g = raea_sys_glb::parse(&a).unwrap();+ let names: Vec<&str> = raea_sys_glb::arr(&g.json, "materials").iter().filter_map(|m| m["name"].as_str()).collect();+ assert_eq!(names, ["bark", "leaf-0", "leaf-1", "leaf-2", "leaf-3", "leaf-4", "leaf-5", "leaf-6", "leaf-7"]);+ assert_eq!(g.json["meshes"][0]["primitives"].as_array().unwrap().len(), 1 + GROUPS);+}++#[test]+fn every_species_grows() {+ for sp in &ALL {+ let req = Request { species: sp.id.into(), height: 12.0, width: 12.0 / sp.height_per_width, clear: 2.5, seed: 7, leaves: 3_000, prune: 0.0 };+ let t = grow(&req).unwrap();+ assert!(t.nodes.len() > 200 && t.leaf_count() > 500, "{}: {} nodes, {} leaves", sp.id, t.nodes.len(), t.leaf_count());+ }+}++#[test]+#[ignore]+fn grow_files() {+ let req = std::env::var("RAEA_FOLIAGE_REQ").expect("RAEA_FOLIAGE_REQ");+ let out = std::path::PathBuf::from(std::env::var("RAEA_FOLIAGE_OUT").expect("RAEA_FOLIAGE_OUT"));+ std::fs::create_dir_all(&out).unwrap();+ let list: Vec<serde_json::Value> = serde_json::from_slice(&std::fs::read(req).unwrap()).unwrap();+ for r in list {+ let req = Request {+ species: r["species"].as_str().unwrap().into(),+ height: r["height"].as_f64().unwrap() as f32,+ width: r["width"].as_f64().unwrap() as f32,+ clear: r["clear"].as_f64().unwrap() as f32,+ seed: r["seed"].as_u64().unwrap_or(1),+ leaves: r["leaves"].as_u64().unwrap_or(40_000) as u32,+ prune: r["prune"].as_f64().unwrap_or(0.0) as f32,+ };+ let t0 = std::time::Instant::now();+ let t = grow(&req).unwrap();+ let ms = t0.elapsed().as_millis();+ let bytes = glb(&req, &t).unwrap();+ let id = r["id"].as_str().unwrap();+ std::fs::write(out.join(format!("{id}.glb")), &bytes).unwrap();+ atlas(crate::species(&req.species).unwrap(), req.seed).save(out.join(format!("{id}-atlas.png"))).unwrap();+ println!("{id}: {} nodes, {} bark triangles, {} leaves, grown in {ms} ms, {} KB", t.nodes.len(), t.bark.tris(), t.leaf_count(), bytes.len() / 1024);+ }+}++#[test]+fn a_pruned_level_drops_its_twigs_and_keeps_its_leaves() {+ let full = Request { leaves: 4_000, ..lime() };+ let far = Request { prune: 0.03, ..full.clone() };+ let (a, b) = (grow(&full).unwrap(), grow(&far).unwrap());+ assert!(b.bark.tris() * 4 < a.bark.tris(), "pruned bark {} against {}", b.bark.tris(), a.bark.tris());+ assert_eq!(a.leaf_count(), b.leaf_count(), "the same leaves");+}++#[test]+fn a_trunk_flares_at_the_ground_and_its_roots_sink_into_it() {+ let sp = crate::species("lime").unwrap();+ let near = Request { leaves: 2_000, ..lime() };+ let far = Request { prune: 0.03, ..near.clone() };+ let (a, b) = (grow(&near).unwrap(), grow(&far).unwrap());+ let r = a.nodes[0].r;+ let out = |p: &[f32; 3]| p[0].hypot(p[2]);+ // the flare at the ground, on the level without roots: its ring averages the species' flare+ let ring: Vec<f32> = b.bark.pos.iter().filter(|p| p[1].abs() < 1e-4 && out(p) > 1.05 * r).map(out).collect();+ let mean = ring.iter().sum::<f32>() / ring.len().max(1) as f32;+ assert!(!ring.is_empty() && (mean / r - sp.flare).abs() < 0.12 * sp.flare, "flare {} against {}", mean / r, sp.flare);+ assert!(b.bark.pos.iter().any(|p| p[1] < -0.2), "the foot goes on under the ground");+ // at breast height it's the trunk again+ let c = a.nodes.iter().filter(|n| n.p.y < near.clear).min_by(|x, y| (x.p.y - 1.3).abs().total_cmp(&(y.p.y - 1.3).abs())).unwrap().p;+ let wide = a.bark.pos.iter().filter(|p| (p[1] - c.y).abs() < 0.05).map(|p| (p[0] - c.x).hypot(p[2] - c.z)).filter(|&d| d < 3.0 * r).fold(0.0, f32::max);+ assert!(wide < 1.05 * r, "at 1.3 m the bark is {} of the trunk", wide / r);+ // the roots: only on the near level, showing in most of their sectors by the trunk, every end under the soil+ assert!(b.bark.pos.iter().filter(|p| p[1] < 0.5).all(|p| out(p) < 2.0 * sp.flare * r), "no roots on a pruned level");+ let n = sp.roots as usize;+ let mut seen = vec![false; n];+ for p in a.bark.pos.iter().filter(|p| p[1] > 0.0 && p[1] < 0.5 && out(p) > 1.3 * sp.flare * r && out(p) < 4.0 * r) {+ seen[((-p[2]).atan2(p[0]).rem_euclid(std::f32::consts::TAU) / std::f32::consts::TAU * n as f32) as usize % n] = true;+ }+ assert!(seen.iter().filter(|s| **s).count() * 2 >= n, "roots show in {seen:?}");+ let mut far_out: Vec<&[f32; 3]> = a.bark.pos.iter().filter(|p| p[1] < 0.6 && out(p) > 2.0 * sp.flare * r).collect();+ far_out.sort_by(|x, y| out(y).total_cmp(&out(x)));+ let tips = &far_out[..far_out.len() / 20];+ assert!(!tips.is_empty() && tips.iter().all(|p| p[1] < 0.0), "a root's end is under the ground: {:?}", tips.iter().map(|p| p[1]).fold(f32::MIN, f32::max));+ println!("lime foot: flare {:.2}, {} of {n} sectors with a root showing, reach {:.2} m", mean / r, seen.iter().filter(|s| **s).count(), out(far_out[0]));+}++/// Side views of every species (three seeds, two bearings) as masks for the project's crown check:+/// RAEA_FOLIAGE_REQ=list.json RAEA_FOLIAGE_OUT=dir cargo test -p raea-sys-foliage -- --ignored silhouettes+#[test]+#[ignore]+fn silhouettes() {+ let req = std::env::var("RAEA_FOLIAGE_REQ").expect("RAEA_FOLIAGE_REQ");+ let out = std::path::PathBuf::from(std::env::var("RAEA_FOLIAGE_OUT").expect("RAEA_FOLIAGE_OUT"));+ std::fs::create_dir_all(&out).unwrap();+ let list: Vec<serde_json::Value> = serde_json::from_slice(&std::fs::read(req).unwrap()).unwrap();+ for r in list {+ for seed in 1..=3u64 {+ let req = Request { species: r["species"].as_str().unwrap().into(), height: r["height"].as_f64().unwrap() as f32, width: r["width"].as_f64().unwrap() as f32, clear: r["clear"].as_f64().unwrap() as f32, seed, leaves: 40_000, prune: 0.0 };+ let t = grow(&req).unwrap();+ for (k, b) in [0.0f32, 1.57].iter().enumerate() {+ crate::silhouette(&req, &t, 600, *b).unwrap().save(out.join(format!("{}-{seed}{}.png", req.species, ["a", "b"][k]))).unwrap();+ }+ }+ }+}diff --git a/systems/foliage/src/tube.rs b/systems/foliage/src/tube.rsnew file mode 100644index 00000000..dfb057cb--- /dev/null+++ b/systems/foliage/src/tube.rs@@ -0,0 +1,86 @@+//! The bark: each branch one tube (docs/foliage.feature FO1). A branch follows its thickest child at each node; the+//! other children start branches of their own, each from its parent's centre so it grows out of the parent's tube.+//! Rings are carried along a branch by parallel transport, so a tube doesn't twist; a branch's sides are fewer as it+//! is thinner (a twig is three sided). The bark hook reads:+//! uv round the branch, in whole repeats of BARK m of circumference (so its noise wraps), and along it in BARK m+//! uv1 the repeats round (the noise's period) and the radius+//! No vertex colour: the engine multiplies a material by it, so a model drawn without the hook would go dark.++use parry3d::glamx::Vec3;++use crate::grow::{Node, children};+use crate::species::Species;+use crate::{Mesh, Request, across};++pub(crate) const BARK: f32 = 0.3;++/// Each branch's nodes in order, its parent's node first (none for the trunk).+pub(crate) fn branches(nodes: &[Node]) -> Vec<Vec<usize>> {+ let kids = children(nodes);+ let mut out = Vec::new();+ let mut starts = vec![(usize::MAX, 0usize)];+ while let Some((from, s)) = starts.pop() {+ let mut chain = if from == usize::MAX { vec![] } else { vec![from] };+ let mut at = s;+ loop {+ chain.push(at);+ let Some(&main) = kids[at].iter().max_by(|&&a, &&b| nodes[a].r.total_cmp(&nodes[b].r).then(b.cmp(&a))) else { break };+ for &k in kids[at].iter().filter(|&&k| k != main) {+ starts.push((at, k));+ }+ at = main;+ }+ out.push(chain);+ }+ out+}++pub(crate) fn bark(_sp: &Species, req: &Request, nodes: &[Node]) -> Mesh {+ let mut m = Mesh::default();+ for chain in branches(nodes) {+ // a pruned level ends each branch where it gets thinner than the prune (radii only thin along a branch)+ let keep = chain.iter().skip(1).take_while(|&&i| nodes[i].r >= req.prune).count() + 1;+ let chain = &chain[..keep.min(chain.len())];+ if chain.len() < 2 {+ continue;+ }+ // a side branch's first ring (at its parent) has its own first node's radius+ let first = if nodes[chain[0]].parent == usize::MAX || chain.len() < 2 { chain[0] } else { chain[1] };+ let r0 = nodes[first].r;+ let sides = ((r0 * 40.0).round() as usize + 3).clamp(3, 14);+ let rep = ((std::f32::consts::TAU * r0 / BARK).round()).max(1.0);+ let mut frame = Vec3::ZERO;+ let mut along = 0.0;+ for (k, &i) in chain.iter().enumerate() {+ let p = nodes[i].p;+ let prev = if k > 0 { nodes[chain[k - 1]].p } else { p };+ let next = if k + 1 < chain.len() { nodes[chain[k + 1]].p } else { p };+ let t = (next - prev).normalize_or_zero();+ let t = if t == Vec3::ZERO { Vec3::Y } else { t };+ frame = if k == 0 { across(t) } else { let f = (frame - t * frame.dot(t)).normalize_or_zero(); if f == Vec3::ZERO { across(t) } else { f } };+ let side = t.cross(frame);+ if k > 0 {+ along += (p - prev).length();+ }+ let r = if k == 0 && chain.len() > 1 && nodes[chain[0]].r > nodes[chain[1]].r { nodes[chain[1]].r } else { nodes[i].r };+ let base = m.pos.len() as u32;+ for s in 0..=sides {+ let a = std::f32::consts::TAU * s as f32 / sides as f32;+ let n = frame * a.cos() + side * a.sin();+ let q = p + n * r;+ m.pos.push(q.to_array());+ m.nrm.push(n.to_array());+ m.uv.push([rep * s as f32 / sides as f32, along / BARK]);+ m.uv1.push([rep, r]);+ }+ if k > 0 {+ let prev_ring = base - (sides as u32 + 1);+ for s in 0..sides as u32 {+ let (a, b, c, d) = (prev_ring + s, prev_ring + s + 1, base + s, base + s + 1);+ m.idx.extend_from_slice(&[a, b, c, b, d, c]);+ }+ }+ }+ }+ m+}