diff --git a/.gitignore b/.gitignore index 02776d51b..1108c7357 100644 --- a/.gitignore +++ b/.gitignore @@ -104,5 +104,8 @@ sdk/raea/.scratch-*/ # the Tripo CLI writes its last task id into the directory it runs in .tripo/ +# examples/materials/wear: its house is made by make-house.ts (media/) and baked at render time (assets/wear/) +/examples/materials/wear/media/ +/examples/materials/wear/assets/ # tools/bevy-parity links each example folder's assets/ to Bevy's checkout at run time (an absolute, per-machine path) /sdk/raea/bench/bevy-parity/**/assets diff --git a/Cargo.lock b/Cargo.lock index 5d21833f3..d0d8e49a0 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -14953,7 +14953,6 @@ dependencies = [ "raea-sys-three-shader", "raea-sys-viewbox", "raea-sys-volume", - "raea-sys-wear", "serde_json", "wgpu", ] @@ -15495,7 +15494,6 @@ dependencies = [ "raea-sys-frame", "raea-sys-layers", "raea-sys-procmat", - "raea-sys-wear", "serde_json", ] @@ -15805,6 +15803,16 @@ dependencies = [ "raea-sys-shader", ] +[[package]] +name = "raea-sys-damage" +version = "0.1.0" +dependencies = [ + "parry3d", + "raea-core-ease", + "raea-sys-touch", + "rayon", +] + [[package]] name = "raea-sys-environment" version = "0.1.0" @@ -15902,6 +15910,7 @@ version = "0.1.0" dependencies = [ "image", "parry3d", + "raea-core-ease", "raea-sys-glb", "serde_json", ] @@ -16523,15 +16532,6 @@ dependencies = [ "serde_json", ] -[[package]] -name = "raea-sys-wear" -version = "0.1.0" -dependencies = [ - "bevy", - "raea-core-program", - "serde_json", -] - [[package]] name = "raea-sys-weathering" version = "0.1.0" @@ -16539,6 +16539,7 @@ dependencies = [ "image", "parry3d", "raea-core-meshcheck", + "raea-sys-damage", "raea-sys-exposure", "raea-sys-glb", "raea-sys-runoff", diff --git a/Cargo.toml b/Cargo.toml index d9c4aa939..a9c85e6e7 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -102,11 +102,11 @@ members = [ "systems/canvas", "systems/tweak", "systems/filters", - "systems/wear", "systems/weathering", "systems/runoff", "systems/touch", "systems/exposure", + "systems/damage", "systems/glb", "systems/procmat", "systems/page", diff --git a/core/ease/src/lib.rs b/core/ease/src/lib.rs index 6815ce12d..9e9282bbb 100644 --- a/core/ease/src/lib.rs +++ b/core/ease/src/lib.rs @@ -7,3 +7,10 @@ pub mod color; pub mod easing; pub mod interpolate; pub mod spring; + +/// 0 below `a`, 1 above `b`, and between them the cubic Hermite ease (WGSL's smoothstep), for a value that fades in +/// over a range rather than a key's time. +pub fn smoothstep(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) +} diff --git a/docs/manual/reference/sdk/pbr.md b/docs/manual/reference/sdk/pbr.md index cc810dde7..3509e9fe1 100644 --- a/docs/manual/reference/sdk/pbr.md +++ b/docs/manual/reference/sdk/pbr.md @@ -271,9 +271,8 @@ Used in: [3d/fog_volumes](https://github.com/shinyobjectz/raea/blob/main/sdk/rae ### `WearExtension` -raea's chips, grime and rust over a StandardMaterial, as an ExtendedMaterial's extension (systems/wear): - -Bevy: `bevy_pbr::mesh_material::MeshMaterial3d>`. +raea's chips, grime and rust over a StandardMaterial, as an ExtendedMaterial's extension: a surface shader of +raea's own (worn.ts) on the hook a ShaderExtension uses, so its Bevy type is ShaderExtension's. | Prop | Type | What it does | | --- | --- | --- | @@ -792,7 +791,7 @@ where density and heat come in: a burner, or an engine moving `at` -> `to` (a co ### `WearExtensionProps` -raea's extension of StandardMaterial that wears it (the engine's Wear MaterialExtension, systems/wear): its paint +raea's extension of StandardMaterial that wears it (a surface shader of raea's own, worn.ts): its paint mottled, chipped back to `chip_color` on edges and a few spots, `grime` gathered low and underneath and `rust` run down in streaks, fixed in the part's own space as it moves. `amount` 0-1; `chips`, `grime` and `rust` each 0-1 of it (0.6, 0.5, 0.25); `scale` a blotch's size in metres (0.08); `seed` moves the pattern. It goes in an diff --git a/docs/sdk-coverage.md b/docs/sdk-coverage.md index e554b8c10..4c9538b7d 100644 --- a/docs/sdk-coverage.md +++ b/docs/sdk-coverage.md @@ -14,7 +14,7 @@ reaches it yet). | area | kind | tier 1 | tier 2 | tier 3 | not rendered | SVG attribute only | blocked upstream | excluded | unmapped | total | |---|---|---:|---:|---:|---:|---:|---:|---:|---:|---:| | bevy | asset | 9 | 0 | 0 | 0 | 0 | 0 | 0 | 0 | 9 | -| bevy | component | 61 | 869 | 0 | 0 | 0 | 0 | 1 | 0 | 931 | +| bevy | component | 60 | 869 | 0 | 0 | 0 | 0 | 1 | 0 | 930 | | bevy | event | 0 | 13 | 0 | 0 | 0 | 0 | 0 | 0 | 13 | | bevy | message | 0 | 40 | 0 | 0 | 0 | 0 | 0 | 0 | 40 | | bevy | resource | 4 | 86 | 0 | 0 | 0 | 0 | 1 | 0 | 91 | @@ -23,9 +23,9 @@ reaches it yet). | css | shorthand | 60 | 0 | 0 | 11 | 0 | 0 | 0 | 0 | 71 | | element | html | 113 | 0 | 0 | 0 | 0 | 0 | 18 | 0 | 131 | | plugin | declared | 0 | 0 | 53 | 0 | 0 | 21 | 0 | 3 | 77 | -| **all** | | **495** | **1009** | **53** | **55** | **14** | **21** | **21** | **3** | **1671** | +| **all** | | **494** | **1009** | **53** | **55** | **14** | **21** | **21** | **3** | **1670** | -Reached (tiers 1-3): **1557**. The ratchet (`tools/sdk-coverage --check`, in tools/agents/check) keeps it from dropping. +Reached (tiers 1-3): **1556**. The ratchet (`tools/sdk-coverage --check`, in tools/agents/check) keeps it from dropping. ## Bevy types (the plugin build's TypeRegistry) @@ -624,7 +624,6 @@ Reached (tiers 1-3): **1557**. The ratchet (`tools/sdk-coverage --check`, in too | `bevy_pbr::mesh_material::MeshMaterial3d>` | component | 2 | bevy.MeshMaterial3dExtendedMaterialStandardMaterialPaint (raea/plugins/bevy) | | `bevy_pbr::mesh_material::MeshMaterial3d>` | component | 2 | bevy.MeshMaterial3dExtendedMaterialStandardMaterialToonExt (raea/plugins/bevy) | | `bevy_pbr::mesh_material::MeshMaterial3d>` | component | 1 | SurfaceShader (sdk/render/src/3d/materials.tsx) | -| `bevy_pbr::mesh_material::MeshMaterial3d>` | component | 1 | WearExtension (sdk/render/src/bevy3d/extensions.tsx) | | `bevy_pbr::mesh_material::MeshMaterial3d` | component | 1 | Mesh3d (sdk/render/src/bevy3d/core.tsx) | | `bevy_pbr::mesh_material::MeshMaterial3d` | component | 2 | bevy.MeshMaterial3dQuakeSkyMaterial (raea/plugins/bevy) | | `bevy_pbr::mesh_material::MeshMaterial3d` | component | 2 | bevy.MeshMaterial3dFireMaterial (raea/plugins/bevy) | diff --git a/docs/sdk-coverage/bevy.tsv b/docs/sdk-coverage/bevy.tsv index 4e89ef380..923347ffa 100644 --- a/docs/sdk-coverage/bevy.tsv +++ b/docs/sdk-coverage/bevy.tsv @@ -593,7 +593,6 @@ bevy_pbr::mesh_material::MeshMaterial3d> component bevy_pbr::mesh_material::MeshMaterial3d> component bevy_pbr::mesh_material::MeshMaterial3d> component -bevy_pbr::mesh_material::MeshMaterial3d> component bevy_pbr::mesh_material::MeshMaterial3d component bevy_pbr::mesh_material::MeshMaterial3d component bevy_pbr::mesh_material::MeshMaterial3d component diff --git a/docs/wear.feature b/docs/wear.feature index bf6cb20f8..2442692cd 100644 --- a/docs/wear.feature +++ b/docs/wear.feature @@ -5,7 +5,7 @@ Feature: raea/wear, weathering that has a cause version, "realistic procedural and highly intelligent seeding ... for what makes sense on wear, wear by material, crumbling infrastructure, doors, walls, plates", and the same for how textures are built and made cheap. - raea's wear so far is shader-only (systems/wear: noise, screen-space curvature, grime on faces turned down; + raea's wear was shader-only (systems/wear: noise, screen-space curvature, grime on faces turned down; systems/procmat: a pattern with dust, dirt and edges). Nothing in it knows where water runs, what is sheltered, where hands touch or what a surface is made of, so the marks are scattered evenly rather than caused. The fix is the method of the literature: the agents of wear are traced through the geometry from their sources, and they leave @@ -246,14 +246,28 @@ Feature: raea/wear, weathering that has a cause faded, the railing rusted; rain, snow with a storm and autumn render; an unbaked sphere under the same shader is unchanged. The corner house with stills of every cause and condition is WR7's - @needs:WR5,WR3 + @needs:WR5,WR3 @done Scenario: WR6. Crumbling Then where damage is high (ground band, edges, sheltered damp, neglect), plaster is gone to the brick 2 cm behind it under a shadowed lip, paint to primer and wood, enamel to iron; cracks run from the corners of openings; panes are broken or boarded by neglect; slates are missing; and spots.json puts debris under the losses And the cracked-road fracture of the kit waits for a piece that needs it + And as built (11-19) + | crate | file | lines | job | + | raea-sys-damage | systems/damage/src/lib.rs | 241 | an opening's corners, a crack from about half of them (by a seed per corner), each point's loss potential (damp foot, soaked faces, knocked arrises, along a crack), debris under the losses where the rain falls, landed on the walk below; version 3 | + | raea-sys-damage | systems/damage/src/tests.rs | 190 | an opening's four corners and no others, cracks along the wall, what loosens a coat, debris under the foot (none indoors, none on a plinth), about half the corners cracking | + | raea-sys-weathering | src/lib.rs, rays.rs, touch.rs | +33 | causes3 a's crack, the loss potential and the debris spots from raea-sys-damage | + | raea-sys-touch | src/lib.rs, spots.rs | +18 | a spot's loss, the seed shared with damage | + | raea/wear | sdk/wear/src/causes.ts | 159 | neglect = (1 - e^(-years / 25)) x (1.15 - upkeep); abandon, the share of a house past what a lived-in one lets go (smoothstep from 0.85 of neglect at its base upkeep) | + | raea/wear | sdk/wear/src/recipes.ts | 303 | plaster off to the brick under its lip, paint to primer and wood, enamel flaked to iron, cracks opening by neglect (stepped through brick's joints), panes broken (38%) and boarded (16%) by abandon, slates gone by neglect and abandon | + | raea/wear | sdk/wear/src/index.ts | 257 | wearDebris: the bake's debris spots where loss x abandon reaches 0.3 | + And proof: `cargo test -p raea-sys-damage` (5 tests) and `-p raea-sys-weathering`; `bun test` in sdk/wear (22 + tests: neglect and upkeep, abandonment's threshold in the shader's text, debris none at upkeep 0.35, all at 90 + years and 0.05, some at 80 and 0.2); the corner house (WR7) rendered after 80 years and as a ruin: plaster off + the rusticated foot and around the openings, cracks from the window corners, the ruin's panes broken and + boarded and slates gone, heaps on the walk under the losses and none inside or on the plinth - @needs:WR5 + @needs:WR5 @done Scenario: WR9. Every season and weather, from uniforms over the causes Given the look's date and weather, the values the realism lane's sets carry: `day` (the day of the year, 1-366) and `hour`, from which the season's phase (day / 365.25) and the sun follow; snow, wet and ice as weather of @@ -297,10 +311,18 @@ Feature: raea/wear, weathering that has a cause posted as i-acp-mwlb9fb4-110 And still open: the mapping from the look's `day` and weather to these values is WR5's (the prototype takes storm, leaves, dust and melt as values of their own); frost and algae; the flash of thunder is the light's + And the shader's half as built (11-19): the eight conditions are WR5's recipes over these causes (spring's damp + and algae, summer's dust, autumn's leaves, frost where December's sun misses, snow lying and driven, rain + wetting, streaming and puddling), named once, and weather that changes during a shot eases toward the sky's + | crate | file | lines | job | + | raea/wear | sdk/wear/src/weather.ts | 79 | WEAR_CONDITIONS (the eight as weather), weatherAt(base, spells, minutes): each value eased exactly toward the sky's per spell, so any frame draws alone; WEATHER_RATES (wetting in about 3 minutes, drying over an hour, snow settling over 20 and melting over 2 hours, driven snow in 10 and off in 30, frost over 30 and gone in 20; ASSUMED until measured) | + | raea/wear | sdk/wear/test/wear.test.ts | 216 | rain soaks and dries at its rates, frames stand alone with no jump at a spell, snow, storm and frost, spells out of order refused, each condition in its season | + And proof: `bun test` in sdk/wear; the corner house under all eight by day and at dusk, and a shower crossing it + (WR7's rain-passes: dry, soaked and drying at frames 0, 40 and 119) Rule: 3. Shown, then cheap - @needs:WR5 + @needs:WR5 @done Scenario: WR7. The demo, and EX9 Then examples/materials/wear/ is a corner house made in code (plinth, rusticated ground floor, plastered storeys, sills, string course, cornice on consoles, door, iron balcony, zinc gutter and downpipe, an enamel street @@ -308,6 +330,22 @@ Feature: raea/wear, weathering that has a cause colour and the house under each of WR9's eight conditions, by day and at dusk And `wear` on MeshStandardMaterial and are raea/wear's, and systems/wear, its spawn branch and its row columns are deleted in the same landing (docs/examples.feature EX9) + And as built (11-19) + | crate | file | lines | job | + | example | examples/materials/wear/house.ts | 260 | the corner house as solids (each 8 corners), a hip roof, openings cut through each band, one .glb material per class | + | example | examples/materials/wear/make-house.ts | 11 | writes media/house.glb | + | example | examples/materials/wear/wear.tsx | 179 | before, new, after (80 sooty years), ruin, ruin-near, door; debug-CAUSE for all 16; the eight conditions and their -dusk; rain-passes (120 frames, half a minute each); paint (worn paint with no bake) | + | example | examples/materials/wear/wear.test.ts | 85 | every part WR7 names, the openings through the walls, the .glb, every cause and condition listed, the paint still | + | raea/render | sdk/render/src/worn.ts | 119 | worn paint as a surface shader on the public hook (WORN_WESL, wornShader): systems/wear's shader ported, same noise, curvature edges, grime, rust and chips in the mesh's own space | + | raea/render | sdk/render/src/3d/materials.tsx | +12 | a material's `wear` becomes that shader (none at amount 0; refused beside `shader` or `grid`) | + | deleted | systems/wear, spawn.rs, raea_plugins.rs, runtime/scene parts.rs | -480 | raea-sys-wear, its WearPlugin, spawn branch and row columns; its type out of the registry snapshot, bevy.gen.tsx and sdk-coverage | + And worn paint's shader lives in raea/render beside the material that takes it, not in raea/wear: raea/wear is + built on raea/render, so the other way would be a cycle. and `wear` keep their props, and the + guides are unchanged + And proof: `bun test` in examples/materials/wear (7 tests) and conformance bevy3d.test.tsx (wear's shader, its + uniforms, none at amount 0, alone); a parity scene of worn paint (sharp, turned and round parts, every setting) + rendered through systems/wear and through worn.ts matches (RMSE 3.8e-5 of full scale); every still, and + rain-passes at frames 0, 40 and 119, render with 0 errors on the Mac. Clay now draws worn paint as it draws any custom surface shader @needs:WR7 Scenario: WR8. Detail textures from mask stacks, and what they cost @@ -315,3 +353,14 @@ Feature: raea/wear, weathering that has a cause rendered by raea once into tiling layers, instead of noise evaluated per pixel per frame And texture arrays get mips (SH9 arrays have none, so a tiling layer shimmers far off) and maps can be BC compressed into KTX2, with the memory and frame time each saves measured + And measured first (11-19, M5 Pro, the corner house at 4K, 121-127 frames each, plain and worn interleaved): with + the machine quiet, 17.2 ms a frame plain and 17.2 worn, 17.6 and 17.7; under other sessions' load both rise + together (18-75 ms). The recipes' per-pixel noise costs no frame time a render can see, so detail layers + would save nothing yet; a live scene at 60 fps with many baked buildings is where to measure again + And the maps' memory: four RGBA8 maps of 2048 x 1108 for the house, 36 MB on the GPU; BC7 would take that to + about 9 MB, but causes2's alpha is the class code read exactly by textureLoad (it needs a map of its own + before the rest compress), and an iPhone has no BC (ASTC there). Worth it for a city of baked buildings, not + one house + And still open, so not done: the detail layers, mips on arrays (they come with the detail layers: adding them + now would grow the city's 40-layer room atlas by a third for no wear user), and BC/KTX2 maps with the class + split out and a fallback where BC isn't diff --git a/engine/render/Cargo.toml b/engine/render/Cargo.toml index 7fd27f736..320919516 100644 --- a/engine/render/Cargo.toml +++ b/engine/render/Cargo.toml @@ -21,8 +21,6 @@ bevy = { version = "=0.20.0", default-features = false, features = ["std", "defa image = { version = "0.25", default-features = false, features = ["png", "jpeg", "hdr"] } # an edit as rows keyed per frame, and 3D shapes as values (docs/media.feature M2) raea-core-program = { path = "../../core/program" } -# worn surfaces on a mesh row (`wear`) -raea-sys-wear = { path = "../../systems/wear" } # procedural surfaces on a mesh row (`proc`) raea-sys-procmat = { path = "../../systems/procmat" } raea-core-shape = { path = "../../core/shape" } diff --git a/engine/render/src/engine/raea_plugins.rs b/engine/render/src/engine/raea_plugins.rs index 59b3e80f7..8d61b72a1 100644 --- a/engine/render/src/engine/raea_plugins.rs +++ b/engine/render/src/engine/raea_plugins.rs @@ -55,7 +55,6 @@ raea_plugin! { Draws2dPlugin: raea_sys_sprite::install, "Plugins' 2D drawing brings up the scene's 2D camera (raea-sys-sprite's Draws2d)."; ScreenPlugin: super::screen::install, "Live pictures on surfaces, drawn as CRTs (screen.rs)."; GridPlugin: super::grid::install, "Greybox surfaces: graph paper and outlines (grid.rs)."; - WearPlugin: raea_sys_wear::install, "Worn surfaces: chipped paint, grime and rust (systems/wear)."; ProcMatPlugin: raea_sys_procmat::install, "Procedural surfaces: wood, stone, brick, tiles and the rest, with dust and dirt (systems/procmat)."; PaintPlugin: super::paint::install, "The paint and cartoon looks' surfaces (paint.rs)."; PassesPlugin: super::passes::install, "Render passes per view (passes.rs)."; diff --git a/engine/render/src/engine/spawn.rs b/engine/render/src/engine/spawn.rs index 7c1668af3..476e5aaea 100644 --- a/engine/render/src/engine/spawn.rs +++ b/engine/render/src/engine/spawn.rs @@ -281,9 +281,6 @@ pub(crate) fn spawn_3d(world: &mut World, e: Entity, t: &Tup, inserted: &[Tup], } else if let Some(extension) = raea_sys_procmat::of(vals).filter(|_| !scene3d::clay::on()) { // a procedural surface (systems/procmat): its pattern, bump and use made on the GPU; clay draws it plain grid::put(world, e, mesh, raea_sys_procmat::ProcMaterial { base: mat, extension }, vals); - } else if let Some(extension) = raea_sys_wear::of(vals).filter(|_| !scene3d::clay::on()) { - // worn paint (systems/wear): chipped edges, grime and rust, fixed in the part's own space - grid::put(world, e, mesh, raea_sys_wear::WearMaterial { base: mat, extension }, vals); } else if vals.get("shader").is_none() { // a plain surface, see-through too: one material per value, shared by the parts that have it (share.rs; // froxel_glass's fog copy is per material, so equal panes share it; mesh_ray_cast's six walls are one) diff --git a/examples/materials/wear/house.ts b/examples/materials/wear/house.ts new file mode 100644 index 000000000..cab4c0106 --- /dev/null +++ b/examples/materials/wear/house.ts @@ -0,0 +1,260 @@ +// The corner house raea/wear's demo weathers (docs/wear.feature WR7), made in code: a four-storey block on a street +// corner, its south front on x = 0..12 facing +z, its east front on z = -10..0 facing +x, the corner at (12, 0). +// A sandstone plinth, a rusticated ground floor, plastered storeys, sandstone sills and a string course, a cornice +// on consoles under a slate roof, a door in a sandstone surround up granite steps, an iron balcony, a zinc gutter and +// downpipe, an enamel street plate on each face of the corner, a cellar hatch in the walk, a brick firewall on the +// west, and the walk all round. The openings go through the walls (glass 15 cm in, frames in the reveals), so cracks +// can start at their corners. One glTF material per wear class, named for it. y up, metres. +// houseGlb() the .glb's bytes (make-house.ts writes assets/house.glb) + +type V3 = [number, number, number]; +/** a hexahedron: its eight corners, corner (i, j, k) at index i + 2j + 4k */ +type Solid = V3[]; + +export const CLASSES = ["plaster", "brick", "sandstone", "granite", "wood", "iron", "zinc", "copper", "slate", "felt", "glass", "enamel", "brass", "ground"] as const; +export type HouseClass = (typeof CLASSES)[number]; + +const LOOK: Record = { + plaster: { color: [0.8, 0.72, 0.56], rough: 0.85, metal: 0 }, + brick: { color: [0.45, 0.2, 0.13], rough: 0.9, metal: 0 }, + sandstone: { color: [0.68, 0.57, 0.4], rough: 0.85, metal: 0 }, + granite: { color: [0.46, 0.46, 0.47], rough: 0.7, metal: 0 }, + wood: { color: [0.17, 0.28, 0.21], rough: 0.6, metal: 0 }, + iron: { color: [0.06, 0.07, 0.065], rough: 0.5, metal: 0.6 }, + zinc: { color: [0.55, 0.58, 0.6], rough: 0.4, metal: 0.9 }, + copper: { color: [0.62, 0.33, 0.18], rough: 0.35, metal: 1 }, + slate: { color: [0.2, 0.21, 0.24], rough: 0.7, metal: 0 }, + felt: { color: [0.08, 0.08, 0.08], rough: 0.9, metal: 0 }, + glass: { color: [0.07, 0.09, 0.11], rough: 0.05, metal: 0.2 }, + enamel: { color: [0.08, 0.16, 0.5], rough: 0.25, metal: 0 }, + brass: { color: [0.75, 0.58, 0.25], rough: 0.3, metal: 1 }, + ground: { color: [0.33, 0.32, 0.3], rough: 0.9, metal: 0 }, +}; + +export const SOUTH = { x0: 0, x1: 12 }; +export const EAST = { z0: -10, z1: 0 }; +export const TOP = 14.2; +/** the storeys' floor heights and their windows' sill and head */ +export const STOREYS = [ + { floor: 0.6, sill: 1.5, head: 3.4 }, + { floor: 4.2, sill: 5.1, head: 7.2 }, + { floor: 7.6, sill: 8.5, head: 10.5 }, + { floor: 10.9, sill: 11.7, head: 13.5 }, +]; +/** the windows' middles along each front (metres from its west or south end), 1.2 m wide; the door's bay is 6 on the south */ +export const BAYS = { south: [1.5, 4.0, 6.0, 8.5, 10.6], east: [1.6, 4.4, 7.2, 9.0] }; +export const DOOR = { at: 6.0, w: 1.4, h: 2.9 }; +const WIN = 1.2; +const T = 0.5; + +const parts = new Map(CLASSES.map((c) => [c, []])); +/** a parallelepiped from a corner and its three edges */ +const add = (c: HouseClass, [o, u, v, w]: [V3, V3, V3, V3]) => { + const s: Solid = []; + for (let n = 0; n < 8; n++) { + const [i, j, k] = [n & 1, (n >> 1) & 1, (n >> 2) & 1]; + s.push([o[0] + u[0] * i + v[0] * j + w[0] * k, o[1] + u[1] * i + v[1] * j + w[1] * k, o[2] + u[2] * i + v[2] * j + w[2] * k]); + } + parts.get(c)!.push(s); +}; +/** a slab `t` thick upward from a planar quad (its corners in order round it) */ +const slab = (c: HouseClass, q: [V3, V3, V3, V3], t: number) => { + const base = [q[0], q[1], q[3], q[2]]; + parts.get(c)!.push([...base, ...base.map((p): V3 => [p[0], p[1] + t, p[2]])]); +}; +/** an axis-aligned box from its two corners */ +const box = (c: HouseClass, a: V3, b: V3) => add(c, [a, [b[0] - a[0], 0, 0], [0, b[1] - a[1], 0], [0, 0, b[2] - a[2]]]); + +/** A front: `along` and `out` its axes, `at` where it starts; a wall of `c` from y0 to y1 with rectangular openings + * (u0, u1, v0, v1 along it and up) cut through, as boxes round them. */ +function wall(c: HouseClass, at: V3, along: V3, out: V3, len: number, y0: number, y1: number, holes: [number, number, number, number][], depth = T, proud = 0) { + const cuts = [...new Set([0, len, ...holes.flatMap((h) => [h[0], h[1]])])].sort((a, b) => a - b); + for (let i = 0; i + 1 < cuts.length; i++) { + const [u0, u1] = [cuts[i], cuts[i + 1]]; + const mid = (u0 + u1) / 2; + // the openings in this column, clipped to the wall's own height + const cut = holes.filter((h) => h[0] <= mid && mid <= h[1] && h[3] > y0 && h[2] < y1).flatMap((h) => [Math.max(h[2], y0), Math.min(h[3], y1)]); + const ys = [y0, y1, ...cut].sort((a, b) => a - b); + for (let j = 0; j + 1 < ys.length; j += 2) { + if (ys[j + 1] - ys[j] < 1e-4) continue; + const o: V3 = [at[0] + along[0] * u0 - out[0] * (depth - proud), ys[j], at[2] + along[2] * u0 - out[2] * (depth - proud)]; + add(c, [o, [along[0] * (u1 - u0), 0, along[2] * (u1 - u0)], [0, ys[j + 1] - ys[j], 0], [out[0] * depth, 0, out[2] * depth]]); + } + } +} + +/** A window in the opening (u0..u1, v0..v1) of the front at `at`: glass 15 cm in, a frame round it in the reveal and a + * transom, a sandstone sill below standing out 8 cm. */ +function window(at: V3, along: V3, out: V3, u0: number, u1: number, v0: number, v1: number, sill = true) { + const p = (u: number, v: number, o: number): V3 => [at[0] + along[0] * u + out[0] * o, v, at[2] + along[2] * u + out[2] * o]; + const piece = (cl: HouseClass, ua: number, ub: number, va: number, vb: number, oa: number, ob: number) => { + const o = p(ua, va, oa); + add(cl, [o, [along[0] * (ub - ua), 0, along[2] * (ub - ua)], [0, vb - va, 0], [out[0] * (ob - oa), 0, out[2] * (ob - oa)]]); + }; + piece("glass", u0 + 0.06, u1 - 0.06, v0 + 0.06, v1 - 0.06, -0.17, -0.15); + piece("wood", u0, u0 + 0.06, v0, v1, -0.2, -0.1); + piece("wood", u1 - 0.06, u1, v0, v1, -0.2, -0.1); + piece("wood", u0, u1, v0, v0 + 0.06, -0.2, -0.1); + piece("wood", u0, u1, v1 - 0.06, v1, -0.2, -0.1); + const tr = v0 + (v1 - v0) * 0.72; + piece("wood", u0, u1, tr - 0.03, tr + 0.03, -0.2, -0.12); + piece("wood", (u0 + u1) / 2 - 0.03, (u0 + u1) / 2 + 0.03, v0, tr, -0.2, -0.12); + if (sill) piece("sandstone", u0 - 0.08, u1 + 0.08, v0 - 0.08, v0, -0.12, 0.08); +} + +function build() { + for (const v of parts.values()) v.length = 0; + const S: V3 = [SOUTH.x0, 0, 0]; + const E: V3 = [SOUTH.x1, 0, EAST.z1]; + const X: V3 = [1, 0, 0]; + const Z: V3 = [0, 0, 1]; + const NZ: V3 = [0, 0, -1]; + const fronts = [ + { at: S, along: X, out: Z, len: SOUTH.x1 - SOUTH.x0, bays: BAYS.south, door: true }, + { at: E, along: NZ, out: X, len: EAST.z1 - EAST.z0, bays: BAYS.east, door: false }, + ]; + for (const f of fronts) { + const holes: [number, number, number, number][] = []; + for (const [k, st] of STOREYS.entries()) { + for (const b of f.bays) { + if (f.door && k === 0 && b === DOOR.at) continue; + holes.push([b - WIN / 2, b + WIN / 2, st.sill, st.head]); + } + } + if (f.door) holes.push([DOOR.at - DOOR.w / 2, DOOR.at + DOOR.w / 2, 0.6, 0.6 + DOOR.h]); + // the ground floor rendered in rusticated bands (a 2 cm groove every 0.4 m), the storeys above plain + const ground = holes.filter((h) => h[2] < 4.2); + for (let y = 0.6; y < 4.2 - 1e-6; y += 0.4) { + const top = Math.min(y + 0.38, 4.2); + wall("plaster", f.at, f.along, f.out, f.len, y, top, ground); + wall("plaster", f.at, f.along, f.out, f.len, top, Math.min(y + 0.4, 4.2), ground, T, -0.02); + } + wall("plaster", f.at, f.along, f.out, f.len, 4.2, TOP, holes.filter((h) => h[2] >= 4.2)); + // the plinth, standing 8 cm out, the string course over the ground floor and the cornice's frieze + wall("sandstone", f.at, f.along, f.out, f.len, 0, 0.6, f.door ? [[DOOR.at - DOOR.w / 2, DOOR.at + DOOR.w / 2, 0, 0.6]] : [], T, 0.08); + wall("sandstone", f.at, f.along, f.out, f.len, 4.05, 4.25, [], T, 0.14); + for (const h of holes) { + if (f.door && h[0] === DOOR.at - DOOR.w / 2) continue; + window(f.at, f.along, f.out, h[0], h[1], h[2], h[3]); + } + // the cornice on its consoles, every 0.9 m + wall("sandstone", f.at, f.along, f.out, f.len + 0.6, TOP, TOP + 0.4, [], T, 0.6); + for (let u = 0.45; u < f.len; u += 0.9) { + const p: V3 = [f.at[0] + f.along[0] * u, TOP - 0.45, f.at[2] + f.along[2] * u]; + add("sandstone", [[p[0] - f.along[0] * 0.09, p[1], p[2] - f.along[2] * 0.09], [f.along[0] * 0.18, 0, f.along[2] * 0.18], [0, 0.45, 0], [f.out[0] * 0.45, 0, f.out[2] * 0.45]]); + } + // the zinc gutter along the cornice's lip + add("zinc", [[f.at[0] + f.out[0] * 0.6 - f.along[0] * 0.0, TOP + 0.4, f.at[2] + f.out[2] * 0.6], [f.along[0] * (f.len + 0.6), 0, f.along[2] * (f.len + 0.6)], [0, 0.14, 0], [f.out[0] * 0.16, 0, f.out[2] * 0.16]]); + } + // the door: wood in a sandstone surround, granite steps up to it, a brass handle and bell plate, a copper canopy + const d0 = DOOR.at - DOOR.w / 2, d1 = DOOR.at + DOOR.w / 2; + box("wood", [d0, 0.6, -0.2], [d1, 0.6 + DOOR.h, -0.12]); + box("sandstone", [d0 - 0.25, 0.6, 0], [d0, 0.6 + DOOR.h + 0.3, 0.1]); + box("sandstone", [d1, 0.6, 0], [d1 + 0.25, 0.6 + DOOR.h + 0.3, 0.1]); + box("sandstone", [d0, 0.6 + DOOR.h, 0], [d1, 0.6 + DOOR.h + 0.3, 0.1]); + for (const [k, w] of [0.2, 0.4, 0.6].entries()) box("granite", [d0 - 0.4 + k * 0.05, 0, 0.1], [d1 + 0.4 - k * 0.05, w, 0.1 + 0.9 - k * 0.3]); + box("brass", [d1 - 0.22, 1.55, -0.12], [d1 - 0.12, 1.62, -0.07]); + box("brass", [d1 + 0.05, 1.75, 0.1], [d1 + 0.2, 1.95, 0.115]); + add("copper", [[d0 - 0.4, 0.6 + DOOR.h + 0.4, 0], [DOOR.w + 0.8, 0, 0], [0, -0.25, 0.8], [0, 0.04, 0]]); + // the iron balcony at the first floor's corner bay on the south front: a stone slab, balusters and a rail + const bx = BAYS.south[4]; + box("sandstone", [bx - 1.1, 4.25, 0], [bx + 1.1, 4.4, 0.95]); + for (let i = 0; i <= 14; i++) box("iron", [bx - 1.05 + i * 0.15, 4.4, 0.86], [bx - 1.03 + i * 0.15, 5.35, 0.88]); + box("iron", [bx - 1.08, 5.35, 0.84], [bx + 1.08, 5.4, 0.9]); + // the downpipe down the south front's west end, from the gutter to the walk + box("zinc", [0.25, 0.05, 0.62], [0.35, TOP + 0.45, 0.72]); + box("zinc", [0.25, 0.05, 0.0], [0.35, 0.15, 0.72]); + // an enamel street plate on each face of the corner, 2.6-2.9 m up + box("enamel", [SOUTH.x1 - 0.9, 2.6, 0], [SOUTH.x1 - 0.2, 2.9, 0.012]); + box("enamel", [SOUTH.x1, 2.6, -0.9], [SOUTH.x1 + 0.012, 2.9, -0.2]); + // the cellar hatch: iron plates in the walk by the east front + box("iron", [SOUTH.x1 + 0.3, -0.01, -6.5], [SOUTH.x1 + 1.1, 0.03, -5.3]); + // the slate roof: a slope up from each front's cornice to a ridge 3 m higher, meeting on a hip over the corner, + // and a felt flat behind them + const [r, d, e, ex, ez] = [3.0, 3.2, TOP + 0.5, SOUTH.x1 + 0.1, EAST.z1 + 0.1]; + slab("slate", [[SOUTH.x0, e, ez], [ex, e, ez], [ex - d, e + r, ez - d], [SOUTH.x0, e + r, ez - d]], 0.06); + slab("slate", [[ex, e, EAST.z0], [ex - d, e + r, EAST.z0], [ex - d, e + r, ez - d], [ex, e, ez]], 0.06); + box("felt", [SOUTH.x0, e + r, EAST.z0], [ex - d, e + r + 0.05, ez - d]); + // the house's own back and its neighbour: a brick firewall on the west, standing above the roof + box("brick", [SOUTH.x0 - 0.4, 0, EAST.z0], [SOUTH.x0, TOP + 4.2, -T]); + box("plaster", [SOUTH.x0, 0, EAST.z0 - 0.1], [SOUTH.x1, TOP + 0.4, EAST.z0]); + box("plaster", [SOUTH.x0, 0, EAST.z0], [SOUTH.x1 - T, TOP + 0.4, -T]); + // the walk round the corner, a granite kerb and the road 15 cm below it + box("ground", [-6, -0.2, -16], [SOUTH.x1 + 3.5, 0, 3.5]); + box("granite", [-6, -0.2, 3.5], [SOUTH.x1 + 3.8, 0, 3.8]); + box("granite", [SOUTH.x1 + 3.5, -0.2, -16], [SOUTH.x1 + 3.8, 0, 3.5]); + box("ground", [-6, -0.5, 3.8], [SOUTH.x1 + 12, -0.15, 14]); + box("ground", [SOUTH.x1 + 3.8, -0.5, -16], [SOUTH.x1 + 12, -0.15, 3.8]); +} + +/** Each class's solids (after `houseGlb` or `solids` builds them). */ +export function solids(): Map { + build(); + return parts; +} + +/** The corner house as a .glb: one primitive and one material per class, each solid's six faces with flat normals. */ +export function houseGlb(): Uint8Array { + build(); + const pos: number[] = [], nrm: number[] = [], idx: number[] = []; + const prims: { first: number; count: number; mat: number }[] = []; + const mats: unknown[] = []; + const sub = (a: V3, b: V3): V3 => [a[0] - b[0], a[1] - b[1], a[2] - b[2]]; + const cross = (a: V3, b: V3): V3 => [a[1] * b[2] - a[2] * b[1], a[2] * b[0] - a[0] * b[2], a[0] * b[1] - a[1] * b[0]]; + const norm = (a: V3): V3 => { const l = Math.hypot(...a) || 1; return [a[0] / l, a[1] / l, a[2] / l]; }; + for (const c of CLASSES) { + const first = idx.length; + for (const s of parts.get(c)!) { + const at = (i: number, j: number, k: number): V3 => s[i + 2 * j + 4 * k]; + const mid: V3 = [0, 1, 2].map((a) => s.reduce((t, p) => t + p[a], 0) / 8) as V3; + const quads: V3[][] = [ + [at(0, 0, 0), at(0, 1, 0), at(0, 1, 1), at(0, 0, 1)], [at(1, 0, 0), at(1, 0, 1), at(1, 1, 1), at(1, 1, 0)], + [at(0, 0, 0), at(0, 0, 1), at(1, 0, 1), at(1, 0, 0)], [at(0, 1, 0), at(1, 1, 0), at(1, 1, 1), at(0, 1, 1)], + [at(0, 0, 0), at(1, 0, 0), at(1, 1, 0), at(0, 1, 0)], [at(0, 0, 1), at(0, 1, 1), at(1, 1, 1), at(1, 0, 1)], + ]; + for (let q of quads) { + let n = norm(cross(sub(q[1], q[0]), sub(q[2], q[0]))); + const centre: V3 = [(q[0][0] + q[2][0]) / 2, (q[0][1] + q[2][1]) / 2, (q[0][2] + q[2][2]) / 2]; + const away = sub(centre, mid); + if (n[0] * away[0] + n[1] * away[1] + n[2] * away[2] < 0) { q = [q[0], q[3], q[2], q[1]]; n = [-n[0], -n[1], -n[2]]; } + const b = pos.length / 3; + for (const p of q) { pos.push(...p); nrm.push(...n); } + idx.push(b, b + 1, b + 2, b, b + 2, b + 3); + } + } + if (idx.length > first) { + prims.push({ first, count: idx.length - first, mat: mats.length }); + const l = LOOK[c]; + mats.push({ name: c, pbrMetallicRoughness: { baseColorFactor: [...l.color, 1], roughnessFactor: l.rough, metallicFactor: l.metal } }); + } + } + const f32 = new Float32Array([...pos, ...nrm]); + const u32 = new Uint32Array(idx); + const bin = new Uint8Array(f32.byteLength + u32.byteLength); + bin.set(new Uint8Array(f32.buffer), 0); + bin.set(new Uint8Array(u32.buffer), f32.byteLength); + const n = pos.length / 3; + const lo = [0, 1, 2].map((k) => Math.min(...pos.filter((_, i) => i % 3 === k))); + const hi = [0, 1, 2].map((k) => Math.max(...pos.filter((_, i) => i % 3 === k))); + const json = { + asset: { version: "2.0", generator: "raea examples/materials/wear/house.ts" }, scene: 0, scenes: [{ nodes: [0] }], nodes: [{ mesh: 0, name: "corner-house" }], + meshes: [{ primitives: prims.map((p, i) => ({ attributes: { POSITION: 0, NORMAL: 1 }, indices: 2 + i, material: p.mat })) }], + materials: mats, + buffers: [{ byteLength: bin.byteLength }], + bufferViews: [{ buffer: 0, byteOffset: 0, byteLength: n * 12 }, { buffer: 0, byteOffset: n * 12, byteLength: n * 12 }, { buffer: 0, byteOffset: n * 24, byteLength: u32.byteLength }], + accessors: [ + { bufferView: 0, componentType: 5126, count: n, type: "VEC3", min: lo, max: hi }, + { bufferView: 1, componentType: 5126, count: n, type: "VEC3" }, + ...prims.map((p) => ({ bufferView: 2, byteOffset: p.first * 4, componentType: 5125, count: p.count, type: "SCALAR" })), + ], + }; + const pad = (b: Uint8Array, fill: number) => { const out = new Uint8Array(Math.ceil(b.length / 4) * 4).fill(fill); out.set(b); return out; }; + const j = pad(new TextEncoder().encode(JSON.stringify(json)), 0x20); + const bb = pad(bin, 0); + const glb = new Uint8Array(12 + 8 + j.length + 8 + bb.length); + const dv = new DataView(glb.buffer); + dv.setUint32(0, 0x46546c67, true); dv.setUint32(4, 2, true); dv.setUint32(8, glb.length, true); + dv.setUint32(12, j.length, true); dv.setUint32(16, 0x4e4f534a, true); glb.set(j, 20); + dv.setUint32(20 + j.length, bb.length, true); dv.setUint32(24 + j.length, 0x004e4942, true); glb.set(bb, 28 + j.length); + return glb; +} diff --git a/examples/materials/wear/make-house.ts b/examples/materials/wear/make-house.ts new file mode 100644 index 000000000..eef731e09 --- /dev/null +++ b/examples/materials/wear/make-house.ts @@ -0,0 +1,11 @@ +// Writes the corner house (house.ts) to media/house.glb, where wear.tsx's staticFile reads it. +// bun examples/materials/wear/make-house.ts +import { mkdirSync, writeFileSync } from "node:fs"; +import { join } from "node:path"; +import { houseGlb } from "./house"; + +const dir = join(import.meta.dir, "media"); +mkdirSync(dir, { recursive: true }); +const glb = houseGlb(); +writeFileSync(join(dir, "house.glb"), glb); +console.log(`make-house: ${join(dir, "house.glb")} (${glb.length} bytes)`); diff --git a/examples/materials/wear/wear.test.ts b/examples/materials/wear/wear.test.ts new file mode 100644 index 000000000..d7d0110dd --- /dev/null +++ b/examples/materials/wear/wear.test.ts @@ -0,0 +1,85 @@ +// The corner house (house.ts) and raea/wear's demo (wear.tsx): every part docs/wear.feature WR7 lists, openings cut +// through the walls (where cracks start), a valid .glb with one material per class, a still for every cause and for +// each of WR9's eight conditions by day and at dusk, and worn paint (docs/examples.feature EX9). +import { describe, expect, test } from "bun:test"; +import { readFileSync } from "node:fs"; +import { join } from "node:path"; +import { DEBUG_CAUSES, WEAR_CLASSES, WEAR_CONDITIONS } from "raea/wear"; +import { BAYS, CLASSES, DOOR, houseGlb, solids, SOUTH, STOREYS } from "./house"; + +type V3 = [number, number, number]; +const box = (s: V3[]) => [0, 1, 2].map((a) => [Math.min(...s.map((p) => p[a])), Math.max(...s.map((p) => p[a]))]); +const parts = solids(); +/** Whether any solid of `cls` holds the point. */ +const solidAt = (p: V3, cls = [...parts.keys()]) => + cls.some((c) => parts.get(c)!.some((s) => box(s).every(([lo, hi], a) => p[a] > lo + 1e-6 && p[a] < hi - 1e-6))); + +describe("the corner house", () => { + test("its classes are raea/wear's, every one used", () => { + const names = WEAR_CLASSES.map((c) => c.name); + for (const c of CLASSES) expect(names).toContain(c); + for (const c of CLASSES) expect(parts.get(c)!.length).toBeGreaterThan(0); + }); + + test("has every part WR7 names", () => { + const n = (c: string) => parts.get(c as (typeof CLASSES)[number])!.length; + // plinth, string course, sills, cornice and consoles, the door's surround; steps; balcony and hatch; gutter and + // downpipe; the two street plates; the roof + expect(n("sandstone")).toBeGreaterThan(40); + expect(n("granite")).toBeGreaterThanOrEqual(3); + expect(n("iron")).toBeGreaterThan(10); + expect(n("zinc")).toBeGreaterThanOrEqual(4); + expect(n("enamel")).toBe(2); + expect(n("slate")).toBe(2); + expect(n("copper")).toBe(1); + // the ground floor rusticated: bands set back 2 cm every 0.4 m up to the string course + const grooves = parts.get("plaster")!.filter((s) => { const b = box(s); return b[1][0] < 4.2 && Math.abs(b[2][1] + 0.02) < 1e-6; }); + expect(grooves.length).toBeGreaterThan(20); + }); + + test("its windows and door go through the walls, their glass 15 cm in", () => { + for (const st of STOREYS) { + for (const x of BAYS.south) { + if (st === STOREYS[0] && x === DOOR.at) continue; + const mid: V3 = [x, (st.sill + st.head) / 2 + 0.3, -0.05]; + expect(solidAt(mid, ["plaster"])).toBe(false); + expect(solidAt([x - 0.3, (st.sill + st.head) / 2 + 0.3, -0.16], ["glass"])).toBe(true); + } + for (const z of BAYS.east) expect(solidAt([SOUTH.x1 - 0.05, (st.sill + st.head) / 2 + 0.3, -z], ["plaster"])).toBe(false); + } + expect(solidAt([DOOR.at, 1.5, -0.05], ["plaster"])).toBe(false); + // and the wall between them is solid + expect(solidAt([(BAYS.south[0] + BAYS.south[1]) / 2, 2.5, -0.25], ["plaster"])).toBe(true); + }); + + test("is a .glb with one material per class, named for it", () => { + const glb = houseGlb(); + const dv = new DataView(glb.buffer, glb.byteOffset); + expect(dv.getUint32(0, true)).toBe(0x46546c67); + expect(dv.getUint32(8, true)).toBe(glb.length); + const len = dv.getUint32(12, true); + const json = JSON.parse(new TextDecoder().decode(glb.subarray(20, 20 + len))); + expect(json.materials.map((m: { name: string }) => m.name)).toEqual([...CLASSES]); + expect(json.meshes[0].primitives).toHaveLength(CLASSES.length); + expect(houseGlb()).toEqual(glb); + }); +}); + +describe("the demo", () => { + const src = readFileSync(join(import.meta.dir, "wear.tsx"), "utf8"); + test("has a still of every cause in false colour", () => { + const listed = src.match(/const CAUSES: WearCause\[\] = \[([^\]]+)\]/)![1].match(/"(\w+)"/g)!.map((s) => s.slice(1, -1)); + expect(listed.sort()).toEqual(Object.keys(DEBUG_CAUSES).sort()); + }); + test("draws worn paint with no bake, as (EX9), from light to heavy", () => { + expect(src).toContain("paint: () => "); + const amounts = [...src.matchAll(/shape: "\w+", wear: \{ amount: ([\d.]+)/g)].map((m) => Number(m[1])); + expect(amounts).toEqual([0.5, 0.8, 1]); + expect(src).toContain("extension={}"); + }); + test("draws each of WR9's eight conditions by day and at dusk", () => { + expect(Object.keys(WEAR_CONDITIONS)).toHaveLength(8); + expect(src).toContain("CONDITIONS.flatMap((c) => ["); + expect(src).toContain("[`${c}-dusk`, () => ]"); + }); +}); diff --git a/examples/materials/wear/wear.tsx b/examples/materials/wear/wear.tsx new file mode 100644 index 000000000..6e8026924 --- /dev/null +++ b/examples/materials/wear/wear.tsx @@ -0,0 +1,179 @@ +// raea/wear's demo (docs/wear.feature WR7): the corner house (house.ts) baked once and shaded. It is drawn new, +// after 80 years of a coal-burning city, and as a ruin. Each cause appears in false colour, and the house stands +// under each of WR9's eight conditions by day and at dusk. A shower crosses it as a timelapse (rain-passes). `paint` +// is the other wear, worn paint with no bake (, a material's `wear`; docs/examples.feature EX9). +// bun examples/materials/wear/make-house.ts (once: writes media/house.glb) +// raea render examples/materials/wear/wear.tsx --composition after +// The south front faces +z and the east front +x, so north is -z. The corner stands at (12, 0, 0). +import { AbsoluteFill, Composition, registerRoot, staticFile, useCurrentFrame } from "raea"; +import { Cuboid, Cylinder, Model, ToneMapping } from "raea/3d"; +import { ExtendedMaterial, ShaderExtension, StandardMaterial, WearExtension, type WearExtensionProps } from "raea/pbr"; +import { Camera3d } from "raea/camera"; +import { AmbientLight, DirectionalLight } from "raea/light"; +import { Mesh3d } from "raea/mesh"; +import { Quat, Transform } from "raea/transform"; +import { WEAR_CONDITIONS, wearBake, wearDebris, wearShader, weatherAt, type WearAge, type WearCause, type WearCondition, type WearShaderOptions, type WearSpell } from "raea/wear"; +import { CLASSES, SOUTH } from "./house"; + +type V3 = [number, number, number]; + +/** The house's bake: each material is its own class, Berlin's latitude, the walk round the corner trodden. */ +export function bakeHouse() { + return wearBake({ + src: staticFile("house.glb"), + env: { up: [0, 1, 0], north: [0, 0, -1], density: 16, walk: ["ground"], sun: { lat: 52.5 } }, + classes: Object.fromEntries(CLASSES.map((c) => [c, c])), + }); +} + +/** The ages the demo shows: a fresh coat, 80 years in a coal-burning city, and 90 years left to go. */ +export const AGES = { + new: { years: 0 }, + old: { years: 80, soot: 0.85, upkeep: 0.35 }, + ruin: { years: 90, soot: 0.85, upkeep: 0.05 }, +} as const satisfies Record; + +/** The light for a time of day and the sky's weather: the sun and its colour, the sky's fill, the backdrop. */ +function lightOf(dusk: boolean, sky: "clear" | "overcast" | "storm") { + // the sun from the south-west, so the south front is lit and the east one in shade; at dusk low in the west + const sun: V3 = dusk ? [-30, 4, 12] : [-8, 14, 20]; + const dim = sky === "clear" ? 1 : sky === "overcast" ? 0.25 : 0.1; + return { + sun, + lux: (dusk ? 1800 : 9000) * dim, + color: dusk ? "#ffb070" : "#f2ece0", + fill: (dusk ? 140 : 500) * (sky === "clear" ? 1 : 1.4), + fillColor: dusk ? "#5a6890" : sky === "clear" ? "#c4ccd6" : "#a9b0b8", + backdrop: dusk ? (sky === "clear" ? "#3a4568" : "#2a2f3a") : sky === "clear" ? "#aab8c8" : "#8c939b", + }; +} + +const SKY: Record = { spring: "clear", summer: "clear", autumn: "overcast", winter: "clear", snow: "overcast", blizzard: "storm", rain: "overcast", thunder: "storm" }; + +interface HouseProps { + look?: Omit; + debug?: WearCause; + dusk?: boolean; + sky?: "clear" | "overcast" | "storm"; + eye?: V3; + at?: V3; + fov?: number; +} + +/** The corner house from across the junction, weathered by `look` (or a cause in false colour), with the debris its + * age has brought down on the walk. */ +export function House({ look, debug, dusk = false, sky = "clear", eye = [24, 4, 17], at = [9, 6.5, -2], fov = 52 }: HouseProps) { + const baked = bakeHouse(); + const shader = look || debug ? wearShader({ baked, ...look, debug }) : undefined; + const debris = look?.age && !debug ? wearDebris(baked, look.age) : []; + const l = lightOf(dusk, sky); + const flat = debug !== undefined; + return ( + + <> + + + + + + {shader ? } extension={} /> : null} + + {debris.flatMap((d, i) => + // a heap is a few lumps of render lying along its front's foot (the east front's runs along z), more and + // bigger under a looser coat; each rests on the walk, which the clipping check reads as passing into the house + lumps(d.loss ?? 0.5, i).map(([u, w, size, yaw], k) => { + const alongX = d.at[0] <= SOUTH.x1; + const half: V3 = [size * (alongX ? 1.6 : 1), size * 0.5, size * (alongX ? 1 : 1.6)]; + return ( + + + + + ); + }), + )} + + + ); +} + +/** A heap's lumps: [along the wall, out from it, size, yaw], three to five by its loss potential, placed by its index. */ +function lumps(loss: number, seed: number): [number, number, number, number][] { + const r = (k: number) => { + const x = Math.sin(seed * 12.9898 + k * 78.233) * 43758.5453; + return x - Math.floor(x); + }; + const n = 3 + Math.round(2 * loss); + return Array.from({ length: n }, (_, k) => [(r(4 * k) - 0.5) * 0.5, (r(4 * k + 1) - 0.5) * 0.18, 0.025 + 0.04 * r(4 * k + 2) * loss, (r(4 * k + 3) - 0.5) * 1.4]); +} + +const old = { age: AGES.old }; +/** Where the losses are easiest to read: the east front's ground floor and its foot, up close from the walk. */ +const NEAR = { eye: [16.8, 1.7, -0.8] as V3, at: [12, 1.2, -4.6] as V3, fov: 50 }; +const DOOR = { eye: [8.5, 1.8, 6.5] as V3, at: [6, 1.9, 0] as V3, fov: 50 }; + +/** A shower crossing the house: dry, raining from minute 6 to 40, drying after. A frame is half a minute. */ +export const SHOWER: WearSpell[] = [{ at: 0 }, { at: 6, rain: 1 }, { at: 40 }]; + +function RainPasses() { + const minutes = useCurrentFrame() * 0.5; + const weather = weatherAt({ day: 130 }, SHOWER, minutes); + const raining = minutes >= 6 && minutes < 40; + return ; +} + +/** Worn paint with no bake: street iron painted green, its edges chipped to the metal, grime low and rust run down, + * by how worn each is (a bollard, a cabinet turned on the walk, a railing post). */ +export const PAINTED: { at: V3; yaw: number; shape: "bollard" | "cabinet" | "post"; wear: WearExtensionProps }[] = [ + { at: [-1.4, 0, 0], yaw: 0, shape: "bollard", wear: { amount: 0.5 } }, + { at: [0.2, 0, -0.3], yaw: 0.6, shape: "cabinet", wear: { amount: 0.8, grime: 0.7, seed: 3 } }, + { at: [1.6, 0, 0.2], yaw: 0, shape: "post", wear: { amount: 1, chips: 0.9, rust: 0.7, rust_color: "#7e4220", seed: 5 } }, +]; + +function Paint() { + const green = ; + return ( + + <> + + + + + {PAINTED.map(({ at, yaw, shape, wear }) => ( + + {shape === "cabinet" ? : } + } /> + + ))} + + + + ); +} + +const CAUSES: WearCause[] = ["class", "sky", "sun", "cavity", "edge", "flow", "deposit", "touch", "ground", "element", "open", "winter", "drift", "litter", "crack", "loss"]; +const CONDITIONS = Object.keys(WEAR_CONDITIONS) as WearCondition[]; + +export const SHOTS: Record JSX.Element> = { + before: () => , + new: () => , + after: () => , + ruin: () => , + "ruin-near": () => , + door: () => , + paint: () => , + ...Object.fromEntries(CAUSES.map((c) => [`debug-${c}`, () => ])), + ...Object.fromEntries(CONDITIONS.flatMap((c) => [ + [c, () => ], + [`${c}-dusk`, () => ], + ])), +}; + +registerRoot(() => ( + <> + {Object.entries(SHOTS).map(([id, Shot]) => ( + + ))} + + +)); diff --git a/runtime/scene/Cargo.toml b/runtime/scene/Cargo.toml index 1cc381042..12205b363 100644 --- a/runtime/scene/Cargo.toml +++ b/runtime/scene/Cargo.toml @@ -13,8 +13,6 @@ raea-runtime-look = { path = "../look" } raea-runtime-scene2d = { path = "../scene2d" } bevy = { version = "=0.20.0", default-features = false, features = ["std"] } serde_json = "1" -# a material's `wear` prop as its row's columns -raea-sys-wear = { path = "../../systems/wear" } # a material's `procedural` prop as its row's columns raea-sys-procmat = { path = "../../systems/procmat" } # a review's fixed camera (RAEA_CAMERA) in place of the scene's own diff --git a/runtime/scene/src/parts.rs b/runtime/scene/src/parts.rs index d9eb1ec90..7ee0bde05 100644 --- a/runtime/scene/src/parts.rs +++ b/runtime/scene/src/parts.rs @@ -231,7 +231,6 @@ pub(crate) fn meshes_rows(tr: &Tracks, names: &[String], p: &mut Program) { } grid_columns(&mut row, m0); paint_columns(&mut row, m0); - raea_sys_wear::columns(&mut row, m0); raea_sys_procmat::columns(&mut row, m0); placement(p, &mut row, &id, &its); visible(p, &mut row, &id, &track); diff --git a/sdk/plugins/src/bevy.gen.tsx b/sdk/plugins/src/bevy.gen.tsx index c1f4ca9e2..f6a9c82fd 100644 --- a/sdk/plugins/src/bevy.gen.tsx +++ b/sdk/plugins/src/bevy.gen.tsx @@ -1,6 +1,6 @@ // Generated by raea-bevy-sdk from raea's Bevy App's TypeRegistry (bevy (bevy)); don't edit, regenerate -// (tools/bevy-plugins.sh gen). 389 component, 12 event, 38 message, 53 resource. -// - In a scene (TSX): 442 wrappers, each a (or ) naming its type path, which raea-render +// (tools/bevy-plugins.sh gen). 388 component, 12 event, 38 message, 53 resource. +// - In a scene (TSX): 441 wrappers, each a (or ) naming its type path, which raea-render // applies with ReflectComponent::insert. Put a component inside the it belongs to; sets the // plugin's resources. // - In a TypeScript program (raea/bevy's BevyApp): `bevy` holds a typed handle for every component, @@ -2555,9 +2555,6 @@ export type MeshMaterial3dExtendedMaterialStandardMaterialProcedural = string | /** bevy_pbr::mesh_material::MeshMaterial3d> */ export type MeshMaterial3dExtendedMaterialStandardMaterialShaderExt = string | Record /* bevy_asset::handle::Handle>: in a Canvas3D an asset path or the asset inline */; -/** bevy_pbr::mesh_material::MeshMaterial3d> */ -export type MeshMaterial3dExtendedMaterialStandardMaterialWear = string | Record /* bevy_asset::handle::Handle>: in a Canvas3D an asset path or the asset inline */; - /** bevy_pbr::mesh_material::MeshMaterial3d */ export type MeshMaterial3dStandardMaterial = string | Record /* bevy_asset::handle::Handle: in a Canvas3D an asset path or the asset inline */; @@ -6016,11 +6013,6 @@ export function MeshMaterial3dExtendedMaterialStandardMaterialShaderExt(props: { return ; } -/** bevy_pbr::mesh_material::MeshMaterial3d> (component); default {"Uuid":"97128bb1-2588-480b-bdc6-87b4adbec477"} */ -export function MeshMaterial3dExtendedMaterialStandardMaterialWear(props: { value?: MeshMaterial3dExtendedMaterialStandardMaterialWear; from?: number }) { - return ; -} - /** bevy_pbr::mesh_material::MeshMaterial3d (component); default {"Uuid":"97128bb1-2588-480b-bdc6-87b4adbec477"} */ export function MeshMaterial3dStandardMaterial(props: { value?: MeshMaterial3dStandardMaterial; from?: number }) { return ; @@ -7703,8 +7695,6 @@ export const bevy = { MeshMaterial3dExtendedMaterialStandardMaterialProcedural: component("bevy_pbr::mesh_material::MeshMaterial3d>"), /** bevy_pbr::mesh_material::MeshMaterial3d> (component) */ MeshMaterial3dExtendedMaterialStandardMaterialShaderExt: component("bevy_pbr::mesh_material::MeshMaterial3d>"), - /** bevy_pbr::mesh_material::MeshMaterial3d> (component) */ - MeshMaterial3dExtendedMaterialStandardMaterialWear: component("bevy_pbr::mesh_material::MeshMaterial3d>"), /** bevy_pbr::mesh_material::MeshMaterial3d (component) */ MeshMaterial3dStandardMaterial: component("bevy_pbr::mesh_material::MeshMaterial3d"), /** bevy_pbr::mesh_material::MeshMaterial3d (component) */ diff --git a/sdk/raea/conformance/bevy3d.test.tsx b/sdk/raea/conformance/bevy3d.test.tsx index 46be0234a..4c7174b51 100644 --- a/sdk/raea/conformance/bevy3d.test.tsx +++ b/sdk/raea/conformance/bevy3d.test.tsx @@ -168,6 +168,18 @@ describe("Mesh3d, Camera3d and StandardMaterial", () => { expect(() => html(} extension={} />)).toThrow(/unlit/); }); + test("wear is a surface shader of raea's own (EX9): its uniforms, none at amount 0, alone", () => { + const out = html(); + expect(out).not.toContain("wear":{"); + expect(out).toContain("fn surface(in: VertexOutput, pbr: ptr<function, PbrInput>)"); + expect(out).toContain(""wear":[0.6,0.08,0.6,0.5]"); + expect(out).toContain(""wear2":[0.25,2,0,0]"); + expect(out).toContain(""chip_color":"#333333""); + expect(html()).toBe(html()); + expect(() => html() {}" }} />)).toThrow(/wear or shader/); + expect(() => html()).toThrow(/grid or wear/); + }); + test("inside a Model a StandardMaterial re-covers with only the fields given, as the old material did", () => { const m = (el: React.ReactElement) => html({el}); expect(m()).toBe(m()); diff --git a/sdk/render/src/3d/materials.tsx b/sdk/render/src/3d/materials.tsx index 0a7c8d964..f9486637b 100644 --- a/sdk/render/src/3d/materials.tsx +++ b/sdk/render/src/3d/materials.tsx @@ -1,6 +1,7 @@ // Materials: surfaces drawn on, standard and physical materials, toon bands and outlines. import { toHex } from "../colour"; import { checkOverlays, type GridOverlay, type PaintOverlay, type ProceduralSurface, type WearOverlay } from "../overlays"; +import { wornShader } from "../worn"; import { useAnimation3d } from "@raea/math/animate"; import { Animate3d, apply3d, node3d } from "./all"; @@ -60,7 +61,8 @@ export interface MeshStandardMaterialProps extends SurfaceDrawProps { grid?: GridOverlay; /** under a paint look, the surface broken up by noise: PaintOverlay, overlays.ts */ paint?: PaintOverlay; - /** a worn surface, fixed on the part as it moves (systems/wear): WearOverlay, overlays.ts */ + /** a worn surface, fixed on the part as it moves (worn.ts, a surface shader; not with `shader` or `grid`): + * WearOverlay, overlays.ts */ wear?: WearOverlay; /** a pattern made on the GPU with dust, dirt and worn edges (systems/procmat): ProceduralSurface, overlays.ts */ procedural?: ProceduralSurface; @@ -301,6 +303,14 @@ export function checkMaterial(owner: string, props: Record): vo const v = props[k]; if (v !== undefined && !(k === "map" && v === null) && !(typeof v === "string" && v !== "")) throw new TypeError(`${owner}: ${k} must be a picture's path (staticFile("floor_diff.jpg")) or a data: URL, got ${JSON.stringify(v)}`); } + // `wear` is a surface shader of raea's own (worn.ts, docs/examples.feature EX9); none at amount 0 + if (props.wear !== undefined) { + if (props.shader !== undefined) throw new TypeError(`${owner}: wear is a surface shader of its own; give wear or shader, not both`); + if (props.grid !== undefined) throw new TypeError(`${owner}: grid draws alone; give grid or wear, not both`); + const w = props.wear as WearOverlay; + delete props.wear; + if (w.amount > 0) props.shader = wornShader(w); + } if (props.shader !== undefined) props.shader = surfaceShader(owner, props.shader as SurfaceShaderSpec); if (props.sampler !== undefined) samplerSpec(owner, props.sampler as SamplerSpec); if (props.samplers !== undefined) { @@ -318,7 +328,7 @@ export function checkMaterial(owner: string, props: Record): vo /** A physically based surface for the Mesh it's inside. * `grid` draws graph paper over it (engine/render grid.rs): - * `wear` chips, grimes and rusts it in the part's own space (systems/wear): + * `wear` chips, grimes and rusts it in the part's own space (worn.ts): * @deprecated , raea/pbr (Bevy's fields: base_color, perceptual_roughness, metallic) */ export function MeshStandardMaterial(props: MeshStandardMaterialProps) { diff --git a/sdk/render/src/bevy3d/extensions.tsx b/sdk/render/src/bevy3d/extensions.tsx index 4d7b4d07a..9e2806b12 100644 --- a/sdk/render/src/bevy3d/extensions.tsx +++ b/sdk/render/src/bevy3d/extensions.tsx @@ -51,7 +51,7 @@ export function PaintExtension(_: PaintExtensionProps): ReactNode { throw new TypeError("PaintExtension goes in an ExtendedMaterial: } extension={} />"); } -/** raea's extension of StandardMaterial that wears it (the engine's Wear MaterialExtension, systems/wear): its paint +/** raea's extension of StandardMaterial that wears it (a surface shader of raea's own, worn.ts): its paint * mottled, chipped back to `chip_color` on edges and a few spots, `grime` gathered low and underneath and `rust` run * down in streaks, fixed in the part's own space as it moves. `amount` 0-1; `chips`, `grime` and `rust` each 0-1 of it * (0.6, 0.5, 0.25); `scale` a blotch's size in metres (0.08); `seed` moves the pattern. It goes in an @@ -77,8 +77,8 @@ export interface WearExtensionProps { rust_color?: string; } -/** raea's chips, grime and rust over a StandardMaterial, as an ExtendedMaterial's extension (systems/wear): - * @bevy bevy_pbr::mesh_material::MeshMaterial3d> */ +/** raea's chips, grime and rust over a StandardMaterial, as an ExtendedMaterial's extension: a surface shader of + * raea's own (worn.ts) on the hook a ShaderExtension uses, so its Bevy type is ShaderExtension's. */ export function WearExtension(_: WearExtensionProps): ReactNode { throw new TypeError("WearExtension goes in an ExtendedMaterial: } extension={} />"); } diff --git a/sdk/render/src/overlays.ts b/sdk/render/src/overlays.ts index bdb9a0e05..a59296e19 100644 --- a/sdk/render/src/overlays.ts +++ b/sdk/render/src/overlays.ts @@ -1,6 +1,6 @@ -// A material's overlays, drawn over its standard surface by the engine: graph paper (`grid`, raea-render's grid.rs), -// a paint look's breakup (`paint`, paint.rs), wear (`wear`, systems/wear) and a procedural surface (`procedural`, -// systems/procmat). Their props and checks; 3d.tsx's materials take them all, a Model takes `grid`. +// A material's overlays, drawn over its standard surface: graph paper (`grid`, raea-render's grid.rs), a paint look's +// breakup (`paint`, paint.rs), wear (`wear`, a surface shader of raea's own, worn.ts) and a procedural surface +// (`procedural`, systems/procmat). Their props and checks; 3d.tsx's materials take them all, a Model takes `grid`. import { toHex } from "./colour"; /** graph paper over the surface (greybox levels): lines every `cell` world units (fixed in the world, so they run on @@ -13,7 +13,7 @@ export interface GridOverlay { cell: number; major?: number; color?: string; edg * uneven paint */ export interface PaintOverlay { breakup?: number; scale?: number; color?: string; amount?: number } -/** a worn surface (systems/wear), fixed in the part's own space so it rides with a moving part: `amount` 0..1 of +/** a worn surface (worn.ts), fixed in the part's own space so it rides with a moving part: `amount` 0..1 of * wear, its paint chipped back to `chipColor` at edges (`chips`), `grime` low and underneath, `rust` run down in * streaks (each 0..1 of the amount), in blotches of `scale` metres (0.08); `seed` moves the pattern */ export interface WearOverlay { amount: number; scale?: number; chips?: number; grime?: number; rust?: number; seed?: number; chipColor?: string; grimeColor?: string; rustColor?: string } diff --git a/sdk/render/src/worn.ts b/sdk/render/src/worn.ts new file mode 100644 index 000000000..7766e497b --- /dev/null +++ b/sdk/render/src/worn.ts @@ -0,0 +1,119 @@ +// Worn paint (docs/examples.feature EX9): the standard material with use written over it, as a surface shader on +// raea's public hook (raea-sys-shader), where it was the engine's own MaterialExtension (raea-sys-wear) until 11-19. +// MeshStandardMaterial's `wear` and raea/pbr's draw it. Paint mottled by noise, its edges chipped back +// to `chipColor` (the metal under the paint, shinier), grime gathered low and on undersides, and rust run down in +// streaks. The noise is taken in the mesh's own space, not the world's, so a walking robot's wear stays where it is on +// each part instead of swimming over it; parts built in one space (a rigged build's pieces, in the rest pose) share +// it, so their wear lines up across a seam. Edges are found from how fast the surface's normal turns on screen +// against how fast its position does (its curvature, 1 / radius), so a rounded edge of a few millimetres chips and a +// broad face doesn't. raea/wear's wearShader is the other wear: the weather's, baked from a building's own shape. +import type { WearOverlay } from "./overlays"; + +/** The surface hook. Its uniforms: `wear` (amount, a blotch's size in metres, chips, grime), `wear2` (rust, seed), + * and the chips', grime's and rust's colours. */ +export const WORN_WESL = /* wgsl */ ` +fn worn_hash(p: vec3) -> f32 { + let q = fract(p * 0.3183099 + vec3(0.1, 0.2, 0.3)); + let r = q * 17.0; + return fract(r.x * r.y * r.z * (r.x + r.y + r.z)); +} + +fn worn_vnoise(p: vec3) -> f32 { + let i = floor(p); + let f = fract(p); + let u = f * f * (3.0 - 2.0 * f); + let a = mix(mix(worn_hash(i), worn_hash(i + vec3(1.0, 0.0, 0.0)), u.x), mix(worn_hash(i + vec3(0.0, 1.0, 0.0)), worn_hash(i + vec3(1.0, 1.0, 0.0)), u.x), u.y); + let b = mix(mix(worn_hash(i + vec3(0.0, 0.0, 1.0)), worn_hash(i + vec3(1.0, 0.0, 1.0)), u.x), mix(worn_hash(i + vec3(0.0, 1.0, 1.0)), worn_hash(i + vec3(1.0, 1.0, 1.0)), u.x), u.y); + return mix(a, b, u.z); +} + +// four octaves, 0..1 +fn worn_fbm(p: vec3) -> f32 { + var s = 0.0; + var w = 0.5; + var q = p; + for (var k = 0; k < 4; k++) { + s += w * worn_vnoise(q); + q = q * 2.03 + vec3(1.7, 9.2, 3.1); + w *= 0.5; + } + return s / 0.9375; +} + +fn surface(in: VertexOutput, pbr: ptr) { + let amount = u_wear().x; + let scale = u_wear().y; + let chips = u_wear().z; + let grimes = u_wear().w; + let rusts = u_wear2().x; + let seed = u_wear2().y; + + var p = in.world_position.xyz; + var n = normalize(in.world_normal); +@if(VERTEX_OUTPUT_INSTANCE_INDEX) { + // the mesh's own space, so the wear rides with the part + let m = bevy_pbr::render::mesh_functions::get_local_from_world(in.instance_index); + p = (m * vec4(in.world_position.xyz, 1.0)).xyz; + n = normalize((m * vec4(n, 0.0)).xyz); +} + let q = p / scale + vec3(seed * 13.1); + + // curvature (1 / metres): how fast the normal turns against how fast the position moves, on screen + let curve = length(fwidth(in.world_normal)) / max(length(fwidth(in.world_position.xyz)), 1e-5); + let edge = smoothstep(25.0, 90.0, curve) + 0.5 * smoothstep(0.12, 0.35, 1.0 - max(abs(n.x), max(abs(n.y), abs(n.z)))); + let a = amount; + + var c = (*pbr).material.base_color.rgb; + var rough = (*pbr).material.perceptual_roughness; + var metal = (*pbr).material.metallic; + + // paint: mottled a little, and duller where it's thin + let mottle = worn_fbm(q * 0.6); + c *= 1.0 + (mottle - 0.5) * 0.22 * a; + rough = clamp(rough + (worn_fbm(q * 1.7 + 5.0) - 0.5) * 0.3 * a, 0.04, 1.0); + + // grime: low, in hollows and undersides, broken up + let low = clamp(-n.y, 0.0, 1.0) * 0.6 + smoothstep(0.55, 0.85, worn_fbm(q * 0.35 + 20.0)); + let g = clamp(low * grimes * a, 0.0, 0.85) * smoothstep(0.3, 0.7, worn_fbm(q * 2.3 + 40.0) + 0.25); + c = mix(c, u_grime_color().rgb, g); + rough = mix(rough, 0.9, g); + + // rust: streaks run down from blotches (noise squashed along local y) + let streak = worn_fbm(vec3(q.x * 3.0, q.y * 0.25, q.z * 3.0) + 60.0); + let blotch = smoothstep(0.6, 0.8, worn_fbm(q * 0.5 + 80.0)); + let r = clamp((blotch + smoothstep(0.62, 0.8, streak) * 0.6) * rusts * a, 0.0, 0.9); + c = mix(c, u_rust_color().rgb * (0.7 + 0.6 * worn_vnoise(q * 6.0)), r); + rough = mix(rough, 0.95, r); + metal = mix(metal, 0.0, r); + + // chips: the paint gone at edges and a few scattered spots, the metal under it showing, shinier; an edge lowers + // the bar a long way, so at full wear most edges chip and only the odd spot on a broad face does + let s = chips * a; + let field = worn_fbm(q * 2.5 + 100.0) + edge * 0.5 - 0.2; + let chip = smoothstep(1.0 - s * 0.55, 1.04 - s * 0.55, field); + c = mix(c, u_chip_color().rgb, chip); + rough = mix(rough, 0.32, chip); + metal = mix(metal, 0.85, chip); + + (*pbr).material.base_color = vec4(c, (*pbr).material.base_color.a); + (*pbr).material.perceptual_roughness = rough; + (*pbr).material.metallic = metal; +} +`; + +const share = (v: number | undefined, d: number) => Math.min(1, Math.max(0, v ?? d)); + +/** A material's `wear` as the surface shader that draws it: `{ wesl, uniforms }` for its `shader`. */ +export function wornShader(w: WearOverlay): { wesl: string; uniforms: Record } { + const amount = Math.min(1, w.amount); + return { + wesl: WORN_WESL, + uniforms: { + wear: [amount, w.scale !== undefined && w.scale > 0 ? w.scale : 0.08, share(w.chips, 0.6), share(w.grime, 0.5)], + wear2: [share(w.rust, 0.25), w.seed ?? 0, 0, 0], + chip_color: w.chipColor ?? "#3a3c40", + grime_color: w.grimeColor ?? "#3b3226", + rust_color: w.rustColor ?? "#7a3f1c", + }, + }; +} diff --git a/sdk/wear/src/causes.ts b/sdk/wear/src/causes.ts index 0d0bef06b..f42975f45 100644 --- a/sdk/wear/src/causes.ts +++ b/sdk/wear/src/causes.ts @@ -3,10 +3,25 @@ // causes0 = sky (rain's reach), sun (the year's sun), cavity, edge (convex arris) // causes1 = flow (run-off passing), deposit (what it left), deposit kind (60 x: 1 grime, 2 rust, 3 copper, 4 zinc), touch // causes2 = ground (height over the walk, 0-4 m), element (the chart's number), open (the whole sky seen), class -// causes3 = winter sun (December's), drift (driven snow), litter (where blown leaves and snow settle) +// causes3 = winter sun (December's), drift (driven snow), litter (where blown leaves and snow settle), crack (1 - the +// distance to the nearest crack from an opening's corner over CRACK_REACH; raea-sys-damage, WR6) // The maps load as colour (sRGB) textures, so a colour channel is re-encoded to read the byte the bake wrote; alpha is // stored linear. Element and class are numbers, read with textureLoad so a filtered read never blends two into a third. +/** How far the bake keeps a texel's distance to a crack, metres (raea-sys-damage's REACH). */ +export const CRACK_REACH = 0.25; +/** The loss potential's edges and weights, as raea-sys-damage's LOSS has them (its test compares the two): how readily + * a coat comes off at the damp foot (ground 0.7-1.3 m), where run-off soaks what the rain doesn't wash (flow 0.5-0.9, + * the rain's reach 0.35-0.85), at a knocked arris low down (edge 0.75-0.9, below 1.4-2.2 m) and along a crack + * (within 0.12 m); then the soak's, the arris's and (CRACK_WEIGHT) the crack's weight against the foot's 1. */ +export const LOSS = [0.7, 1.3, 0.5, 0.9, 0.35, 0.85, 0.75, 0.9, 1.4, 2.2, 0.12, 0.8, 0.7] as const; +export const CRACK_WEIGHT = 0.6; +/** Neglect past this is a house left empty (its panes broken and boarded, its slates gone, fallen render left on the + * walk), full at 1: a lived-in house mends and sweeps these however poorly it is kept. */ +export const ABANDON_FROM = 0.85; +const f = (x: number) => (Number.isInteger(x) ? `${x}.0` : `${x}`); +const L = LOSS.map(f); + /** The uniforms the module reads: `up` (the bake's up), `age` (years since the last repair, soot, upkeep, the bake's * texels a metre), `wx` (wet, snow, storm, ice) and `season` (damp, dust, leaves, melt). */ export const CAUSES = /* wgsl */ ` @@ -16,7 +31,7 @@ struct WearCauses { sky: f32, sun: f32, cav: f32, edge: f32, flow: f32, dep: f32, kind: i32, touch: f32, ground: f32, elem: f32, open: f32, cls: i32, - dec: f32, drift: f32, litter: f32 + dec: f32, drift: f32, litter: f32, crack: f32 } fn wear_causes(uv: vec2) -> WearCauses { @@ -33,10 +48,19 @@ fn wear_causes(uv: vec2) -> WearCauses { wear_enc(a.r), wear_enc(a.g), wear_enc(a.b), a.a, wear_enc(f.r), wear_enc(f.g), kind, f.a, wear_enc(b.r) * 4.0, round(wear_enc(x.g) * 255.0), wear_enc(b.b), cls, - wear_enc(d.r), wear_enc(d.g), wear_enc(d.b) + wear_enc(d.r), wear_enc(d.g), wear_enc(d.b), (1.0 - d.a) * ${f(CRACK_REACH)} ); } +// how readily the coat here comes off (WR6): raea-sys-damage's loss, so the debris the bake put down lies under it +fn wear_loss(c: WearCauses) -> f32 { + let foot = 1.0 - smoothstep(${L[0]}, ${L[1]}, c.ground); + let soak = smoothstep(${L[2]}, ${L[3]}, c.flow) * (1.0 - smoothstep(${L[4]}, ${L[5]}, c.sky)); + let arris = smoothstep(${L[6]}, ${L[7]}, c.edge) * (1.0 - smoothstep(${L[8]}, ${L[9]}, c.ground)); + let near = 1.0 - smoothstep(0.0, ${L[10]}, c.crack); + return max(max(foot, ${L[11]} * soak), max(${L[12]} * arris, ${f(CRACK_WEIGHT)} * near)); +} + // value noise over the face, in metres fn wear_h21(p: vec2) -> f32 { var q = fract(p * vec2(123.34, 456.21)); @@ -62,24 +86,28 @@ fn wear_fbm2(p: vec2) -> f32 { } // where the point is: how far its face looks up, its place on the face in metres (along a wall and up it; two -// horizontal axes on a level face), its height over the walk, and how upright the face is -struct WearGeo { up: f32, p: vec2, h: f32, wall: f32 } +// horizontal axes on a level face), its height over the walk, how upright the face is, a pixel's size in metres +// (from the caller, before any branch: derivatives need uniform control flow) and the parallax: how far a point a +// metre behind the face shifts in its place as the eye sees it (what's behind lost render is drawn there) +struct WearGeo { up: f32, p: vec2, h: f32, wall: f32, px: f32, par: vec2 } -fn wear_geo(wp: vec3, nrm: vec3, c: WearCauses) -> WearGeo { +fn wear_geo(wp: vec3, nrm: vec3, c: WearCauses, eye: vec3, px: f32) -> WearGeo { let U = normalize(u_up()); let n = normalize(nrm); let up = dot(n, U); let side = n - U * up; - var p: vec2; + var ax = U; + var ay = U; if (length(side) > 0.3) { - let t = normalize(cross(U, side)); - p = vec2(dot(wp, t), dot(wp, U)); + ax = normalize(cross(U, side)); } else { let r = select(vec3(1.0, 0.0, 0.0), vec3(0.0, 0.0, 1.0), abs(U.x) > 0.9); - let e1 = normalize(cross(U, r)); - p = vec2(dot(wp, e1), dot(wp, cross(U, e1))); + ax = normalize(cross(U, r)); + ay = cross(U, ax); } - return WearGeo(up, p, c.ground, 1.0 - smoothstep(0.5, 0.8, abs(up))); + let v = normalize(eye); + let par = -vec2(dot(v, ax), dot(v, ay)) / max(dot(v, n), 0.25); + return WearGeo(up, vec2(dot(wp, ax), dot(wp, ay)), c.ground, 1.0 - smoothstep(0.5, 0.8, abs(up)), px, par); } // what years of weather left, by cause: the same in every season @@ -87,7 +115,7 @@ struct WearMarks { age: f32, upkeep: f32, wear: f32, wash: f32, shelter: f32, tuck: f32, crust: f32, tear: f32, stain: f32, damp: f32, salt: f32, splash: f32, - low: f32, chip: f32 + low: f32, chip: f32, loss: f32, neglect: f32, abandon: f32 } fn wear_marks(c: WearCauses, g: WearGeo) -> WearMarks { @@ -117,7 +145,13 @@ fn wear_marks(c: WearCauses, g: WearGeo) -> WearMarks { // chips need a real arris, so a bake of 12 texels a metre or finer (at 4 an edge spreads 25 cm); people and carts // reach below 2.2 m let chip = step(12.0, u_age().w) * smoothstep(0.75, 0.9, c.edge) * low * step(0.68 - 0.2 * (1.0 - upkeep), wear_vn2(g.p * 16.0 + vec2(c.elem * 9.0, 0.0))) * step(0.05, age); - return WearMarks(age, upkeep, wear, wash, shelter, tuck, crust, tear, stain, damp, salt, splash, low, chip); + // WR6: how readily the coat comes off here, and how far neglect has let things go (little while kept up) + let loss = wear_loss(c) * g.wall; + let neglect = clamp(age * (1.15 - upkeep), 0.0, 1.0); + // left empty: neglect past what a lived-in house lets go (broken panes, slates and fallen render are mended or + // swept while anyone lives there), the whole house's, so by its own upkeep and not each element's draw + let abandon = smoothstep(${f(ABANDON_FROM)}, 1.0, age * (1.15 - clamp(u_age().z, 0.0, 1.0))); + return WearMarks(age, upkeep, wear, wash, shelter, tuck, crust, tear, stain, damp, salt, splash, low, chip, loss, neglect, abandon); } // a surface's own colour, roughness and metalness as the recipes change them diff --git a/sdk/wear/src/debug.ts b/sdk/wear/src/debug.ts index 462afba1e..408235a6e 100644 --- a/sdk/wear/src/debug.ts +++ b/sdk/wear/src/debug.ts @@ -32,6 +32,10 @@ export const DEBUG_CAUSES = { litter: "vec3(1.0, 0.5, 0.1) * c.litter", /** the material class, by WEAR_CLASSES' colour; magenta where the bake found none */ class: "wear_class_colour(c.cls)", + /** nearness to a crack from an opening's corner (WR6), in red */ + crack: "vec3(1.0, 0.25, 0.1) * (1.0 - c.crack / 0.25)", + /** how readily the coat comes off (WR6): the damp foot, soaked faces, knocked arrises, cracks */ + loss: "vec3(wear_loss(c))", } as const; export type WearCause = keyof typeof DEBUG_CAUSES; diff --git a/sdk/wear/src/index.ts b/sdk/wear/src/index.ts index 405585cd4..7fdf4d0a1 100644 --- a/sdk/wear/src/index.ts +++ b/sdk/wear/src/index.ts @@ -10,29 +10,33 @@ // // The same spec goes on one glTF material ( as the base), a // , or a over the whole scene. A surface without the -// bake's second UV set is drawn as it was. +// bake's second UV set is drawn as it was. Crumbling (WR6) follows the same age: render lost to the brick, paint to +// the primer and the wood, enamel to the iron, cracks from the openings' corners, panes broken or boarded, slates +// gone; `wearDebris(baked, age)` is the debris that age has brought down, where the bake put it. import { hasNative, native, type NativeCalls } from "@raea/app/native"; -import { CAUSES } from "./causes"; +import { ABANDON_FROM, CAUSES } from "./causes"; import { debugHook, DEBUG_CAUSES, type WearCause } from "./debug"; import { HELPERS, RECIPES, SHARED, WEATHER } from "./recipes"; export { DEBUG_CAUSES, type WearCause } from "./debug"; +export { ABANDON_FROM, CRACK_REACH, CRACK_WEIGHT, LOSS } from "./causes"; +export { WEAR_CONDITIONS, WEATHER_RATES, weatherAt, type WearCondition, type WearSpell } from "./weather"; /** The material classes, in the bake's order (causes2's alpha is 16 x (the place + 1)), each with its colour in the * debug view and what the causes do to it. */ export const WEAR_CLASSES = [ - { name: "plaster", colour: [0.95, 0.9, 0.75], marks: "washed clean and chalky; soot grey where sheltered, darkest under cornices; dark tears from sill ends; splash to 0.4 m and a damp tide at 0.6-1.2 m; blown at the foot; chipped arrises low down; a grease band" }, - { name: "brick", colour: [0.75, 0.3, 0.2], marks: "mortar washed out; soot black where sheltered; efflorescence under ledges; a tide line, green on north faces; spalled faces" }, + { name: "plaster", colour: [0.95, 0.9, 0.75], marks: "washed clean and chalky; soot grey where sheltered, darkest under cornices; dark tears from sill ends; splash to 0.4 m and a damp tide at 0.6-1.2 m; by neglect blown to the brick behind at the damp foot, under sills, at knocked arrises and along cracks, and cracked from the openings' corners; chipped arrises low down; a grease band" }, + { name: "brick", colour: [0.75, 0.3, 0.2], marks: "mortar washed out; soot black where sheltered; efflorescence under ledges; a tide line, green on north faces; spalled faces; cracks stepping along the joints from the openings' corners" }, { name: "sandstone", colour: [0.9, 0.75, 0.45], marks: "washed light; a black crust where sheltered; black and white streaks under ledges; rounded arrises" }, { name: "granite", colour: [0.6, 0.6, 0.62], marks: "little: soot where sheltered" }, - { name: "wood", colour: [0.55, 0.35, 0.15], marks: "sun-faded and alligatored on the faces the sun reaches; peeling at bottom rails; rot at the foot; worn to the wood where held and kicked" }, + { name: "wood", colour: [0.55, 0.35, 0.15], marks: "sun-faded and alligatored on the faces the sun reaches; peeling to the primer and the wood at bottom rails, and by neglect wherever the coat's loosened; rot at the foot; worn to the wood where held and kicked" }, { name: "iron", colour: [0.25, 0.3, 0.4], marks: "paint flaking at joints and arrises; rust at the foot and on the stone below; bright where held" }, { name: "zinc", colour: [0.7, 0.8, 0.85], marks: "a pale patina where rain-washed; white streaks below" }, { name: "copper", colour: [0.3, 0.7, 0.55], marks: "verdigris where rain-washed, brown-black where sheltered; green streaks below" }, - { name: "slate", colour: [0.35, 0.35, 0.45], marks: "lichen where the sun misses; soot in the laps" }, + { name: "slate", colour: [0.35, 0.35, 0.45], marks: "lichen where the sun misses; soot in the laps; slates gone by neglect, most along ridges, verges and eaves" }, { name: "felt", colour: [0.15, 0.15, 0.15], marks: "greyed by the sun; washed where the rain runs" }, - { name: "glass", colour: [0.5, 0.85, 1.0], marks: "a grime film where sheltered, thickest at the bottom and corners" }, - { name: "enamel", colour: [0.2, 0.3, 0.9], marks: "rust bled from its screws; chipped to black iron at holes and edges" }, + { name: "glass", colour: [0.5, 0.85, 1.0], marks: "a grime film where sheltered, thickest at the bottom and corners; panes broken or boarded by neglect" }, + { name: "enamel", colour: [0.2, 0.3, 0.9], marks: "rust bled from its screws; chipped to black iron at holes and edges, and by neglect flaking in sheets to rusting iron" }, { name: "brass", colour: [0.9, 0.7, 0.2], marks: "dull brown, more where rain-washed; bright where touched" }, { name: "ground", colour: [0.4, 0.55, 0.3], marks: "dirt in corners and at the wall's foot; moss where the sun misses; polished where feet pass" }, ] as const satisfies readonly { name: string; colour: [number, number, number]; marks: string }[]; @@ -90,6 +94,59 @@ export interface WearWeather { melt?: number; } +/** A thing the bake's rules put on the model (spots.json, docs/wear.feature WR3, WR6): what, who put it there, its + * middle, the face it's on and its size (across, up); debris also carries the loss potential of the plaster above it. */ +export interface WearSpot { + what: "bill" | "street plate" | "nameplate" | "debris"; + by: string; + at: [number, number, number]; + n: [number, number, number]; + size: [number, number]; + loss?: number; +} + +const spotsOf = new Map(); + +/** The spots the bake put down (bills, street plates, nameplates, debris), read once from its spots.json. */ +export function wearSpots(baked: Pick): WearSpot[] { + const path = baked?.spots; + if (typeof path !== "string") throw new TypeError("wearSpots: baked is wearBake's answer, with its spots"); + let s = spotsOf.get(path); + if (!s) { + if (!hasNative()) throw new Error("wearSpots: reading the bake's spots needs the raea engine (raea render)"); + const got = native("asset.read", { path }); + // spots.json is ASCII (the rules' names and numbers), so atob's binary string is its text + s = JSON.parse(atob(got.base64)) as WearSpot[]; + spotsOf.set(path, s); + } + return s; +} + +/** How far neglect has let things go at an age (wearShader's own: the marks' age, less what upkeep keeps up). */ +export function neglectOf(age: WearAge = {}): number { + const years = age.years ?? 30; + const upkeep = age.upkeep ?? 0.5; + return Math.min(1, Math.max(0, (1 - Math.exp(-Math.max(years, 0) / 25)) * (1.15 - upkeep))); +} + +/** How far a house is left empty at an age, 0..1 (wearShader's own): neglect past ABANDON_FROM. A lived-in house + * mends its panes and slates and sweeps its walk however poorly it is kept. */ +export function abandonOf(age: WearAge = {}): number { + const t = Math.min(1, Math.max(0, (neglectOf(age) - ABANDON_FROM) / (1 - ABANDON_FROM))); + return t * t * (3 - 2 * t); +} + +/** A heap shows where the plaster above it has come off and nobody sweeps: loss potential x abandonment past this. */ +export const DEBRIS_AT = 0.3; + +/** The debris an age has left lying (WR6): the bake's debris under plaster whose loss potential has let it go, on + * the walk of a house left empty. `spots` is wearSpots' answer, or wearBake's to read it. */ +export function wearDebris(spots: readonly WearSpot[] | Pick, age: WearAge = {}): WearSpot[] { + const all = Array.isArray(spots) ? (spots as readonly WearSpot[]) : wearSpots(spots as Pick); + const a = abandonOf(age); + return all.filter((s) => s.what === "debris" && (s.loss ?? 0) * a >= DEBRIS_AT); +} + export interface WearShaderOptions { /** wearBake's answer: its maps are the shader's textures, its density decides whether edges can chip */ baked: Pick; @@ -179,8 +236,9 @@ ${cases.join("\n")} const SURFACE = /* wgsl */ ` fn wear_surface(uv: vec2, pbr: ptr) { + let px = length(fwidth((*pbr).world_position.xyz)); let c = wear_causes(uv); - let g = wear_geo((*pbr).world_position.xyz, (*pbr).world_normal, c); + let g = wear_geo((*pbr).world_position.xyz, (*pbr).world_normal, c, (*pbr).V, px); let m = wear_marks(c, g); var s = WearSurf((*pbr).material.base_color.rgb, (*pbr).material.perceptual_roughness, (*pbr).material.metallic); if (!wear_class(&s, c, g, m)) { return; } diff --git a/sdk/wear/src/recipes.ts b/sdk/wear/src/recipes.ts index 5b041869b..f0a3f0d0d 100644 --- a/sdk/wear/src/recipes.ts +++ b/sdk/wear/src/recipes.ts @@ -14,16 +14,21 @@ export const RECIPES: Record = { (*s).rough = mix((*s).rough, 0.95, m.wash * 0.4 * m.age); // sheltered: soot grey, darkest tucked under cornices (*s).col = mix((*s).col, (*s).col * vec3(0.3, 0.29, 0.27), m.crust); - // the foot: render blown where the damp and the frost work, the brick behind it showing (worst where let go) - let blowN = wear_fbm2(g.p * vec2(0.9, 1.4) + vec2(c.elem * 0.31, 5.0)); - let blowAt = 0.74 - 0.2 * (1.0 - m.upkeep) - 0.12 * (1.0 - smoothstep(0.15, 0.9, g.h)); - let foot = (1.0 - smoothstep(0.7, 1.3, g.h)) * g.wall * step(0.2, m.wear); - let blown = smoothstep(blowAt, blowAt + 0.015, blowN) * foot; - let lip = smoothstep(blowAt - 0.04, blowAt, blowN) * (1.0 - blown) * foot; - (*s).col = mix((*s).col, wear_bond(g.p) * mix(1.0, 0.55, m.crust), blown); - (*s).col = (*s).col * (1.0 - 0.45 * lip); + // WR6: the render lost where the causes loosen it (the damp foot, soaked faces, knocked arrises, along a crack) and + // neglect lets it go, to the brick 2 cm behind it; the broken edge's lip shades the hole under it + let lost = m.loss * m.neglect; + let lossAt = 0.8 - 0.34 * lost; + let q = g.p * vec2(0.9, 1.4) + vec2(c.elem * 0.31, 5.0); + let blowN = wear_fbm2(q); + let gone = smoothstep(lossAt, lossAt + 0.012, blowN) * step(0.03, lost); + let over = smoothstep(lossAt, lossAt + 0.012, wear_fbm2(q + vec2(0.0, 0.042))); + let lip = smoothstep(lossAt - 0.035, lossAt, blowN) * (1.0 - gone) * step(0.03, lost); + let behind = wear_bond(g.p + g.par * 0.02) * mix(1.0, 0.55, m.crust); + (*s).col = mix((*s).col, behind * (1.0 - 0.55 * (1.0 - over)), gone); + (*s).col = (*s).col * (1.0 - 0.4 * lip); + (*s).rough = mix((*s).rough, 0.95, gone); // chipped arrises low down: the lime coat knocked off to the brick - (*s).col = mix((*s).col, mix(vec3(0.78, 0.76, 0.7), wear_bond(g.p), 0.5), m.chip * (1.0 - blown)); + (*s).col = mix((*s).col, mix(vec3(0.78, 0.76, 0.7), wear_bond(g.p), 0.5), m.chip * (1.0 - gone)); // a grease band where shoulders and hubs rub (*s).col = mix((*s).col, (*s).col * vec3(0.5, 0.48, 0.45), c.touch * 0.6 * g.wall); (*s).rough = mix((*s).rough, 0.55, c.touch * 0.5);`, @@ -66,9 +71,14 @@ export const RECIPES: Record = { (*s).col = mix((*s).col, vec3(dot((*s).col, vec3(0.33))) * 1.25 + vec3(0.04), c.sun * 0.45 * m.wear); let cells = abs(wear_vn2(g.p * vec2(14.0, 9.0)) - 0.5); (*s).col = (*s).col * (1.0 - 0.45 * (1.0 - smoothstep(0.015, 0.05, cells)) * smoothstep(0.3, 0.8, c.sun) * m.wear); - // under a ledge and at the bottom rails: peeling where the run-off soaks the timber, the grey wood showing + // under a ledge and at the bottom rails: peeling where the run-off soaks the timber, and by neglect (WR6) wherever + // the coat's loosened: the top coat off to the red-lead primer, then to the grey wood let wetWood = clamp(c.flow + (1.0 - smoothstep(0.04, 0.5, g.h)) * g.wall, 0.0, 1.0); - let peel = smoothstep(0.5, 0.56, wear_fbm2(g.p * vec2(9.0, 4.0)) + 0.2 * wetWood * m.wear) * wetWood * step(0.1, m.wear); + let bare = wear_fbm2(g.p * vec2(9.0, 4.0)) + 0.2 * wetWood * m.wear + 0.25 * m.loss * m.neglect; + let reach = max(wetWood, m.loss * smoothstep(0.1, 0.5, m.neglect)) * step(0.1, m.wear); + let primer = smoothstep(0.46, 0.49, bare) * reach; + let peel = smoothstep(0.53, 0.56, bare) * reach; + (*s).col = mix((*s).col, vec3(0.58, 0.34, 0.25) * (0.9 + 0.2 * wear_vn2(g.p * 25.0)), primer * (1.0 - peel)); (*s).col = mix((*s).col, vec3(0.3, 0.27, 0.22) * (0.8 + 0.3 * wear_vn2(vec2(g.p.x * 30.0, g.p.y * 2.0))), max(peel, m.chip)); // rot at the foot let rot = (1.0 - smoothstep(0.02, 0.25, g.h)) * m.wear * g.wall; @@ -114,7 +124,16 @@ export const RECIPES: Record = { // lichen on the faces the sun misses, soot in the laps let lichen = (1.0 - c.sun) * smoothstep(0.55, 0.75, wear_fbm2(g.p * 2.5 + vec2(c.elem * 0.13, 1.0))) * m.age; (*s).col = mix((*s).col, vec3(0.2, 0.22, 0.13), lichen * 0.6); - (*s).col = mix((*s).col, vec3(0.03), m.crust * 0.5);`, + (*s).col = mix((*s).col, vec3(0.03), m.crust * 0.5); + // WR6: slates slipped and gone, the odd one by neglect and many once the house is empty, more along the ridge, the + // verges and the eaves, the battens and the + // felt under them showing (courses 11 cm up the slope's height, slates 25 cm across, broken bond) + let course = floor(g.p.y / 0.11); + let across = g.p.x / 0.25 + select(0.0, 0.5, i32(course) % 2 == 1); + let missing = step(wear_h21(vec2(floor(across) + c.elem * 17.0, course)), 0.1 * (0.15 * m.neglect + 0.85 * m.abandon) * (1.0 + 2.0 * c.edge)); + let batten = 1.0 - smoothstep(0.0, 0.18, abs(fract(g.p.y / 0.11) - 0.5) * 2.0 - 0.6); + (*s).col = mix((*s).col, mix(vec3(0.04, 0.035, 0.03), vec3(0.3, 0.21, 0.12), batten), missing); + (*s).rough = mix((*s).rough, 0.95, missing);`, felt: /* wgsl */ ` // roofing felt: greyed by the sun, its grit washed off where the rain runs @@ -125,7 +144,23 @@ export const RECIPES: Record = { // sheltered: a grime film, thickest in the corners and at the bottom where the frame holds the dirt let film = clamp(m.shelter * 0.5 + c.cav * 0.8 + (1.0 - m.wash) * 0.2, 0.0, 1.0) * m.age * (1.0 - 0.6 * m.upkeep); (*s).col = mix((*s).col, (*s).col * vec3(0.62, 0.6, 0.55), film * 0.7); - (*s).rough = mix((*s).rough, 0.55, film * 0.6);`, + (*s).rough = mix((*s).rough, 0.55, film * 0.6); + // WR6: a house left empty has its panes broken and boarded over, one fate per pane + let fate = wear_h21(vec2(c.elem, 11.0)); + if (fate < 0.16 * m.abandon) { + // boarded: planks of grey, weathered deal across the opening + let row = fract(g.p.y / 0.15); + let tone = 0.75 + 0.4 * wear_h21(vec2(floor(g.p.y / 0.15), c.elem)); + let gap = 1.0 - smoothstep(0.0, 0.06, min(row, 1.0 - row)); + (*s).col = vec3(0.36, 0.32, 0.26) * tone * (0.85 + 0.3 * wear_vn2(vec2(g.p.x * 30.0, g.p.y * 3.0))) * (1.0 - 0.7 * gap); + (*s).rough = 0.9; + (*s).metal = 0.0; + } else if (fate < 0.38 * m.abandon) { + // broken: the dark room behind, shards left in the putty at the frame + let shard = smoothstep(0.52, 0.56, wear_fbm2(g.p * 7.0 + vec2(c.elem, 0.0)) * 0.6 + 0.7 * c.cav); + (*s).col = mix(vec3(0.012, 0.011, 0.01), (*s).col, shard); + (*s).rough = mix(1.0, (*s).rough, shard); + }`, enamel: /* wgsl */ ` // rust bled from its screws, in short tails below them @@ -133,10 +168,17 @@ export const RECIPES: Record = { let screw = step(0.8, wear_h21(vec2(col, c.elem))); let tail = screw * (1.0 - smoothstep(0.0, 0.04, abs(fract(g.p.x * 6.0) - 0.5) / 6.0)) * smoothstep(0.3, 0.9, wear_vn2(vec2(col, g.p.y * 3.0))); (*s).col = mix((*s).col, vec3(0.3, 0.12, 0.04), tail * m.wear * 0.8); - // chipped to black iron at its holes and edges + // chipped to black iron at its holes and edges, and by neglect (WR6) flaking off in sheets from them to the iron, + // which rusts, and rust creeping under the enamel's broken edge let chipped = smoothstep(0.65, 0.9, c.edge) * step(0.62 - 0.3 * m.wear, wear_vn2(g.p * 30.0)) * step(0.05, m.wear); - (*s).col = mix((*s).col, vec3(0.03, 0.03, 0.035), chipped); - (*s).rough = mix((*s).rough, 0.7, chipped);`, + let flakeN = wear_fbm2(g.p * 14.0 + vec2(c.elem * 3.1, 0.0)); + let flakeAt = 0.82 - 0.38 * m.neglect * max(smoothstep(0.5, 0.9, c.edge), 0.5 * m.loss + 0.3); + let flake = smoothstep(flakeAt, flakeAt + 0.01, flakeN) * step(0.05, m.neglect); + let creep = smoothstep(flakeAt - 0.03, flakeAt, flakeN) * (1.0 - flake) * step(0.05, m.neglect); + let iron = mix(vec3(0.03, 0.03, 0.035), vec3(0.2, 0.08, 0.03), smoothstep(0.3, 0.7, wear_vn2(g.p * 40.0)) * flake); + (*s).col = mix((*s).col, iron, max(chipped, flake)); + (*s).col = mix((*s).col, vec3(0.25, 0.1, 0.04), creep * 0.7); + (*s).rough = mix((*s).rough, 0.75, max(chipped, flake));`, brass: /* wgsl */ ` // tarnished dull brown, more where the rain reaches; bright where hands touch it @@ -195,6 +237,16 @@ fn wear_shared(s: ptr, c: WearCauses, g: WearGeo, m: WearMar (*s).col = mix((*s).col, vec3(0.8, 0.79, 0.74), m.salt * 0.3 * porous * smoothstep(0.4, 0.75, wear_vn2(vec2(g.p.x * 1.3, g.p.y * 3.0)))); if (c.cls != 13 && c.cls != 10) { (*s).col = mix((*s).col, (*s).col * 0.62, m.splash * 0.7); } (*s).rough = mix((*s).rough, 0.97, m.crust * 0.5); + // WR6: cracks from the openings' corners, opening as neglect grows and gathering dirt along them; in brick a crack + // steps along the joints. Drawn no thinner than a pixel, fading as it gets thinner than one + let opened = smoothstep(0.1, 0.7, m.neglect) * porous; + let wide = 0.0035 * opened; + let dd = max(c.crack + (wear_vn2(g.p * 38.0) - 0.5) * 0.006, 0.0); + let line = (1.0 - smoothstep(0.5 * wide, 0.5 * wide + g.px, dd)) * min(1.0, wide / max(g.px, 0.0001) + 0.25) * step(0.0001, wide); + let stepped = (1.0 - smoothstep(0.02, 0.05, c.crack)) * wear_bond_joint(g.p) * opened; + let crack = select(line, stepped, c.cls == 1); + let halo = (1.0 - smoothstep(0.0, 0.03, dd)) * opened; + (*s).col = (*s).col * (1.0 - 0.8 * crack) * (1.0 - 0.15 * halo); } `; diff --git a/sdk/wear/src/weather.ts b/sdk/wear/src/weather.ts new file mode 100644 index 000000000..fa0e0438c --- /dev/null +++ b/sdk/wear/src/weather.ts @@ -0,0 +1,79 @@ +// Weather that changes during a shot (docs/wear.feature WR9): rain starting, snow settling, frost forming. What lies +// on the surfaces (wet, snow, driven snow, frost) follows what the sky does at its own rate, so a shot that starts +// dry darkens over the minutes rain takes to soak a front and dries over the hour it takes to dry. `weatherAt` gives +// the surfaces' weather at a moment, for wearShader each frame. +// +// const spells = [{ at: 0 }, { at: 2, rain: 1 }, { at: 40 }]; // dry, raining from minute 2 to 40 +// const minutes = (frame / fps) * 60; // a timelapse: a second a minute +// wearShader({ baked, weather: weatherAt({ day: 120 }, spells, minutes) }) +import type { WearWeather } from "./index"; + +/** What the sky does from minute `at` of the shot on: rain, snow falling, a storm driving it, frost (each 0..1; + * what a spell leaves out is 0). */ +export interface WearSpell { + at: number; + rain?: number; + snow?: number; + storm?: number; + ice?: number; +} + +/** How fast the surfaces follow the sky, the share of the way left covered per minute (ASSUMED until measured): + * wetting in about 3 minutes of steady rain, drying over about an hour; snow settling over about 20 minutes and + * melting over about two hours; driven snow plastering in about 10 and falling off over 30; frost forming over half + * an hour and going in 20. */ +export const WEATHER_RATES = { wet: 1 / 3, dry: 1 / 60, settle: 1 / 20, melt: 1 / 120, plaster: 1 / 10, shed: 1 / 30, freeze: 1 / 30, thaw: 1 / 20 } as const; + +type Lying = { wet: number; snow: number; storm: number; ice: number }; +const KEYS = [ + ["wet", "rain", "wet", "dry"], + ["snow", "snow", "settle", "melt"], + ["storm", "storm", "plaster", "shed"], + ["ice", "ice", "freeze", "thaw"], +] as const; + +/** The surfaces' weather `minutes` into the shot: `base` is how they lie when it starts (its day, and its wet, snow, + * storm and ice), `spells` what the sky does from when (in order). Each value eases toward the sky's at its rate, + * exactly (an exponential over each spell), so any frame can be drawn alone. */ +export function weatherAt(base: WearWeather, spells: readonly WearSpell[], minutes: number): WearWeather { + if (!Number.isFinite(minutes)) throw new RangeError(`weatherAt: minutes is a number, got ${minutes}`); + for (let i = 1; i < spells.length; i++) if (!(spells[i].at >= spells[i - 1].at)) throw new RangeError("weatherAt: spells are in order of `at`"); + const v: Lying = { wet: base.wet ?? 0, snow: base.snow ?? 0, storm: base.storm ?? 0, ice: base.ice ?? 0 }; + let t = spells.length ? Math.min(spells[0].at, minutes) : minutes; + for (let i = 0; i < spells.length && spells[i].at <= minutes; i++) { + const s = spells[i]; + const end = Math.min(i + 1 < spells.length ? spells[i + 1].at : minutes, minutes); + const dt = Math.max(0, end - Math.max(t, s.at)); + for (const [k, sky, up, down] of KEYS) { + const target = s[sky] ?? 0; + if (!(target >= 0 && target <= 1)) throw new RangeError(`weatherAt: a spell's ${sky} is 0..1, got ${target}`); + const rate = WEATHER_RATES[target > v[k] ? up : down]; + v[k] = target + (v[k] - target) * Math.exp(-rate * dt); + } + t = end; + } + const r = (x: number) => Math.round(x * 1e4) / 1e4; + return { ...base, wet: r(v.wet), snow: r(v.snow), storm: r(v.storm), ice: r(v.ice) }; +} + +/** WR9's eight conditions as weather on the surfaces: a day of the year in its season and what lies on them. The + * light that goes with each (overcast for rain, a flash for thunder) is the scene's. */ +export const WEAR_CONDITIONS = { + /** damp lingering on north faces and plinths, algae where the run-off and the shade meet */ + spring: { day: 105, damp: 0.85 }, + /** dry: dust on ledges and treads */ + summer: { day: 205 }, + /** leaves where blown things settle, wet and dark after a shower */ + autumn: { day: 300, wet: 0.35, leaves: 1 }, + /** frost on the faces the winter sun misses */ + winter: { day: 20, ice: 0.8 }, + /** snow lying on what is open above, deeper in the lee */ + snow: { day: 30, snow: 0.85, ice: 0.4 }, + /** snow, and driven snow plastered on the faces the storm reaches */ + blizzard: { day: 40, snow: 1, storm: 0.9, ice: 0.6 }, + /** wet where the rain reaches, rivulets down the run-off's paths, puddles in the walk's hollows */ + rain: { day: 130, wet: 0.8 }, + /** heavy rain: wet through */ + thunder: { day: 200, wet: 1 }, +} as const satisfies Record; +export type WearCondition = keyof typeof WEAR_CONDITIONS; diff --git a/sdk/wear/test/wear.test.ts b/sdk/wear/test/wear.test.ts index 1d78dc6c9..379293c41 100644 --- a/sdk/wear/test/wear.test.ts +++ b/sdk/wear/test/wear.test.ts @@ -1,8 +1,10 @@ import { describe, expect, test } from "bun:test"; import { readFileSync } from "node:fs"; import { surfaceShader } from "@raea/render/3d/materials"; -import { DEBUG_CAUSES, seasonOf, WEAR_CLASSES, wearShader, type WearCause } from "../src/index"; +import { ABANDON_FROM, abandonOf, CRACK_REACH, CRACK_WEIGHT, DEBRIS_AT, DEBUG_CAUSES, LOSS, neglectOf, seasonOf, WEAR_CLASSES, wearDebris, wearShader, type WearCause, type WearSpot } from "../src/index"; import { RECIPES } from "../src/recipes"; +import { CAUSES } from "../src/causes"; +import { WEAR_CONDITIONS, weatherAt } from "../src/weather"; const baked = { maps: { causes0: "/s/causes0.png", causes1: "/s/causes1.png", causes2: "/s/causes2.png", causes3: "/s/causes3.png" }, density: 16 }; const ROOT = new URL("../../..", import.meta.url).pathname; @@ -73,6 +75,61 @@ describe("the shader", () => { }); }); +describe("crumbling (WR6)", () => { + const rs = readFileSync(`${ROOT}systems/damage/src/lib.rs`, "utf8"); + const num = (name: string) => Number(rs.match(new RegExp(`const ${name}: f32 = ([0-9.]+);`))?.[1]); + test("the loss potential is raea-sys-damage's, so the debris it put down lies under the losses", () => { + const list = rs.match(/pub const LOSS: \[f32; (\d+)\] = \[([^\]]*)\]/); + expect(list).not.toBeNull(); + expect(list![2].split(",").map(Number)).toEqual([...LOSS]); + expect(num("CRACK_WEIGHT")).toBe(CRACK_WEIGHT); + expect(num("REACH")).toBe(CRACK_REACH); + const sh = wearShader({ baked }).wesl; + expect(sh).toContain("fn wear_loss(c: WearCauses) -> f32"); + expect(sh.includes(`let foot = 1.0 - smoothstep(${LOSS[0]}, ${LOSS[1]}, c.ground);`)).toBe(true); + expect(sh.includes("(1.0 - d.a) * 0.25")).toBe(true); + }); + test("each class crumbles its own way", () => { + const sh = wearShader({ baked }).wesl; + const body = (c: string) => sh.slice(sh.indexOf(`fn wear_${c}(`), sh.indexOf("\n}\n", sh.indexOf(`fn wear_${c}(`))); + expect(body("plaster")).toContain("wear_bond(g.p + g.par * 0.02)"); + expect(body("wood")).toContain("primer"); + expect(body("enamel")).toContain("flake"); + expect(body("glass")).toContain("boarded"); + expect(body("glass")).toContain("broken"); + expect(body("slate")).toContain("missing"); + // cracks for the masonry and render, stepping along brick's joints, from a pixel size taken before any branch + expect(sh).toContain("let crack = select(line, stepped, c.cls == 1);"); + const surf = sh.slice(sh.indexOf("fn wear_surface(")); + expect(surf.indexOf("fwidth(")).toBeLessThan(surf.indexOf("if (")); + }); + test("neglect grows with the years and falls with upkeep", () => { + expect(neglectOf({ years: 0 })).toBe(0); + expect(neglectOf({ years: 80, upkeep: 0.1 })).toBeGreaterThan(0.9); + expect(neglectOf({ years: 80, upkeep: 1 })).toBeLessThan(0.2); + expect(neglectOf({ years: 30, upkeep: 0.5 })).toBeGreaterThan(neglectOf({ years: 10, upkeep: 0.5 })); + }); + test("a house is left empty only past what a lived-in one lets go", () => { + expect(abandonOf({ years: 80, upkeep: 0.35 })).toBe(0); + expect(abandonOf({ years: 30, upkeep: 0.5 })).toBe(0); + expect(abandonOf({ years: 90, upkeep: 0.05 })).toBeGreaterThan(0.95); + expect(abandonOf({ years: 80, upkeep: 0.2 })).toBeGreaterThan(0); + expect(neglectOf({ years: 80, upkeep: 0.35 })).toBeLessThan(ABANDON_FROM); + // the shader's own threshold is the same number + expect(CAUSES).toContain(`smoothstep(${ABANDON_FROM}, 1.0, age * (1.15 - clamp(u_age().z, 0.0, 1.0)))`); + }); + test("debris lies where its plaster has come off and nobody sweeps", () => { + const heap = (loss: number): WearSpot => ({ what: "debris", by: "weather", at: [0, 0, 0], n: [0, 1, 0], size: [0.5, 0.3], loss }); + const spots: WearSpot[] = [heap(1), heap(0.55), { what: "bill", by: "bill poster", at: [0, 1.5, 0], n: [0, 0, 1], size: [0.6, 0.85] }]; + expect(wearDebris(spots, { years: 0 })).toEqual([]); + expect(wearDebris(spots, { years: 80, upkeep: 0.35 })).toEqual([]); + expect(wearDebris(spots, { years: 90, upkeep: 0.05 })).toHaveLength(2); + const some = wearDebris(spots, { years: 80, upkeep: 0.2 }); + expect(some.every((s) => s.what === "debris" && s.loss! * abandonOf({ years: 80, upkeep: 0.2 }) >= DEBRIS_AT)).toBe(true); + expect(some.length).toBeLessThan(2); + }); +}); + describe("the uniforms", () => { test("carry age, the day's weather and the season's own share", () => { const sh = wearShader({ baked, age: { years: 60, soot: 0.9, upkeep: 0.3 }, weather: { day: 300, wet: 0.4, snow: 0.2 }, up: [0, 0, 1] }); @@ -114,3 +171,46 @@ describe("the debug mode", () => { expect(() => wearShader({ baked, debug: "rain" as never })).toThrow(/debug is one of/); }); }); + +describe("weather during a shot (WR9)", () => { + const rain = [{ at: 0 }, { at: 2, rain: 1 }, { at: 40 }]; + test("rain soaks a dry front in minutes and it dries over the hour", () => { + expect(weatherAt({ day: 120 }, rain, 1).wet).toBe(0); + expect(weatherAt({ day: 120 }, rain, 3).wet).toBeGreaterThan(0.2); + expect(weatherAt({ day: 120 }, rain, 12).wet).toBeGreaterThan(0.95); + const stop = weatherAt({ day: 120 }, rain, 40).wet!; + expect(weatherAt({ day: 120 }, rain, 50).wet).toBeLessThan(stop); + expect(weatherAt({ day: 120 }, rain, 50).wet).toBeGreaterThan(0.75); + expect(weatherAt({ day: 120 }, rain, 300).wet).toBeLessThan(0.05); + expect(weatherAt({ day: 120 }, rain, 3).day).toBe(120); + }); + test("each frame stands alone, and the values run on without a jump at a spell", () => { + const at = (m: number) => weatherAt({}, rain, m).wet!; + expect(Math.abs(at(40.001) - at(39.999))).toBeLessThan(1e-3); + for (let m = 0; m < 60; m += 1.7) expect(at(m)).toBeGreaterThanOrEqual(0); + }); + test("snow settles, a storm plasters faster than it settles, frost forms", () => { + const w = weatherAt({ day: 20 }, [{ at: 0, snow: 1, storm: 1, ice: 1 }], 10); + expect(w.storm!).toBeGreaterThan(w.snow!); + expect(w.snow!).toBeGreaterThan(0.3); + expect(w.ice!).toBeGreaterThan(0.2); + expect(weatherAt({ day: 20, snow: 0.8 }, [{ at: 0 }], 60).snow).toBeGreaterThan(0.4); + }); + test("refuses spells out of order or out of range", () => { + expect(() => weatherAt({}, [{ at: 5 }, { at: 1 }], 3)).toThrow(/in order/); + expect(() => weatherAt({}, [{ at: 0, rain: 2 }], 3)).toThrow(/0..1/); + }); +}); + +describe("the eight conditions (WR9)", () => { + test("each is a weather wearShader takes, in its season", () => { + expect(Object.keys(WEAR_CONDITIONS)).toEqual(["spring", "summer", "autumn", "winter", "snow", "blizzard", "rain", "thunder"]); + for (const w of Object.values(WEAR_CONDITIONS)) { + expect(w.day >= 1 && w.day <= 366).toBe(true); + for (const v of Object.values(w)) expect(Number.isFinite(v)).toBe(true); + } + expect(seasonOf(WEAR_CONDITIONS.summer).dust).toBeGreaterThan(0.6); + expect(seasonOf(WEAR_CONDITIONS.spring).damp).toBeGreaterThan(0.6); + expect(seasonOf(WEAR_CONDITIONS.winter).leaves).toBe(0); + }); +}); diff --git a/systems/damage/Cargo.toml b/systems/damage/Cargo.toml new file mode 100644 index 000000000..bcc2b0db8 --- /dev/null +++ b/systems/damage/Cargo.toml @@ -0,0 +1,14 @@ +[package] +name = "raea-sys-damage" +version = "0.1.0" +edition = "2024" +license = "FSL-1.1-ALv2" +publish = false +description = "Where a building breaks: cracks from the corners of its openings, how readily each point loses its coat, and debris under the losses (raea/wear's crumbling)" + +[dependencies] +parry3d = "0.31" +rayon = "1" +raea-sys-touch = { path = "../touch" } +# smoothstep, shared with raea-sys-foliage +raea-core-ease = { path = "../../core/ease" } diff --git a/systems/damage/src/lib.rs b/systems/damage/src/lib.rs new file mode 100644 index 000000000..f2f86abeb --- /dev/null +++ b/systems/damage/src/lib.rs @@ -0,0 +1,232 @@ +//! Where a building breaks (docs/wear.feature WR6), by rules over the weathering bake's texels: +//! - cracks run from the re-entrant corners of a wall's openings (a window's, a door's), where a wall's stresses +//! gather, away from the opening and steeper than 45 degrees, 0.35-1.25 m, wandering as they go; each texel gets +//! its distance to the nearest crack on its own wall (to REACH), which raea/wear draws, wider as neglect grows; +//! - the loss potential (`loss`): how readily a point's coat (render, paint, enamel) comes off, from what loosens +//! it: the damp foot of a wall, run-off soaking where the rain doesn't wash it, a knocked arris low down, a crack. +//! raea/wear's recipes lose the coat where noise passes a threshold that potential and neglect lower, by the same +//! formula (its test reads LOSS here); +//! - debris on the walking surface under plaster with a high loss potential, each with that potential, so a scene +//! puts down only what its neglect has brought down (raea/wear's wearDebris). +//! Sizes and weights are ASSUMED until measured. + +#[cfg(test)] +mod tests; + +use parry3d::bounding_volume::Aabb; +use parry3d::glamx::Vec3; +use parry3d::query::{Ray, RayCast}; +use rayon::prelude::*; + +use raea_core_ease::smoothstep as smooth; +use raea_sys_touch::{Mat, Point, Spot, Surface}; + +/// A cache key's part: a change to the rules changes every bake that used them. +pub const VERSION: &str = "raea-sys-damage 3"; + +/// How far a texel's distance to a crack is kept (metres): the cause map holds 1 - d / REACH. +pub const REACH: f32 = 0.25; + +/// The loss potential's edges and weights, in the order `loss` uses them (raea/wear's causes.ts has the same list, +/// and its test compares them): the foot band (ground 0.7-1.3 m), the soak (flow 0.5-0.9, the rain's reach washing +/// it from 0.35-0.85), the arris (edge 0.75-0.9, below 1.4-2.2 m), the crack (within 0.12 m), then the weights of +/// the soak, the arris and the crack against the foot's 1. +pub const LOSS: [f32; 13] = [0.7, 1.3, 0.5, 0.9, 0.35, 0.85, 0.75, 0.9, 1.4, 2.2, 0.12, 0.8, 0.7]; +const CRACK_WEIGHT: f32 = 0.6; + +/// a probe's reach across the wall either way when looking for an opening's corner +const PROBE: f32 = 0.12; +/// a probe meets the wall when it lands within this of the texel's plane +const PLANE: f32 = 0.04; +/// corner texels this near with the same opening are one corner +const CORNER: f32 = 0.3; +/// the share of re-entrant corners that crack (ASSUMED: about half; which ones by the corner's place, so a house +/// cracks the same way every bake) +const CRACKED: u64 = 50; +const STEP: f32 = 0.04; +const DEBRIS: [f32; 2] = [0.5, 0.3]; +const GAP_DEBRIS: f32 = 1.5; +/// debris only under plaster this ready to come off +const DEBRIS_LOSS: f32 = 0.5; +/// how far out from the wall a heap lies (metres), and how far below the wall's foot the walk may be +const DEBRIS_OUT: f32 = 0.2; +const DROP: f32 = 0.5; +/// a wall the rain reaches less than this is indoors (a room's wall, the back of a hollow model): nothing falls on a +/// walk from it +const OUTDOORS: f32 = 0.02; + +/// How readily the coat at `q` comes off (0-1), with `crack` its distance to the nearest crack (metres). +pub fn loss(q: &Point, crack: f32) -> f32 { + let l = &LOSS; + let foot = 1.0 - smooth(l[0], l[1], q.ground); + let soak = smooth(l[2], l[3], q.flow) * (1.0 - smooth(l[4], l[5], q.rain)); + let arris = smooth(l[6], l[7], q.edge) * (1.0 - smooth(l[8], l[9], q.ground)); + let near = 1.0 - smooth(0.0, l[10], crack); + foot.max(l[11] * soak).max(l[12] * arris).max(CRACK_WEIGHT * near) +} + +fn wallish(m: Mat) -> bool { + matches!(m, Mat::Plaster | Mat::Masonry) +} + +fn standing(s: &Surface, q: &Point) -> bool { + q.n.dot(s.up).abs() < 0.2 && wallish(s.mat[q.tri as usize]) +} + +/// The wall of the face at `p` (normal `n`) goes on at `at`: a ray into it from 0.3 m out meets plaster or masonry +/// facing the same way within PLANE of p's plane (a reveal, a recess, a sill in front or nothing at all is no wall). +fn wall_at(s: &Surface, p: Vec3, n: Vec3, at: Vec3) -> bool { + let o = at + n * 0.3; + s.mesh.cast_local_ray_and_get_normal(&Ray::new(o, -n), 0.6, false).is_some_and(|h| { + let t = h.subshape as usize; + wallish(s.mat[t]) && s.nrm[t].dot(n) > 0.9 && ((o - n * h.time_of_impact - p).dot(n)).abs() < PLANE + }) +} + +/// An opening's corner: where it is, its wall's normal, and the way a crack leaves it (in the wall's plane, away +/// from the opening). +#[derive(Clone, Debug, PartialEq)] +pub struct Corner { + pub at: Vec3, + pub n: Vec3, + pub away: Vec3, +} + +/// The re-entrant corners of the walls' openings. A wall texel is beside one when, of the eight probes PROBE away +/// across and up the wall, only one diagonal misses the wall: the opening is that way, and the wall goes on along +/// both its edges. A building's outer corner (an edge missing too) or a pier between two openings isn't one. +pub fn corners(s: &Surface, pts: &[Point]) -> Vec { + let found: Vec<(Vec3, Vec3, Vec3)> = pts + .par_iter() + .filter(|q| standing(s, q)) + .filter_map(|q| { + let t = s.up.cross(q.n).normalize_or_zero(); + let on = |d: Vec3| wall_at(s, q.p, q.n, q.p + d); + let (x, y) = (t * PROBE, s.up * PROBE); + if !(on(x) && on(-x) && on(y) && on(-y)) { + return None; + } + let open: Vec = [x + y, x - y, -x + y, -x - y].into_iter().filter(|&d| !on(d)).collect(); + (open.len() == 1).then(|| (q.p, q.n, -open[0].normalize())) + }) + .collect(); + // one corner per cluster: the texels nearest it see it alike; keep their middle + let mut out: Vec<(Corner, u32)> = Vec::new(); + let mut found = found; + found.sort_by_key(|f| raea_sys_touch::seed(f.0)); + for (p, n, away) in found { + match out.iter_mut().find(|(c, _)| c.away.dot(away) > 0.99 && c.n.dot(n) > 0.95 && c.at.distance(p) < CORNER) { + Some((c, k)) => { + c.at = (c.at * *k as f32 + p) / (*k + 1) as f32; + *k += 1; + } + None => out.push((Corner { at: p, n, away }, 1)), + } + } + let mut out: Vec = out.into_iter().map(|(c, _)| c).collect(); + out.sort_by(|a, b| a.at.x.total_cmp(&b.at.x).then(a.at.y.total_cmp(&b.at.y)).then(a.at.z.total_cmp(&b.at.z))); + out +} + +fn unit(h: u64) -> f32 { + (h >> 40) as f32 / (1u64 << 24) as f32 +} + +fn mix(h: u64, k: u64) -> u64 { + let mut x = h ^ k.wrapping_mul(0x9e37_79b9_7f4a_7c15); + x ^= x >> 31; + x = x.wrapping_mul(0xbf58_476d_1ce4_e5b9); + x ^ (x >> 29) +} + +/// A crack's path from a corner: steeper than its diagonal (a wall settles), each step turned up to 20 degrees +/// about that heading, stopping where the wall ends (another opening, the wall's edge) or at its length. +pub fn crack(s: &Surface, c: &Corner) -> Vec { + let h = raea_sys_touch::seed(c.at); + let len = 0.35 + 0.9 * unit(mix(h, 1)); + let side = c.away.dot(s.up).signum(); + let heading = (c.away + s.up * side * 0.45).normalize_or_zero(); + let across = c.n.cross(heading); + let (mut p, mut run, mut k) = (c.at, 0.0, 0u64); + let mut path = vec![p]; + while run < len { + let a = (unit(mix(h, 10 + k)) - 0.5) * 0.7; + let q = p + (heading * a.cos() + across * a.sin()) * STEP; + if !wall_at(s, c.at, c.n, q) { + break; + } + path.push(q); + p = q; + run += STEP; + k += 1; + } + path +} + +fn to_segment(p: Vec3, a: Vec3, b: Vec3) -> f32 { + let ab = b - a; + let t = ((p - a).dot(ab) / ab.length_squared().max(1e-12)).clamp(0.0, 1.0); + p.distance(a + ab * t) +} + +/// Whether the corner at `at` cracks (CRACKED in a hundred do). +fn cracked(at: Vec3) -> bool { + raea_sys_touch::seed(at).rotate_right(29) % 100 < CRACKED +} + +/// Each point's distance to the nearest crack on its own wall (same facing, within 5 cm of its plane), at most REACH; +/// with the corners the cracks start from. +pub fn cracks(s: &Surface, pts: &[Point]) -> (Vec, Vec) { + let cs: Vec = corners(s, pts).into_iter().filter(|c| cracked(c.at)).collect(); + let paths: Vec<(Vec3, Vec, Vec3, Vec3)> = cs + .iter() + .map(|c| { + let path = crack(s, c); + let b = Aabb::from_points(path.iter().copied()); + (c.n, path, b.mins - Vec3::splat(REACH), b.maxs + Vec3::splat(REACH)) + }) + .collect(); + let d = pts + .par_iter() + .map(|q| { + if !standing(s, q) { + return REACH; + } + let mut best = REACH; + for (n, path, lo, hi) in &paths { + if n.dot(q.n) < 0.95 || (q.p - path[0]).dot(*n).abs() > 0.05 || q.p.cmplt(*lo).any() || q.p.cmpgt(*hi).any() { + continue; + } + for w in path.windows(2) { + best = best.min(to_segment(q.p, w[0], w[1])); + } + } + best + }) + .collect(); + (d, cs) +} + +/// Where a heap from the foot of `q` lands: straight down from DEBRIS_OUT in front of it onto the walk, or nowhere +/// when the first thing below is something else (a step, a plinth, a sill). +fn landing(s: &Surface, q: &Point) -> Option { + let from = q.p + q.n * DEBRIS_OUT; + let h = s.mesh.cast_local_ray_and_get_normal(&Ray::new(from, -s.up), q.ground + DROP, false)?; + s.walk[h.subshape as usize].then(|| from - s.up * h.time_of_impact) +} + +/// Debris on the walking surface in front of outdoor plaster whose loss potential is high, one a GAP_DEBRIS apart, +/// each with the potential of the plaster above it. +pub fn debris(s: &Surface, pts: &[Point], crack: &[f32]) -> Vec<(Spot, f32)> { + let c: Vec<(Spot, f32)> = pts + .iter() + .zip(crack) + .filter(|(q, _)| standing(s, q) && s.mat[q.tri as usize] == Mat::Plaster && q.ground <= LOSS[1] && q.rain >= OUTDOORS) + .map(|(q, &d)| (q, loss(q, d))) + .filter(|(_, l)| *l >= DEBRIS_LOSS) + .filter_map(|(q, l)| Some((Spot { what: "debris", by: "weather", at: landing(s, q)?, n: s.up, size: DEBRIS }, l))) + .collect(); + let mut kept = raea_sys_touch::thin_by(c, GAP_DEBRIS, |x| x.0.at, |_| true); + kept.sort_by(|a, b| a.0.at.x.total_cmp(&b.0.at.x).then(a.0.at.z.total_cmp(&b.0.at.z))); + kept +} diff --git a/systems/damage/src/tests.rs b/systems/damage/src/tests.rs new file mode 100644 index 000000000..87543bed1 --- /dev/null +++ b/systems/damage/src/tests.rs @@ -0,0 +1,190 @@ +//! A plastered front with a window opening 1.2 m wide and 1.6 m high, recessed 0.25 m to its glass, and the wall's +//! end at x = 6 (a building's outer corner). Points are sampled every 5 cm on the front as an atlas's texels would be; +//! the ground is the plane y = 0. + +use parry3d::glamx::Vec3; +use parry3d::query::{Ray, RayCast}; +use parry3d::shape::TriMesh; + +use raea_sys_touch::{Mat, Point, Surface}; + +use crate::{CRACKED, REACH, corners, cracked, cracks, debris, loss}; + +#[derive(Default)] +struct B { + pos: Vec, + tri: Vec<[u32; 3]>, + nrm: Vec, + mat: Vec, + walk: Vec, +} + +impl B { + fn quad(&mut self, c: [Vec3; 4], out: Vec3, m: Mat, walk: bool) { + let n = (c[1] - c[0]).cross(c[2] - c[0]).normalize(); + let c = if n.dot(out) < 0.0 { [c[0], c[3], c[2], c[1]] } else { c }; + let i = self.pos.len() as u32; + self.pos.extend(c); + for t in [[i, i + 1, i + 2], [i, i + 2, i + 3]] { + self.tri.push(t); + self.nrm.push(out); + self.mat.push(m); + self.walk.push(walk); + } + } + fn cube(&mut self, a: [f32; 3], b: [f32; 3], m: Mat) { + let v = |x: f32, y: f32, z: f32| Vec3::new(x, y, z); + let ([x0, y0, z0], [x1, y1, z1]) = (a, b); + self.quad([v(x0, y0, z0), v(x0, y0, z1), v(x0, y1, z1), v(x0, y1, z0)], -Vec3::X, m, false); + self.quad([v(x1, y0, z0), v(x1, y0, z1), v(x1, y1, z1), v(x1, y1, z0)], Vec3::X, m, false); + self.quad([v(x0, y0, z0), v(x1, y0, z0), v(x1, y0, z1), v(x0, y0, z1)], -Vec3::Y, m, false); + self.quad([v(x0, y1, z0), v(x1, y1, z0), v(x1, y1, z1), v(x0, y1, z1)], Vec3::Y, m, false); + self.quad([v(x0, y0, z0), v(x1, y0, z0), v(x1, y1, z0), v(x0, y1, z0)], -Vec3::Z, m, false); + self.quad([v(x0, y0, z1), v(x1, y0, z1), v(x1, y1, z1), v(x0, y1, z1)], Vec3::Z, m, false); + } + fn mesh(&self) -> TriMesh { + TriMesh::new(self.pos.clone(), self.tri.clone()).unwrap() + } + fn surface<'a>(&'a self, mesh: &'a TriMesh) -> Surface<'a> { + Surface { pos: &self.pos, tri: &self.tri, nrm: &self.nrm, mat: &self.mat, walk: &self.walk, mesh, up: Vec3::Y } + } +} + +const WIN: [f32; 4] = [-0.6, 0.6, 3.0, 4.6]; + +/// The front at z = 0 from x = -6 to 6 and 8 m up, of `m`, with the window cut through it, its glass 0.25 m in. +fn front(m: Mat) -> B { + let mut b = B::default(); + let [x0, x1, y0, y1] = WIN; + b.cube([-6.0, 0.0, -0.5], [x0, 8.0, 0.0], m); + b.cube([x1, 0.0, -0.5], [6.0, 8.0, 0.0], m); + b.cube([x0, 0.0, -0.5], [x1, y0, 0.0], m); + b.cube([x0, y1, -0.5], [x1, 8.0, 0.0], m); + b.cube([x0, y0, -0.5], [x1, y1, -0.25], Mat::Other); + let v = |x: f32, z: f32| Vec3::new(x, 0.0, z); + b.quad([v(-20.0, -20.0), v(20.0, -20.0), v(20.0, 20.0), v(-20.0, 20.0)], Vec3::Y, Mat::Other, true); + b +} + +/// The front's texels every 5 cm, outside the opening; `flow` and `rain` as the other maps would say. +fn texels(mesh: &TriMesh, flow: f32, rain: f32) -> Vec { + let mut out = Vec::new(); + for i in 0..239 { + for j in 0..159 { + let p = Vec3::new(-5.95 + i as f32 * 0.05, 0.025 + j as f32 * 0.05, 0.0); + let [x0, x1, y0, y1] = WIN; + if p.x > x0 && p.x < x1 && p.y > y0 && p.y < y1 { + continue; + } + let h = mesh.cast_local_ray_and_get_normal(&Ray::new(p + Vec3::Z * 0.02, -Vec3::Z), 0.05, false).expect("the front"); + out.push(Point { p, n: Vec3::Z, tri: h.subshape, ground: p.y, rain, flow, edge: 0.0 }); + } + } + out +} + +// the four corners of the opening, each leaving away from it; the wall's end at x = 6 isn't one +#[test] +fn an_openings_four_corners_and_no_others() { + let b = front(Mat::Plaster); + let mesh = b.mesh(); + let s = b.surface(&mesh); + let cs = corners(&s, &texels(&mesh, 0.0, 1.0)); + assert_eq!(cs.len(), 4, "{cs:?}"); + let [x0, x1, y0, y1] = WIN; + for (cx, cy) in [(x0, y0), (x0, y1), (x1, y0), (x1, y1)] { + let c = cs.iter().find(|c| c.at.distance(Vec3::new(cx, cy, 0.0)) < 0.2).unwrap_or_else(|| panic!("no corner at {cx}, {cy}: {cs:?}")); + let out = Vec3::new(cx.signum(), if cy == y1 { 1.0 } else { -1.0 }, 0.0).normalize(); + assert!(c.away.dot(out) > 0.95, "corner {cx}, {cy} leaves along {:?}", c.away); + assert!(c.n.dot(Vec3::Z) > 0.99); + } +} + +// each crack runs on the wall away from its corner, steeper than 45 degrees; texels on it are 0 from it, far ones +// REACH; the same front gives the same cracks +#[test] +fn cracks_leave_the_corners_along_the_wall() { + let b = front(Mat::Plaster); + let mesh = b.mesh(); + let s = b.surface(&mesh); + let pts = texels(&mesh, 0.0, 1.0); + let (d, cs) = cracks(&s, &pts); + assert_eq!(d.len(), pts.len()); + let [x0, x1, y0, y1] = WIN; + for c in &cs { + let path = crate::crack(&s, c); + assert!(path.len() >= 8, "a crack of {} steps from {:?}", path.len(), c.at); + let end = *path.last().unwrap(); + let run = end - c.at; + assert!(run.y.abs() > run.x.abs(), "steeper than 45: {run:?}"); + assert_eq!(run.y.signum(), c.away.y.signum(), "up from the head's corners, down from the sill's"); + assert_eq!(run.x.signum(), c.away.x.signum(), "away from the opening"); + for p in &path { + assert!(!(p.x > x0 && p.x < x1 && p.y > y0 && p.y < y1), "into the opening at {p:?}"); + assert!(p.z.abs() < 1e-4); + } + } + let near = pts.iter().zip(&d).filter(|(_, d)| **d < 0.03).count(); + assert!(near > 20, "{near} texels on the cracks"); + let far = pts.iter().zip(&d).find(|(q, _)| q.p.distance(Vec3::new(-4.0, 1.0, 0.0)) < 0.05).unwrap(); + assert_eq!(*far.1, REACH); + assert_eq!(cracks(&s, &pts).0, d); +} + +// the loss potential: the damp foot, a soaked face the rain doesn't wash, a knocked arris low down, a crack; nothing +// on a dry, rain-washed face up the wall +#[test] +fn what_loosens_a_coat() { + let q = |ground: f32, rain: f32, flow: f32, edge: f32| Point { p: Vec3::ZERO, n: Vec3::Z, tri: 0, ground, rain, flow, edge }; + assert!((loss(&q(0.2, 1.0, 0.0, 0.0), REACH) - 1.0).abs() < 1e-6, "the foot"); + assert_eq!(loss(&q(3.0, 1.0, 0.0, 0.0), REACH), 0.0, "a plain face up the wall"); + assert!((loss(&q(3.0, 0.1, 0.95, 0.0), REACH) - 0.8).abs() < 1e-6, "soaked under a sill"); + assert_eq!(loss(&q(3.0, 0.95, 0.95, 0.0), REACH), 0.0, "run-off the rain washes"); + assert!((loss(&q(1.0, 1.0, 0.0, 1.0), REACH) - 0.7).abs() < 0.2, "an arris low down"); + assert_eq!(loss(&q(3.0, 1.0, 0.0, 1.0), REACH), 0.0, "an arris out of reach"); + assert!((loss(&q(3.0, 1.0, 0.0, 0.0), 0.0) - 0.6).abs() < 1e-6, "on a crack"); +} + +// debris on the walk in front of the plaster's foot, 1.5 m apart, each with the potential above it; none in front of +// stone, whose face doesn't come off in sheets +#[test] +fn debris_under_the_plasters_foot() { + let b = front(Mat::Plaster); + let mesh = b.mesh(); + let s = b.surface(&mesh); + let pts = texels(&mesh, 0.0, 1.0); + let (d, _) = cracks(&s, &pts); + let spots = debris(&s, &pts, &d); + assert!(spots.len() >= 5, "{} heaps along 12 m", spots.len()); + for (sp, l) in &spots { + assert!(sp.at.y.abs() < 1e-4 && (sp.at.z - 0.2).abs() < 1e-4, "on the walk in front: {:?}", sp.at); + assert!(*l >= 0.5 && *l <= 1.0); + assert_eq!(sp.what, "debris"); + } + for (i, a) in spots.iter().enumerate() { + assert!(spots[i + 1..].iter().all(|b| a.0.at.distance(b.0.at) >= 1.5)); + } + // a wall the rain doesn't reach is indoors; a plinth's top under the foot is no walk + assert!(debris(&s, &texels(&mesh, 0.0, 0.0), &d).is_empty(), "indoors"); + let mut b = front(Mat::Plaster); + b.cube([-6.0, 0.0, 0.0], [6.0, 0.6, 0.3], Mat::Masonry); + let mesh = b.mesh(); + let s = b.surface(&mesh); + let pts: Vec = texels(&mesh, 0.0, 1.0).into_iter().filter(|q| q.p.y > 0.6).map(|q| Point { ground: q.p.y, ..q }).collect(); + let (d, _) = cracks(&s, &pts); + assert!(debris(&s, &pts, &d).is_empty(), "on a plinth 0.3 m out, a heap 0.2 m out lands on its top"); + let stone = front(Mat::Masonry); + let mesh = stone.mesh(); + let s = stone.surface(&mesh); + let pts = texels(&mesh, 0.0, 1.0); + assert!(debris(&s, &pts, &vec![REACH; pts.len()]).is_empty()); +} + +// about CRACKED in a hundred corners crack, the same ones every time: a front of 20 x 20 windows' corners +#[test] +fn about_half_the_corners_crack() { + let at: Vec = (0..400).map(|i| Vec3::new((i % 20) as f32 * 2.5 - 0.6, (i / 20) as f32 * 3.4 + 1.5, 0.0)).collect(); + let n = at.iter().filter(|&&p| cracked(p)).count(); + assert!((n as i64 - CRACKED as i64 * 4).abs() < 60, "{n} of 400 crack"); + assert!(at.iter().all(|&p| cracked(p) == cracked(p))); +} diff --git a/systems/foliage/Cargo.toml b/systems/foliage/Cargo.toml index 5bcaf2658..cc1795edf 100644 --- a/systems/foliage/Cargo.toml +++ b/systems/foliage/Cargo.toml @@ -11,3 +11,5 @@ parry3d = "0.31" serde_json = "1" image = { version = "0.25", default-features = false, features = ["png"] } raea-sys-glb = { path = "../glb" } +# smoothstep, shared with raea-sys-damage +raea-core-ease = { path = "../../core/ease" } diff --git a/systems/foliage/src/leaves.rs b/systems/foliage/src/leaves.rs index 25f9935c6..ccd11d325 100644 --- a/systems/foliage/src/leaves.rs +++ b/systems/foliage/src/leaves.rs @@ -130,10 +130,7 @@ pub(crate) fn leaves(sp: &Species, req: &Request, nodes: &[Node], env: &Envelope } /// 0 below `a`, 1 above `b`, smoothly between (a leaf's gaps, its teeth's roots in atlas.rs). -pub(crate) 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) -} +pub(crate) use raea_core_ease::smoothstep as smooth; /// Value noise in 3D, 0 to 1, from a seed. fn noise3(p: Vec3, seed: u64) -> f32 { diff --git a/systems/touch/src/lib.rs b/systems/touch/src/lib.rs index 49f12e571..4edeb4eec 100644 --- a/systems/touch/src/lib.rs +++ b/systems/touch/src/lib.rs @@ -21,10 +21,10 @@ use std::collections::HashMap; use parry3d::glamx::Vec3; use parry3d::shape::TriMesh; -pub use spots::Spot; +pub use spots::{Spot, thin_by}; /// Bumped when the output would change for the same input (a bake that uses it keys on it). -pub const VERSION: &str = "raea-sys-touch 4"; +pub const VERSION: &str = "raea-sys-touch 5"; /// What a triangle is made of, as far as touch goes. #[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)] @@ -120,8 +120,8 @@ impl Parts { } } -/// A seed from a place, the same on every machine (the lock side of a single leaf). -pub(crate) fn seed(p: Vec3) -> u64 { +/// A seed from a place, the same on every machine (the lock side of a single leaf; raea-sys-damage's cracks). +pub fn seed(p: Vec3) -> u64 { let q = |v: f32| (v * 100.0).round() as i64 as u64; let mut h = 0xcbf2_9ce4_8422_2325u64; for v in [q(p.x), q(p.y), q(p.z)] { diff --git a/systems/touch/src/spots.rs b/systems/touch/src/spots.rs index 736a3d828..2bd239b57 100644 --- a/systems/touch/src/spots.rs +++ b/systems/touch/src/spots.rs @@ -4,9 +4,8 @@ //! facing open ground, GAP_BILL apart; //! - street plates (the city): on a building's corner, 2.5-3 m up, one on each face, where the arris runs from the //! walking surface to 3.5 m and both faces look onto open ground; -//! - nameplates (the tenant): beside a single door's lock side, 1.5 m up, on the wall; -//! - debris (the weather): on the ground under plaster that run-off and rain soak at its foot (blown plaster's -//! place, until WR6 decides where plaster is lost). +//! - nameplates (the tenant): beside a single door's lock side, 1.5 m up, on the wall. +//! Debris under lost plaster is raea-sys-damage's (WR6), by the loss potential raea/wear's recipes use. //! Candidates are taken in the order of a seed from their place, each kept if none kept is nearer than its gap. use std::collections::BTreeMap; @@ -36,8 +35,6 @@ const PLATE: [f32; 2] = [0.6, 0.18]; const CORNER: f32 = 0.4; const GAP_PLATE: f32 = 2.0; const NAMEPLATE: [f32; 2] = [0.3, 0.12]; -const DEBRIS: [f32; 2] = [0.5, 0.3]; -const GAP_DEBRIS: f32 = 1.5; /// open ground in front: a ray out of the face runs this far free const OPEN: f32 = 2.0; /// a ray that runs this far free reaches the sky @@ -86,12 +83,19 @@ fn thin(c: Vec, gap: f32) -> Vec { } /// As thin, keeping only candidates that pass `ok` (tested only on those the gap leaves). -fn thin_if(mut c: Vec, gap: f32, ok: impl Fn(&Spot) -> bool) -> Vec { - c.sort_by_key(|s| seed(s.at)); - let mut kept: Vec = Vec::new(); - for s in c { - if !kept.iter().any(|k| k.at.distance(s.at) < gap) && ok(&s) { - kept.push(s); +fn thin_if(c: Vec, gap: f32, ok: impl Fn(&Spot) -> bool) -> Vec { + thin_by(c, gap, |s| s.at, ok) +} + +/// Candidates of any kind kept in seed order of where each is (`at`), none nearer than `gap` to one kept, and only +/// those that pass `ok` (tested only on those the gap leaves): thin's rule for what carries a spot (raea-sys-damage's +/// debris with its loss). +pub fn thin_by(mut c: Vec, gap: f32, at: impl Fn(&T) -> Vec3, ok: impl Fn(&T) -> bool) -> Vec { + c.sort_by_cached_key(|x| seed(at(x))); + let mut kept: Vec = Vec::new(); + for x in c { + if !kept.iter().any(|k| at(k).distance(at(&x)) < gap) && ok(&x) { + kept.push(x); } } kept @@ -158,11 +162,6 @@ pub(crate) fn spots(s: &Surface, doors: &[Door], pts: &[Point]) -> Vec { } } - // debris: under plaster soaked at its foot, on the walking surface in front - let soaked = pts.iter().filter(|q| s.mat[q.tri as usize] == Mat::Plaster && standing(s, q) && q.ground <= 1.2 && q.flow > 0.5 && q.rain > 0.5); - let debris = soaked.map(|q| Spot { what: "debris", by: "weather", at: q.p - s.up * q.ground + q.n * 0.2, n: s.up, size: DEBRIS }).collect(); - out.extend(thin(debris, GAP_DEBRIS)); - out.sort_by(|a, b| a.what.cmp(b.what).then(a.at.x.total_cmp(&b.at.x)).then(a.at.y.total_cmp(&b.at.y)).then(a.at.z.total_cmp(&b.at.z))); out } diff --git a/systems/wear/Cargo.toml b/systems/wear/Cargo.toml deleted file mode 100644 index a9a6b7e9a..000000000 --- a/systems/wear/Cargo.toml +++ /dev/null @@ -1,14 +0,0 @@ -[package] -name = "raea-sys-wear" -version = "0.1.0" -edition = "2024" -license = "FSL-1.1-ALv2" -publish = false -description = "Worn surfaces: the standard material with chipped edges, grime, rust streaks and mottled paint over it, its noise in the mesh's own space so the wear stays on a moving part" - -[dependencies] -bevy = { version = "=0.20.0", default-features = false, features = ["std", "bevy_pbr"] } -# a mesh row's values -raea-core-program = { path = "../../core/program" } -# a material's `wear` prop, as the SDK sends it -serde_json = "1" diff --git a/systems/wear/src/lib.rs b/systems/wear/src/lib.rs deleted file mode 100644 index d03127f37..000000000 --- a/systems/wear/src/lib.rs +++ /dev/null @@ -1,106 +0,0 @@ -//! Worn surfaces: the standard material with use written over it. Paint mottled by noise, its edges chipped back to -//! `chip_color` (the metal under the paint, shinier), grime gathered low and on undersides, and rust run down in -//! streaks. The noise is taken in the mesh's own space, not the world's, so a walking robot's wear stays where it is -//! on each part instead of swimming over it; a part built in rest-pose coordinates (as a rigged build's pieces are) -//! shares one space with its neighbours, so their wear lines up across a seam. Edges are found from how fast the -//! surface's normal turns on screen against how fast its position does (its curvature, 1 / radius), so a rounded edge -//! of a few millimetres chips and a broad face doesn't. -//! -//! A mesh row's columns (all optional but wear_amount): wear_amount (0..1, how worn; on when > 0), wear_scale (metres -//! across a blotch, 0.08), wear_chips, wear_grime, wear_rust (each 0..1 of the amount: 0.6, 0.5, 0.25), wear_seed, -//! wear_chip_color ('#3a3c40'), wear_grime_color ('#3b3226'), wear_rust_color ('#7a3f1c'). `columns` makes them from -//! a material's `wear` prop (raea-runtime-react's scene3d); `of` reads them back where the engine spawns the mesh. - -use bevy::pbr::{ExtendedMaterial, MaterialExtension}; -use bevy::prelude::*; -use bevy::render::render_resource::{AsBindGroup, ShaderType}; -use bevy::shader::ShaderRef; -use raea_core_program::ir::V; -use serde_json::{Map, Value}; -use std::collections::BTreeMap; - -pub type WearMaterial = ExtendedMaterial; - -pub fn install(app: &mut App) { - bevy::asset::embedded_asset!(app, "wear.wesl"); - app.add_plugins(MaterialPlugin::::default()); -} - -#[derive(Asset, TypePath, AsBindGroup, Clone, Debug)] -pub struct Wear { - #[uniform(100)] - p: WearParams, -} - -#[derive(ShaderType, Clone, Copy, Default, PartialEq, Debug)] -struct WearParams { - chip: Vec4, - grime: Vec4, - rust: Vec4, - amount: f32, - scale: f32, - chips: f32, - grimes: f32, - rusts: f32, - seed: f32, -} - -impl MaterialExtension for Wear { - fn fragment_shader() -> ShaderRef { - "embedded://raea_sys_wear/wear.wesl".into() - } -} - -/// The prop's keys and the columns they become; colours pass through as the hex the SDK checked -const NUMS: [(&str, &str); 6] = - [("amount", "wear_amount"), ("scale", "wear_scale"), ("chips", "wear_chips"), ("grime", "wear_grime"), ("rust", "wear_rust"), ("seed", "wear_seed")]; -const COLOURS: [(&str, &str); 3] = [("chipColor", "wear_chip_color"), ("grimeColor", "wear_grime_color"), ("rustColor", "wear_rust_color")]; - -/// A material's `wear` prop as its row's columns (the first frame's, as a grid's are) -pub fn columns(row: &mut BTreeMap, props: &Map) { - let Some(w) = props.get("wear").and_then(Value::as_object) else { return }; - for (k, col) in NUMS { - if let Some(n) = w.get(k).and_then(Value::as_f64) { - row.insert(col.into(), V::N(n)); - } - } - for (k, col) in COLOURS { - if let Some(s) = w.get(k).and_then(Value::as_str) { - row.insert(col.into(), V::S(s.into())); - } - } -} - -/// The wear a mesh row asks for, or None (no wear_amount above 0) -pub fn of(vals: &BTreeMap) -> Option { - let num = |col: &str| vals.get(col).map(|v| v.num() as f32); - let amount = num("wear_amount").unwrap_or(0.0).min(1.0); - if amount <= 0.0 { - return None; - } - let rgb = |col: &str, d: Srgba| { - let c = match vals.get(col) { - Some(V::S(s)) => Srgba::hex(s.trim()).unwrap_or(d), - _ => d, - }; - let l = LinearRgba::from(c); - Vec4::new(l.red, l.green, l.blue, 1.0) - }; - let share = |col: &str, d: f32| num(col).unwrap_or(d).clamp(0.0, 1.0); - Some(Wear { - p: WearParams { - chip: rgb("wear_chip_color", Srgba::rgb(0.227, 0.235, 0.251)), - grime: rgb("wear_grime_color", Srgba::rgb(0.231, 0.196, 0.149)), - rust: rgb("wear_rust_color", Srgba::rgb(0.478, 0.247, 0.11)), - amount, - scale: num("wear_scale").filter(|s| *s > 0.0).unwrap_or(0.08), - chips: share("wear_chips", 0.6), - grimes: share("wear_grime", 0.5), - rusts: share("wear_rust", 0.25), - seed: num("wear_seed").unwrap_or(0.0), - }, - }) -} - -#[cfg(test)] -mod tests; diff --git a/systems/wear/src/tests.rs b/systems/wear/src/tests.rs deleted file mode 100644 index 172423fdf..000000000 --- a/systems/wear/src/tests.rs +++ /dev/null @@ -1,31 +0,0 @@ -use super::*; -use serde_json::json; - -fn row(v: Value) -> BTreeMap { - let mut row = BTreeMap::new(); - columns(&mut row, v.as_object().unwrap()); - row -} - -#[test] -fn a_prop_becomes_columns() { - let r = row(json!({ "wear": { "amount": 0.7, "rust": 0.4, "chipColor": "#202020", "bogus": 1 } })); - assert_eq!(r.len(), 3); - assert!(matches!(r.get("wear_amount"), Some(V::N(n)) if *n == 0.7)); - assert!(matches!(r.get("wear_chip_color"), Some(V::S(s)) if s == "#202020")); - assert!(row(json!({ "color": "#fff" })).is_empty()); -} - -#[test] -fn off_without_an_amount() { - assert!(of(&BTreeMap::new()).is_none()); - assert!(of(&row(json!({ "wear": { "amount": 0 } }))).is_none()); -} - -#[test] -fn defaults_and_clamps() { - let w = of(&row(json!({ "wear": { "amount": 3, "chips": -1, "scale": 0 } }))).unwrap(); - assert_eq!((w.p.amount, w.p.chips, w.p.scale, w.p.grimes), (1.0, 0.0, 0.08, 0.5)); - let red = of(&row(json!({ "wear": { "amount": 0.5, "rustColor": "#ff0000" } }))).unwrap(); - assert_eq!(red.p.rust, Vec4::new(1.0, 0.0, 0.0, 1.0)); -} diff --git a/systems/wear/src/wear.wesl b/systems/wear/src/wear.wesl deleted file mode 100644 index 8c15cfe72..000000000 --- a/systems/wear/src/wear.wesl +++ /dev/null @@ -1,121 +0,0 @@ -// lib.rs: wear over the standard material (Bevy's extended-material fragment, its lighting kept). Noise in the mesh's -// own space; edges from screen-space curvature; the paint's colour, roughness and metalness changed before the light. -import bevy_pbr::render::pbr_fragment::pbr_input_from_standard_material; -import bevy_pbr::render::pbr_functions::alpha_discard; -import bevy_pbr::render::mesh_functions::get_local_from_world; -@if(PREPASS_PIPELINE) import bevy_pbr::prepass::io::{VertexOutput, FragmentOutput}; -@if(PREPASS_PIPELINE) import bevy_pbr::deferred::functions::deferred_output; -@if(!PREPASS_PIPELINE) import bevy_pbr::render::forward_io::{VertexOutput, FragmentOutput}; -@if(!PREPASS_PIPELINE) import bevy_pbr::render::pbr_functions::{apply_pbr_lighting, main_pass_post_lighting_processing}; - -struct Wear { - chip: vec4, - grime: vec4, - rust: vec4, - amount: f32, - scale: f32, - chips: f32, - grimes: f32, - rusts: f32, - seed: f32, -} - -@group(constants::MATERIAL_BIND_GROUP) @binding(100) -var wear: Wear; - -fn hash(p: vec3) -> f32 { - let q = fract(p * 0.3183099 + vec3(0.1, 0.2, 0.3)); - let r = q * 17.0; - return fract(r.x * r.y * r.z * (r.x + r.y + r.z)); -} - -fn vnoise(p: vec3) -> f32 { - let i = floor(p); - let f = fract(p); - let u = f * f * (3.0 - 2.0 * f); - let a = mix(mix(hash(i), hash(i + vec3(1.0, 0.0, 0.0)), u.x), mix(hash(i + vec3(0.0, 1.0, 0.0)), hash(i + vec3(1.0, 1.0, 0.0)), u.x), u.y); - let b = mix(mix(hash(i + vec3(0.0, 0.0, 1.0)), hash(i + vec3(1.0, 0.0, 1.0)), u.x), mix(hash(i + vec3(0.0, 1.0, 1.0)), hash(i + vec3(1.0, 1.0, 1.0)), u.x), u.y); - return mix(a, b, u.z); -} - -// four octaves, 0..1 -fn fbm(p: vec3) -> f32 { - var s = 0.0; - var w = 0.5; - var q = p; - for (var k = 0; k < 4; k++) { - s += w * vnoise(q); - q = q * 2.03 + vec3(1.7, 9.2, 3.1); - w *= 0.5; - } - return s / 0.9375; -} - -@fragment -fn fragment( - in: VertexOutput, - @builtin(front_facing) is_front: bool, -) -> FragmentOutput { - var pbr_input = pbr_input_from_standard_material(in, is_front); - - var p = in.world_position.xyz; - var n = normalize(in.world_normal); -@if(VERTEX_OUTPUT_INSTANCE_INDEX) { - // the mesh's own space, so the wear rides with the part - let m = get_local_from_world(in.instance_index); - p = (m * vec4(in.world_position.xyz, 1.0)).xyz; - n = normalize((m * vec4(n, 0.0)).xyz); -} - let q = p / wear.scale + vec3(wear.seed * 13.1); - - // curvature (1 / metres): how fast the normal turns against how fast the position moves, on screen - let curve = length(fwidth(in.world_normal)) / max(length(fwidth(in.world_position.xyz)), 1e-5); - let edge = smoothstep(25.0, 90.0, curve) + 0.5 * smoothstep(0.12, 0.35, 1.0 - max(abs(n.x), max(abs(n.y), abs(n.z)))); - let a = wear.amount; - - var c = pbr_input.material.base_color.rgb; - var rough = pbr_input.material.perceptual_roughness; - var metal = pbr_input.material.metallic; - - // paint: mottled a little, and duller where it's thin - let mottle = fbm(q * 0.6); - c *= 1.0 + (mottle - 0.5) * 0.22 * a; - rough = clamp(rough + (fbm(q * 1.7 + 5.0) - 0.5) * 0.3 * a, 0.04, 1.0); - - // grime: low, in hollows and undersides, broken up - let low = clamp(-n.y, 0.0, 1.0) * 0.6 + smoothstep(0.55, 0.85, fbm(q * 0.35 + 20.0)); - let g = clamp(low * wear.grimes * a, 0.0, 0.85) * smoothstep(0.3, 0.7, fbm(q * 2.3 + 40.0) + 0.25); - c = mix(c, wear.grime.rgb, g); - rough = mix(rough, 0.9, g); - - // rust: streaks run down from blotches (noise squashed along local y) - let streak = fbm(vec3(q.x * 3.0, q.y * 0.25, q.z * 3.0) + 60.0); - let blotch = smoothstep(0.6, 0.8, fbm(q * 0.5 + 80.0)); - let r = clamp((blotch + smoothstep(0.62, 0.8, streak) * 0.6) * wear.rusts * a, 0.0, 0.9); - c = mix(c, wear.rust.rgb * (0.7 + 0.6 * vnoise(q * 6.0)), r); - rough = mix(rough, 0.95, r); - metal = mix(metal, 0.0, r); - - // chips: the paint gone at edges and a few scattered spots, the metal under it showing, shinier - // an edge lowers the bar a long way, so at full wear most edges chip and only the odd spot on a broad face does - let s = wear.chips * a; - let field = fbm(q * 2.5 + 100.0) + edge * 0.5 - 0.2; - let chip = smoothstep(1.0 - s * 0.55, 1.04 - s * 0.55, field); - c = mix(c, wear.chip.rgb, chip); - rough = mix(rough, 0.32, chip); - metal = mix(metal, 0.85, chip); - - pbr_input.material.base_color = vec4(c, pbr_input.material.base_color.a); - pbr_input.material.perceptual_roughness = rough; - pbr_input.material.metallic = metal; - pbr_input.material.base_color = alpha_discard(pbr_input.material.flags, pbr_input.material.alpha_cutoff, pbr_input.material.base_color); - -@if(PREPASS_PIPELINE) { - return deferred_output(in, pbr_input); -} @else { - var out: FragmentOutput; - out.color = apply_pbr_lighting(pbr_input); - out.color = main_pass_post_lighting_processing(pbr_input, out.color); - return out; -} -} diff --git a/systems/weathering/Cargo.toml b/systems/weathering/Cargo.toml index 96861cf86..40247f8e3 100644 --- a/systems/weathering/Cargo.toml +++ b/systems/weathering/Cargo.toml @@ -16,6 +16,7 @@ image = { version = "0.25", default-features = false, features = ["png"] } raea-sys-runoff = { path = "../runoff" } raea-sys-touch = { path = "../touch" } raea-sys-exposure = { path = "../exposure" } +raea-sys-damage = { path = "../damage" } # a union-find's root (charts merged by shared edges) raea-core-meshcheck = { path = "../../core/meshcheck" } raea-sys-glb = { path = "../glb" } diff --git a/systems/weathering/src/lib.rs b/systems/weathering/src/lib.rs index 41892c0ed..e55aed6ec 100644 --- a/systems/weathering/src/lib.rs +++ b/systems/weathering/src/lib.rs @@ -11,7 +11,8 @@ //! causes0 = (sky: rain reach, sun: share of the sun's path seen, cavity: occlusion within CAVITY_REACH, edge: //! nearness to a convex arris); causes1 = (flow, deposit, deposit kind, touch); causes2 = (ground: height over the //! walking surface, 0-4 m; element: the chart's own number; open: the share of the whole sky seen; class: the -//! triangle's material class as `Class::code`); causes3 = (winter sun, drift, litter, spare). +//! triangle's material class as `Class::code`); causes3 = (winter sun, drift, litter, crack: 1 - the distance to the +//! nearest crack from an opening's corner over raea-sys-damage's REACH). mod charts; mod flow; @@ -35,7 +36,7 @@ pub use scene::{Class, Classes}; type R = Result; /// Bumped when a bake's bytes would change for the same request. -const VERSION: &str = "raea-sys-weathering 6"; +const VERSION: &str = "raea-sys-weathering 7"; /// The world the bake's causes come from. #[derive(Clone, Debug)] @@ -146,6 +147,7 @@ pub fn bake(store: &Path, src: &Path, req: &Value) -> R { key.update(raea_sys_runoff::VERSION.as_bytes()); key.update(raea_sys_touch::VERSION.as_bytes()); key.update(raea_sys_exposure::VERSION.as_bytes()); + key.update(raea_sys_damage::VERSION.as_bytes()); key.update(canonical(&strip_src(req)).as_bytes()); key.update(&bytes); let key: String = key.finalize().iter().take(12).map(|b| format!("{b:02x}")).collect(); @@ -168,7 +170,10 @@ pub fn bake(store: &Path, src: &Path, req: &Value) -> R { let (mut c0, mut c1, mut c2, mut c3) = (vec![[0u8; 4]; n], vec![[0u8; 4]; n], vec![[0u8; 4]; n], vec![[0u8; 4]; n]); rays::causes(&sc, &at, &env, &mesh, &mut c0, &mut c2, &mut c3); flow::flow(&sc, &at, &env, &mesh, &c0, &mut c1); - let spots = touch::touch(&sc, &at, &env, &mesh, &c0, &mut c1, &c2); + let (spots, crack) = touch::touch(&sc, &at, &env, &mesh, &c0, &mut c1, &c2); + for (tx, b) in at.texels.iter().zip(crack) { + c3[at.px(tx.x, tx.y)][3] = b; + } let t3 = Instant::now(); std::fs::create_dir_all(&dir).map_err(|e| format!("{}: {e}", dir.display()))?; let model = dir.join("model.glb"); diff --git a/systems/weathering/src/rays.rs b/systems/weathering/src/rays.rs index d6bac3e1d..b430b566a 100644 --- a/systems/weathering/src/rays.rs +++ b/systems/weathering/src/rays.rs @@ -220,7 +220,8 @@ pub(crate) fn causes(sc: &Scene, at: &Atlas, env: &Env, mesh: &TriMesh, c0: &mut let edge = edges.near(p, reach_of(t.tri)); let ground = ground(sc, mesh, env, t.tri, p, n); let element = (crate::rays::hash(at.chart_of[t.tri as usize].wrapping_add(17)) & 0xff) as u8; - let c3 = [byte(x.december), byte(x.drift), byte(x.litter), 255]; + // a: the crack, raea-sys-damage's (touch.rs) + let c3 = [byte(x.december), byte(x.drift), byte(x.litter), 0]; ([byte(sky), byte(x.sun), byte(occl), byte(edge)], [byte(ground / GROUND_RANGE), element, byte(open), sc.class[t.tri as usize].code()], c3) }) .collect(); diff --git a/systems/weathering/src/tests.rs b/systems/weathering/src/tests.rs index 28afd8c4e..46d30ca70 100644 --- a/systems/weathering/src/tests.rs +++ b/systems/weathering/src/tests.rs @@ -332,7 +332,8 @@ fn a_door_is_held_on_one_side_and_gets_its_nameplate() { let mut c3 = vec![[0u8; 4]; n]; rays::causes(&sc, &at, &e, &mesh, &mut c0, &mut c2, &mut c3); flow::flow(&sc, &at, &e, &mesh, &c0, &mut c1); - touch::touch(&sc, &at, &e, &mesh, &c0, &mut c1, &c2); + let (_, crack) = touch::touch(&sc, &at, &e, &mesh, &c0, &mut c1, &c2); + assert_eq!(crack.len(), at.texels.len()); let touched = |keep: &dyn Fn(Vec3, Vec3) -> bool| at.texels.iter().any(|t| keep(t.p, t.n) && c1[t.y as usize * at.w as usize + t.x as usize][3] > 128); let held = |side: f32| touched(&|p, n| n.z > 0.99 && (p.z + 0.25).abs() < 0.01 && (0.97..1.08).contains(&p.y) && p.x * side > 0.25); assert!(held(1.0) != held(-1.0), "the handle band on one side of the leaf only"); @@ -343,5 +344,7 @@ fn a_door_is_held_on_one_side_and_gets_its_nameplate() { let out = bake(&tmp.join("store"), &tmp.join("door.glb"), &req).unwrap(); let spots: Value = serde_json::from_str(&std::fs::read_to_string(out["spots"].as_str().unwrap()).unwrap()).unwrap(); assert_eq!(spots.as_array().unwrap().iter().filter(|s| s["what"] == "nameplate").count(), 1, "{spots}"); + // the plaster's foot sheds: debris in front of it, each with its loss potential (raea-sys-damage) + assert!(spots.as_array().unwrap().iter().any(|s| s["what"] == "debris" && s["loss"].as_f64().is_some_and(|l| l >= 0.5)), "{spots}"); let _ = std::fs::remove_dir_all(&tmp); } diff --git a/systems/weathering/src/touch.rs b/systems/weathering/src/touch.rs index bcae5e24a..2f24cc632 100644 --- a/systems/weathering/src/touch.rs +++ b/systems/weathering/src/touch.rs @@ -1,9 +1,11 @@ //! causes1's touch and spots.json (WR3): the model handed to raea-sys-touch with each triangle's material and whether //! it is walked on, and each texel with what the other maps already say there (its height over the walk, the rain's -//! reach, the run-off passing, the nearness to an arris). +//! reach, the run-off passing, the nearness to an arris). The same texels go to raea-sys-damage (WR6): causes3's a +//! is each one's nearness to a crack from an opening's corner, and debris joins the spots with its loss potential. use parry3d::glamx::Vec3; use parry3d::shape::TriMesh; +use raea_sys_damage as damage; use raea_sys_touch::{Mat, Point, Spot, Surface, mark}; use serde_json::{Value, json}; @@ -23,8 +25,8 @@ fn mat(c: Class) -> Mat { } } -/// Touch into causes1's a; the spots, as JSON. -pub(crate) fn touch(sc: &Scene, at: &Atlas, env: &Env, mesh: &TriMesh, c0: &[[u8; 4]], c1: &mut [[u8; 4]], c2: &[[u8; 4]]) -> Value { +/// Touch into causes1's a; the spots, as JSON, and each texel's crack byte (causes3's a). +pub(crate) fn touch(sc: &Scene, at: &Atlas, env: &Env, mesh: &TriMesh, c0: &[[u8; 4]], c1: &mut [[u8; 4]], c2: &[[u8; 4]]) -> (Value, Vec) { let mats: Vec = sc.class.iter().map(|&c| mat(c)).collect(); let walk: Vec = (0..sc.tri.len()).map(|t| walks(sc, env, t)).collect(); let s = Surface { pos: &sc.pos, tri: &sc.tri, nrm: &sc.nrm, mat: &mats, walk: &walk, mesh, up: env.up }; @@ -34,11 +36,20 @@ pub(crate) fn touch(sc: &Scene, at: &Atlas, env: &Env, mesh: &TriMesh, c0: &[[u8 Point { p: tx.p, n: tx.n, tri: tx.tri, ground: f(c2[i][0]) * GROUND_RANGE, rain: f(c0[i][0]), flow: f(c1[i][0]), edge: f(c0[i][3]) } }).collect(); let (touch, spots) = mark(&s, &pts); + let (cracks, _) = damage::cracks(&s, &pts); for (tx, v) in at.texels.iter().zip(touch) { c1[at.px(tx.x, tx.y)][3] = (v.clamp(0.0, 1.0) * 255.0).round() as u8; } + let crack = cracks.iter().map(|d| ((1.0 - d / damage::REACH).clamp(0.0, 1.0) * 255.0).round() as u8).collect(); let v3 = |v: Vec3| json!([round(v.x), round(v.y), round(v.z)]); - json!(spots.iter().map(|s: &Spot| json!({ "what": s.what, "by": s.by, "at": v3(s.at), "n": v3(s.n), "size": s.size })).collect::>()) + let spot = |s: &Spot| json!({ "what": s.what, "by": s.by, "at": v3(s.at), "n": v3(s.n), "size": s.size }); + let mut out: Vec = spots.iter().map(spot).collect(); + out.extend(damage::debris(&s, &pts, &cracks).iter().map(|(s, l)| { + let mut v = spot(s); + v["loss"] = json!(round(*l)); + v + })); + (json!(out), crack) } fn round(v: f32) -> f64 { diff --git a/tools/dupes.max b/tools/dupes.max index 84a200447..54dcb9cc7 100644 --- a/tools/dupes.max +++ b/tools/dupes.max @@ -30,4 +30,4 @@ # core/grow's would change every tree) # near: runtime/live props.rs Live::controls/held (accessors); io/av1 and io/soft Backend::sound (one-line forwards) exact=294 -near=59 +near=58 diff --git a/tools/layers.toml b/tools/layers.toml index a8e1fea8b..d6cb16eb8 100644 --- a/tools/layers.toml +++ b/tools/layers.toml @@ -98,11 +98,11 @@ raea-sys-measure = "systems" raea-sys-canvas = "systems" raea-sys-tweak = "systems" raea-sys-filters = "systems" -raea-sys-wear = "systems" raea-sys-weathering = "systems" raea-sys-runoff = "systems" raea-sys-touch = "systems" raea-sys-exposure = "systems" +raea-sys-damage = "systems" raea-sys-glb = "systems" raea-sys-procmat = "systems" raea-sys-grass = "systems" @@ -274,7 +274,6 @@ raea-sys-fingerprint = true raea-sys-fingerprint-use = true raea-sys-song = true raea-sys-k = true -raea-sys-wear = true raea-sys-procmat = true # trees grown by species as meshes: crowns, leaves, bark and roots (the city's tree LODs build on them) raea-sys-foliage = true @@ -293,5 +292,7 @@ raea-sys-runoff = true raea-sys-touch = true # what a model is exposed to through the year: the sun by date, driven snow, where blown things settle (the weathering bake's causes3) raea-sys-exposure = true +# where a building breaks: cracks from its openings' corners, how readily a coat comes off, debris under the losses (the weathering bake's causes3 a and debris) +raea-sys-damage = true # a .glb read as JSON and bytes and written back (the weathering bake reads and rewrites models through it) raea-sys-glb = true diff --git a/tools/sdk-coverage.min b/tools/sdk-coverage.min index 1fa85e6cd..78c916853 100644 --- a/tools/sdk-coverage.min +++ b/tools/sdk-coverage.min @@ -1 +1 @@ -1557 +1556 diff --git a/tools/taxonomy.list b/tools/taxonomy.list index 5df465b68..a579540f6 100644 --- a/tools/taxonomy.list +++ b/tools/taxonomy.list @@ -56,7 +56,7 @@ raea Compute a compute shader run once a frame before the cameras draw ( raea ShaderExtension raea's MaterialExtension running a surface shader (ExtendedMaterial's extension) raea GridExtension raea's MaterialExtension drawing a grid (ExtendedMaterial's extension) raea PaintExtension raea's MaterialExtension for the paint look (ExtendedMaterial's extension) -raea WearExtension raea's MaterialExtension that chips, grimes and rusts a StandardMaterial in the part's own space (systems/wear); Bevy has none +raea WearExtension raea's surface shader that chips, grimes and rusts a StandardMaterial in the part's own space (sdk/render worn.ts, on the ShaderExtension hook); Bevy has none raea ProceduralExtension raea's MaterialExtension that draws wood, stone, brick, tiles and the rest on a StandardMaterial with dust, dirt and worn edges (systems/procmat); Bevy has none raea ToonExtension raea's MaterialExtension for toon bands (ExtendedMaterial's extension) raea ToonMaterial StandardMaterial with ToonExtension (S2a's table: raea's)