From 09a8e6ae6e303185af722707e9ab604617c2b777 Mon Sep 17 00:00:00 2001 From: lyeepedro Date: Wed, 18 Nov 2026 12:37:03 +0000 Subject: [PATCH 1/3] Water: draw with the entity's authored material when it has one set_water adds a Custom Mesh Filter and a Mesh Renderer so the water entity can carry a .mat; the renderer falls back to its built-in look only when none is assigned. Co-Authored-By: Claude Sonnet 5.5 --- src/caffeine/capi/EngineAPI.cpp | 9 +++++++++ src/caffeine/render/GpuSceneRenderer.cpp | 11 +++++++---- 2 files changed, 16 insertions(+), 4 deletions(-) diff --git a/src/caffeine/capi/EngineAPI.cpp b/src/caffeine/capi/EngineAPI.cpp index 1963b51..618c616 100644 --- a/src/caffeine/capi/EngineAPI.cpp +++ b/src/caffeine/capi/EngineAPI.cpp @@ -2131,6 +2131,15 @@ CaffeineResult caffeine_session_set_water(CaffeineSession* session, CaffeineEnti if (!session || !water) return CAFFEINE_INVALID_ARGUMENT; if (!entityAlive(*session, entityId)) return CAFFEINE_NOT_FOUND; const Caffeine::ECS::Entity entity = entityOf(*session, entityId); + // The renderer draws water from the mesh-filter pass, and a material assigned to the entity + // (a .mat) is the water's material: give the entity the components that carry them. + if (!session->world.get(entity)) { + session->world.add(entity).primitive = + Caffeine::ECS::MeshPrimitive::Custom; + } + if (!session->world.get(entity)) { + session->world.add(entity); + } auto* fluid = session->world.get(entity); if (!fluid) fluid = &session->world.add(entity); fluid->enabled = water->enabled ? 1 : 0; diff --git a/src/caffeine/render/GpuSceneRenderer.cpp b/src/caffeine/render/GpuSceneRenderer.cpp index 466fe07..c53df17 100644 --- a/src/caffeine/render/GpuSceneRenderer.cpp +++ b/src/caffeine/render/GpuSceneRenderer.cpp @@ -1962,10 +1962,13 @@ std::vector GpuSceneRenderer::gatherMeshDraws( if (const ECS::NaturalFluidComponent* fluid = world.get(entity)) { if (fluid->enabled) { - if (fluid->mode != static_cast(ECS::NaturalFluidMode::FluidVolume)) { - // Water surface: physically-based transparent liquid with a - // sharp clearcoat so reflections read as water even before a - // dedicated water shader exists. + if (fluid->mode != static_cast(ECS::NaturalFluidMode::FluidVolume) && + draw.hasAuthoredMaterial) { + // The entity has its own material (a .mat, for example one written by the + // Water Generator): it is the water's material, as for any mesh. + } else if (fluid->mode != static_cast(ECS::NaturalFluidMode::FluidVolume)) { + // No material assigned: a physically-based transparent liquid with a sharp + // clearcoat, so reflections read as water. const Vec3 albedo = srgbToLinear(Vec3(fluid->albedoR, fluid->albedoG, fluid->albedoB)); draw.albedo = Vec4(albedo.x, albedo.y, albedo.z, From 06cf38b2b740a4f79de67224e8f5ee8451abd275 Mon Sep 17 00:00:00 2001 From: lyeepedro Date: Wed, 18 Nov 2026 12:37:04 +0000 Subject: [PATCH 2/3] Nature and Water: materials are nodes and real project assets Golden rule: nothing is hidden in a menu. Library, texture and colour nodes are moulds; applying a preset or placing writes the PNG and .mat into the project and turns the node into Your Material pointing at it. Leaf size is a percentage of tree height; the leaf atlas layout travels with the material. Water requires a Water Material that becomes water/.mat and is never overwritten. Co-Authored-By: Claude Sonnet 5.5 --- .../ui/src/uikit/components/node_canvas.rs | 4 + doppio/crates/ui/src/uikit/nature/graph.rs | 25 ++ doppio/crates/ui/src/uikit/nature/mesh.rs | 6 +- doppio/crates/ui/src/uikit/nature/mod.rs | 52 +++- doppio/crates/ui/src/uikit/nature/ops.rs | 291 +++++++++++++----- doppio/crates/ui/src/uikit/nature/tests.rs | 158 ++++++++-- .../ui/src/uikit/panels/nature_generator.rs | 22 +- .../ui/src/uikit/panels/water_generator.rs | 21 ++ doppio/crates/ui/src/uikit/theme.rs | 1 + doppio/crates/ui/src/uikit/water/mod.rs | 96 +++++- doppio/crates/ui/src/uikit/water/tests.rs | 43 +++ doppio/crates/ui/src/windows/main.rs | 8 +- .../crates/ui/src/windows/main/naturegen.rs | 102 +++++- doppio/crates/ui/src/windows/main/tests.rs | 154 +++++++-- doppio/crates/ui/src/windows/main/watergen.rs | 114 ++++++- doppio/docs/nature-generator-guide.md | 47 ++- doppio/docs/water-generator-guide.md | 24 +- 17 files changed, 980 insertions(+), 188 deletions(-) diff --git a/doppio/crates/ui/src/uikit/components/node_canvas.rs b/doppio/crates/ui/src/uikit/components/node_canvas.rs index 38e856d..f042deb 100644 --- a/doppio/crates/ui/src/uikit/components/node_canvas.rs +++ b/doppio/crates/ui/src/uikit/components/node_canvas.rs @@ -32,6 +32,8 @@ pub enum PortKind { Look, /// Terrain Generator: a field (a grid of 0-1 values: a height map or a mask). Height, + /// Nature Generator: a material (library, card, colour or your own asset). + Material, } impl PortKind { @@ -46,6 +48,7 @@ impl PortKind { PortKind::Waves => theme::ICON_CYAN, PortKind::Look => theme::WARNING, PortKind::Height => theme::ICON_ORANGE, + PortKind::Material => theme::ICON_PINK, } } @@ -60,6 +63,7 @@ impl PortKind { PortKind::Waves => "waves", PortKind::Look => "look", PortKind::Height => "field", + PortKind::Material => "material", } } diff --git a/doppio/crates/ui/src/uikit/nature/graph.rs b/doppio/crates/ui/src/uikit/nature/graph.rs index 8618822..f1636d3 100644 --- a/doppio/crates/ui/src/uikit/nature/graph.rs +++ b/doppio/crates/ui/src/uikit/nature/graph.rs @@ -28,6 +28,8 @@ pub enum Kind { Mesh, Skeleton, Points, + /// A material (library preset, card, solid colour or one of your own assets). + Material, } impl Kind { @@ -36,6 +38,7 @@ impl Kind { Kind::Mesh => "mesh", Kind::Skeleton => "skeleton", Kind::Points => "points", + Kind::Material => "material", } } } @@ -70,6 +73,7 @@ pub enum Value { Mesh(Part), Skeleton(super::tree::Skeleton), Points(Vec), + Material(MaterialSpec), } /// What an op sees: its parameters, its inputs and the quality level. @@ -104,6 +108,12 @@ impl<'a> Args<'a> { _ => None, } } + pub fn material(&self, i: usize) -> Option<&'a MaterialSpec> { + match self.inputs.get(i).copied().flatten() { + Some(Value::Material(m)) => Some(m), + _ => None, + } + } pub fn points(&self, i: usize) -> Option<&'a Vec> { match self.inputs.get(i).copied().flatten() { Some(Value::Points(p)) => Some(p), @@ -364,6 +374,21 @@ impl NatureGraph { if part.is_empty() { continue; } + // Nothing is chosen inside a Part: the material has to arrive on its port (a generated + // surface counts, it brings its own). + if self.node(link.from).is_some_and(|n| n.op == "part") && part.surface.is_none() { + let wired = self + .links + .iter() + .find(|l| l.to == link.from && l.input == 1) + .and_then(|l| memo.get(&l.from).and_then(|v| v.get(l.output))); + if !matches!(wired, Some(Value::Material(_))) { + return Err(format!( + "The {} part has no material: wire a material node (Materials category) into its Material port", + part.name + )); + } + } match model .parts .iter_mut() diff --git a/doppio/crates/ui/src/uikit/nature/mesh.rs b/doppio/crates/ui/src/uikit/nature/mesh.rs index 31a1223..a7c9ba2 100644 --- a/doppio/crates/ui/src/uikit/nature/mesh.rs +++ b/doppio/crates/ui/src/uikit/nature/mesh.rs @@ -51,10 +51,10 @@ pub enum MaterialSpec { /// A plain colour and roughness (stylised models, flower centres). Solid { rgb: [f32; 3], roughness: f32 }, /// One of **your own** materials: an asset path to an existing `.mat` (used as it is). - Project(String), + Project(String, (u32, u32)), /// One of your own images with transparency (a PNG leaf, petal, grass blade...): turned into a /// cut-out card material. - ProjectTexture(String), + ProjectTexture(String, (u32, u32)), } impl MaterialSpec { @@ -66,7 +66,7 @@ impl MaterialSpec { .chars() .map(|c| if c.is_ascii_alphanumeric() { c } else { '_' }) .collect(), - MaterialSpec::Project(path) | MaterialSpec::ProjectTexture(path) => { + MaterialSpec::Project(path, _) | MaterialSpec::ProjectTexture(path, _) => { let stem = std::path::Path::new(path) .file_stem() .and_then(|s| s.to_str()) diff --git a/doppio/crates/ui/src/uikit/nature/mod.rs b/doppio/crates/ui/src/uikit/nature/mod.rs index db873fc..f855406 100644 --- a/doppio/crates/ui/src/uikit/nature/mod.rs +++ b/doppio/crates/ui/src/uikit/nature/mod.rs @@ -149,17 +149,48 @@ fn chain(g: &mut NatureGraph, ids: &[NodeId]) { } } -fn part(g: &mut NatureGraph, col: f32, row: f32, name: &str, material: &str) -> NodeId { +/// Adds the node that gives a material from a table label (a library preset, a card texture or a solid +/// colour) and returns it. Presets use this so every part has an explicit material node. +fn material_node(g: &mut NatureGraph, label: &str, col: f32, row: f32) -> NodeId { + if let Some(i) = ops::LIBRARY_LABELS.iter().position(|l| *l == label) { + return g.add_with("mat_library", at(col, row), &[("preset", i as f32)]); + } + if let Some(i) = ops::CARD_LABELS.iter().position(|l| *l == label) { + return g.add_with("mat_cards", at(col, row), &[("card", i as f32)]); + } + let rgb = ops::solid_rgb(label); g.add_with( - "part", + "mat_solid", at(col, row), - &[ - ("name", ops::part_name_index(name)), - ("material", ops::material_index(material)), - ], + &[("r", rgb[0]), ("g", rgb[1]), ("b", rgb[2])], ) } +/// A part with its own material node wired in. +fn part(g: &mut NatureGraph, col: f32, row: f32, name: &str, material: &str) -> NodeId { + let p = g.add_with( + "part", + at(col, row), + &[("name", ops::part_name_index(name))], + ); + let m = material_node(g, material, col, row - 0.75); + assert!(g.connect(m, 0, p, 1), "material cannot feed the part"); + p +} + +/// Feeds the texture wired into a part to the Leaves node too, so it knows the atlas layout. +fn share_texture(g: &mut NatureGraph, leaves: NodeId, leaf_part: NodeId) { + let Some(link) = g + .links + .iter() + .find(|l| l.to == leaf_part && l.input == 1) + .copied() + else { + return; + }; + assert!(g.connect(link.from, 0, leaves, 1)); +} + fn finish(g: &mut NatureGraph, col: f32, parts: &[NodeId]) { let out = g.add("output", at(col, 1.0)); for (i, p) in parts.iter().enumerate() { @@ -429,12 +460,13 @@ fn tree( at(1.0, 2.0), &[ ("density", leaf_density), - ("size", leaf_size), + // Given in metres by the recipes; the node takes a share of the tree's height. + ("size", leaf_size / height * 100.0), ("seed", seed), - ("shapes", if foliage.contains("Mix") { 1.0 } else { 0.0 }), ], ); let leaf_part = part(&mut g, 2.0, 2.0, "leaves", foliage); + share_texture(&mut g, leaves, leaf_part); chain(&mut g, &[grow, leaves, leaf_part]); parts.push(leaf_part); } @@ -462,12 +494,12 @@ fn ancient_oak() -> NatureGraph { at(2.0, 2.0), &[ ("density", 14.0), - ("size", 0.75), + ("size", 0.75 / 7.5 * 100.0), ("seed", 12.0), - ("shapes", 1.0), ], ); let leaf_part = part(&mut g, 3.0, 2.0, "leaves", "Leaves · Broadleaf Mix (atlas)"); + share_texture(&mut g, leaves, leaf_part); assert!(g.connect(grow, 0, leaves, 0)); assert!(g.connect(leaves, 0, leaf_part, 0)); // Moss on the trunk and the roots (only the up-facing, lower parts get it). diff --git a/doppio/crates/ui/src/uikit/nature/ops.rs b/doppio/crates/ui/src/uikit/nature/ops.rs index c7c0d3e..5f2c5fd 100644 --- a/doppio/crates/ui/src/uikit/nature/ops.rs +++ b/doppio/crates/ui/src/uikit/nature/ops.rs @@ -20,9 +20,6 @@ enum Source { Library(&'static str), Cards(&'static str), Solid([f32; 3]), - Custom, - ProjectMaterial, - ProjectTexture, } /// `(label, source, stylised colour)`. @@ -132,17 +129,6 @@ const MATERIALS: &[(&str, Source, [f32; 3])] = &[ Source::Solid([0.95, 0.75, 0.1]), [0.95, 0.75, 0.1], ), - ("Solid · Custom colour", Source::Custom, [0.5, 0.5, 0.5]), - ( - "Your material (.mat)", - Source::ProjectMaterial, - [0.5, 0.5, 0.5], - ), - ( - "Your texture (cut-out PNG)", - Source::ProjectTexture, - [0.3, 0.5, 0.2], - ), ( "Leaves · Broadleaf Mix (atlas)", Source::Cards("Atlas · Broadleaf"), @@ -177,9 +163,6 @@ const MATERIAL_LABELS: &[&str] = &[ "Solid · Brown", "Solid · Grey", "Solid · Yellow", - "Solid · Custom colour", - "Your material (.mat)", - "Your texture (cut-out PNG)", "Leaves · Broadleaf Mix (atlas)", "Leaves · Autumn Mix (atlas)", ]; @@ -198,45 +181,76 @@ pub fn part_name_index(name: &str) -> f32 { PART_NAMES.iter().position(|n| *n == name).unwrap_or(0) as f32 } -/// Index of a material label (used by presets). -pub fn material_index(label: &str) -> f32 { - MATERIALS.iter().position(|m| m.0 == label).unwrap_or(0) as f32 -} - const PART_NAMES: &[&str] = &[ "trunk", "branches", "roots", "leaves", "rock", "moss", "stem", "petals", "center", "blades", "fronds", "ground", "body", ]; -/// The material a Part node gives its mesh at a quality level. -fn material_for( - index: usize, - rgb: [f32; 3], - roughness: f32, - path: &str, - quality: super::Quality, -) -> MaterialSpec { - let (_, source, stylised) = MATERIALS[index.min(MATERIALS.len() - 1)]; - let stylized = quality == super::Quality::Stylized; +/// The material for a table label at a quality level (low poly falls back to a solid colour). +pub fn spec_for_label(label: &str, quality: super::Quality) -> MaterialSpec { + let (_, source, stylised) = MATERIALS + .iter() + .find(|m| m.0 == label) + .copied() + .unwrap_or(MATERIALS[0]); match source { - Source::Library(_) | Source::Cards(_) if stylized => MaterialSpec::Solid { - rgb: stylised, - roughness: 0.85, - }, + Source::Library(_) | Source::Cards(_) if quality == super::Quality::Stylized => { + MaterialSpec::Solid { + rgb: stylised, + roughness: 0.85, + } + } Source::Library(name) => MaterialSpec::Preset(name), Source::Cards(name) => MaterialSpec::Cards(name), Source::Solid(rgb) => MaterialSpec::Solid { rgb, roughness: 0.8, }, - Source::Custom => MaterialSpec::Solid { rgb, roughness }, - // Your own assets are always used as they are, whatever the quality. - Source::ProjectMaterial if !path.is_empty() => MaterialSpec::Project(path.to_owned()), - Source::ProjectTexture if !path.is_empty() => MaterialSpec::ProjectTexture(path.to_owned()), - Source::ProjectMaterial | Source::ProjectTexture => MaterialSpec::Solid { - rgb: stylised, - roughness: 0.85, - }, + } +} + +/// The colour of a `Solid · ...` label. +pub fn solid_rgb(label: &str) -> [f32; 3] { + MATERIALS + .iter() + .find_map(|m| match m.1 { + Source::Solid(rgb) if m.0 == label => Some(rgb), + _ => None, + }) + .unwrap_or([0.4, 0.4, 0.4]) +} + +/// Labels the material nodes offer, by kind. +pub const LIBRARY_LABELS: &[&str] = &[ + "Rock · Cliff Granite", + "Rock · Basalt", + "Rock · Limestone", + "Rock · Sandstone", + "Rock · Mossy Boulder", + "Rock · Lichen Granite", + "Bark · Oak", + "Bark · Pine", + "Bark · Birch", + "Ground · Lawn Grass", + "Ground · Pine Needles", +]; +pub const CARD_LABELS: &[&str] = &[ + "Leaves · Green", + "Leaves · Autumn", + "Leaves · Willow (narrow)", + "Leaves · Broadleaf Mix (atlas)", + "Leaves · Autumn Mix (atlas)", + "Petals · Pink", + "Petals · White", + "Petals · Yellow", +]; + +/// Atlas columns and rows of a card material (1 x 1 = one picture). +pub fn atlas_of(spec: &MaterialSpec) -> (u32, u32) { + match spec { + MaterialSpec::Cards(name) if name.starts_with("Atlas") => (4, 2), + MaterialSpec::Project(_, atlas) | MaterialSpec::ProjectTexture(_, atlas) => *atlas, + _ => (1, 1), } } @@ -720,19 +734,17 @@ fn eval_tubes(a: &Args) -> Vec { mesh_out(part) } +const LEAVES_IN: &[PortDef] = &[ + port("Skeleton", Kind::Skeleton), + port("Texture", Kind::Material), +]; const LEAVES_P: &[crate::uikit::procedural::ParamSpec] = &[ choice("style", "Style", &["Cards", "Blobs"], 0), float("density", "Leaves per metre", 0.0, 30.0, 12.0, 0.5), - float("size", "Leaf size (m)", 0.05, 3.0, 0.7, 0.01), + float("size", "Leaf size (% of tree height)", 0.5, 40.0, 7.0, 0.1), float("inner", "Inner limbs", 0.0, 1.0, 0.45, 0.01), int("budget", "Triangle budget", 200, 30000, 9000), int("seed", "Seed", 0, 9999, 1), - choice( - "shapes", - "Leaf shapes", - &["Single leaf", "Atlas 4x2 (8 shapes)"], - 0, - ), float("fold", "Fold along the midrib", 0.0, 1.0, 0.35, 0.01), float("droop", "Droop", 0.0, 1.0, 0.3, 0.01), ]; @@ -742,10 +754,12 @@ fn eval_leaves(a: &Args) -> Vec { return mesh_out(empty()); }; let seed = a.u(5).wrapping_add(a.salt); + // The leaf size is a share of the tree's height, so it scales with the tree. + let leaf = a.f(2) / 100.0 * skeleton.height.max(0.1); if a.u(0) == 1 || a.stylized() { let mut part = tree::leaf_blobs( skeleton, - a.f(2).max(if a.stylized() { 0.9 } else { 0.0 }), + leaf.max(if a.stylized() { 0.9 } else { 0.0 }), 1, seed, ); @@ -757,17 +771,19 @@ fn eval_leaves(a: &Args) -> Vec { super::Quality::Balanced => 2, super::Quality::Detailed => 4, }; + // The texture wired into the node tells it how many leaf shapes its atlas holds. + let atlas = a.material(1).map_or((1, 1), atlas_of); mesh_out(tree::leaf_cards( skeleton, tree::LeafCards { // Atlas leaves are drawn smaller and sparser per card: more of them fill the crown. - density: a.q(a.f(1)) * if a.u(6) == 1 { 1.5 } else { 1.0 }, - size: a.f(2), + density: a.q(a.f(1)) * if atlas != (1, 1) { 1.5 } else { 1.0 }, + size: leaf, inner_share: a.f(3), max_triangles: a.u(4) as usize, - atlas: if a.u(6) == 1 { (4, 2) } else { (1, 1) }, - fold: a.f(7), - droop: a.f(8), + atlas, + fold: a.f(6), + droop: a.f(7), rows, }, seed, @@ -1024,18 +1040,11 @@ fn eval_instance(a: &Args) -> Vec { const PART_IN: &[PortDef] = &[port("Mesh", Kind::Mesh)]; const MESH_OUT: &[PortDef] = &[port("Mesh", Kind::Mesh)]; -const PART_STRINGS: &[StringSpec] = &[StringSpec { - key: "path", - label: "Your asset (.mat or .png)", -}]; -const PART_P: &[crate::uikit::procedural::ParamSpec] = &[ - choice("name", "Part name", PART_NAMES, 0), - choice("material", "Material", MATERIAL_LABELS, 6), - float("r", "Colour R", 0.0, 1.0, 0.5, 0.01), - float("g", "Colour G", 0.0, 1.0, 0.5, 0.01), - float("b", "Colour B", 0.0, 1.0, 0.5, 0.01), - float("roughness", "Roughness", 0.0, 1.0, 0.8, 0.01), -]; +const MAT_OUT: &[PortDef] = &[port("Material", Kind::Material)]; +/// A part is a mesh **and** its material: both are wired in, nothing is chosen inside the node. +const PART_NODE_IN: &[PortDef] = &[port("Mesh", Kind::Mesh), port("Material", Kind::Material)]; +const PART_P: &[crate::uikit::procedural::ParamSpec] = + &[choice("name", "Part name", PART_NAMES, 0)]; fn eval_part(a: &Args) -> Vec { let Some(mesh) = a.mesh(0) else { @@ -1043,13 +1052,93 @@ fn eval_part(a: &Args) -> Vec { }; let mut part = mesh.clone(); part.name = PART_NAMES[a.u(0).min(PART_NAMES.len() as u32 - 1) as usize].to_owned(); - let rgb = [a.f(2), a.f(3), a.f(4)]; - let path = a.strings.first().map(String::as_str).unwrap_or(""); - part.material = material_for(a.u(1) as usize, rgb, a.f(5), path, a.quality); - part.preview = preview_colour(&part.material, part.preview); + // The material arrives on its port; a generated surface (Rock Surface) brings its own. + if let Some(material) = a.material(1) { + part.material = material.clone(); + part.preview = preview_colour(&part.material, part.preview); + } mesh_out(part) } +// ------------------------------------------------------------ material nodes + +const LIBRARY_P: &[crate::uikit::procedural::ParamSpec] = + &[choice("preset", "Material", LIBRARY_LABELS, 6)]; +fn eval_mat_library(a: &Args) -> Vec { + let label = LIBRARY_LABELS[(a.u(0) as usize).min(LIBRARY_LABELS.len() - 1)]; + vec![Value::Material(spec_for_label(label, a.quality))] +} + +const CARDS_P: &[crate::uikit::procedural::ParamSpec] = + &[choice("card", "Texture", CARD_LABELS, 0)]; +fn eval_mat_cards(a: &Args) -> Vec { + let label = CARD_LABELS[(a.u(0) as usize).min(CARD_LABELS.len() - 1)]; + vec![Value::Material(spec_for_label(label, a.quality))] +} + +const SOLID_P: &[crate::uikit::procedural::ParamSpec] = &[ + float("r", "Red", 0.0, 1.0, 0.3, 0.01), + float("g", "Green", 0.0, 1.0, 0.45, 0.01), + float("b", "Blue", 0.0, 1.0, 0.2, 0.01), + float("roughness", "Roughness", 0.0, 1.0, 0.8, 0.01), +]; +fn eval_mat_solid(a: &Args) -> Vec { + vec![Value::Material(MaterialSpec::Solid { + rgb: [a.f(0), a.f(1), a.f(2)], + roughness: a.f(3), + })] +} + +/// Leaf shapes across and down the picture of your material (1 x 1 = one picture). +const ATLAS_P: &[crate::uikit::procedural::ParamSpec] = &[ + float("columns", "Shapes across", 1.0, 8.0, 1.0, 1.0), + float("rows", "Shapes down", 1.0, 8.0, 1.0, 1.0), +]; +fn atlas_args(a: &Args) -> (u32, u32) { + ( + a.f(0).round().max(1.0) as u32, + a.f(1).round().max(1.0) as u32, + ) +} + +const PROJECT_MAT_STRINGS: &[StringSpec] = &[StringSpec { + key: "path", + label: "Your material (.mat)", +}]; +const PROJECT_TEX_STRINGS: &[StringSpec] = &[StringSpec { + key: "path", + label: "Your image (cut-out PNG)", +}]; +/// Your own `.mat`, used exactly as it is. With no path it gives no material (the Part reports it). +fn eval_mat_project(a: &Args) -> Vec { + match a + .strings + .first() + .map(String::as_str) + .filter(|p| !p.is_empty()) + { + Some(path) => vec![Value::Material(MaterialSpec::Project( + path.to_owned(), + atlas_args(a), + ))], + None => Vec::new(), + } +} +fn eval_mat_texture(a: &Args) -> Vec { + match a + .strings + .first() + .map(String::as_str) + .filter(|p| !p.is_empty()) + { + Some(path) => vec![Value::Material(MaterialSpec::ProjectTexture( + path.to_owned(), + atlas_args(a), + ))], + None => Vec::new(), + } +} + const OUTPUT_IN: &[PortDef] = &[ port("Part 1", Kind::Mesh), port("Part 2", Kind::Mesh), @@ -1085,7 +1174,8 @@ macro_rules! node { }; } -pub const CATEGORIES: [&str; 8] = [ +pub const CATEGORIES: [&str; 9] = [ + "Materials", "Surface", "Shapes", "Modifiers", @@ -1228,7 +1318,7 @@ pub static NODES: &[NodeDef] = &[ "leaves", "Leaves", "Trees", - SKEL_IN, + LEAVES_IN, MESH_OUT, LEAVES_P, eval_leaves @@ -1292,12 +1382,59 @@ pub static NODES: &[NodeDef] = &[ id: "part", title: "Part", category: "Output", - inputs: PART_IN, + inputs: PART_NODE_IN, outputs: MESH_OUT, params: PART_P, - strings: PART_STRINGS, + strings: NO_STRINGS, eval: eval_part, }, + node!( + "mat_library", + "Library Material", + "Materials", + NONE, + MAT_OUT, + LIBRARY_P, + eval_mat_library + ), + node!( + "mat_cards", + "Leaf / Petal Texture", + "Materials", + NONE, + MAT_OUT, + CARDS_P, + eval_mat_cards + ), + node!( + "mat_solid", + "Solid Colour", + "Materials", + NONE, + MAT_OUT, + SOLID_P, + eval_mat_solid + ), + NodeDef { + id: "mat_project", + title: "Your Material (.mat)", + category: "Materials", + inputs: NONE, + outputs: MAT_OUT, + params: ATLAS_P, + strings: PROJECT_MAT_STRINGS, + eval: eval_mat_project, + }, + NodeDef { + id: "mat_texture", + title: "Your Texture (PNG)", + category: "Materials", + inputs: NONE, + outputs: MAT_OUT, + params: ATLAS_P, + strings: PROJECT_TEX_STRINGS, + eval: eval_mat_texture, + }, node!( "output", "Output", diff --git a/doppio/crates/ui/src/uikit/nature/tests.rs b/doppio/crates/ui/src/uikit/nature/tests.rs index 3ef5bbb..caf1276 100644 --- a/doppio/crates/ui/src/uikit/nature/tests.rs +++ b/doppio/crates/ui/src/uikit/nature/tests.rs @@ -242,17 +242,17 @@ fn graphs_round_trip_through_text_including_your_own_assets() { // A part that uses one of your own materials keeps the path (with spaces) through save and load. let mut graph = preset("Boulder").graph(); let part_id = graph.nodes.iter().find(|n| n.op == "part").unwrap().id; - graph.set( + swap_material( + &mut graph, part_id, - "material", - ops::material_index("Your material (.mat)"), + "mat_project", + "my project/materials/Wet Moss.mat", ); - graph.set_string(part_id, 0, "my project/materials/Wet Moss.mat".to_owned()); let (_, back, _) = from_text(&to_text("x", &graph, Quality::Balanced)).unwrap(); let model = back.build(Quality::Stylized).unwrap(); assert_eq!( model.parts[0].material, - MaterialSpec::Project("my project/materials/Wet Moss.mat".to_owned()), + MaterialSpec::Project("my project/materials/Wet Moss.mat".to_owned(), (1, 1)), "your assets stay as they are, even stylised" ); assert!(from_text("CAFMGRAPH2\n").is_none()); @@ -262,23 +262,31 @@ fn graphs_round_trip_through_text_including_your_own_assets() { fn your_own_textures_become_cutout_card_parts() { let mut graph = preset("Grass Clump").graph(); let part_id = graph.nodes.iter().find(|n| n.op == "part").unwrap().id; - graph.set( - part_id, - "material", - ops::material_index("Your texture (cut-out PNG)"), - ); - graph.set_string(part_id, 0, "textures/my_grass.png".to_owned()); + let node = swap_material(&mut graph, part_id, "mat_texture", "textures/my_grass.png"); let model = graph.build(Quality::Balanced).unwrap(); assert_eq!( model.parts[0].material, - MaterialSpec::ProjectTexture("textures/my_grass.png".to_owned()) + MaterialSpec::ProjectTexture("textures/my_grass.png".to_owned(), (1, 1)) ); - // Without a path it falls back to a plain colour instead of failing. - graph.set_string(part_id, 0, String::new()); - assert!(matches!( - graph.build(Quality::Balanced).unwrap().parts[0].material, - MaterialSpec::Solid { .. } - )); + // Without a path there is no material, and the part says so instead of guessing one. + graph.set_string(node, 0, String::new()); + let error = graph.build(Quality::Balanced).unwrap_err(); + assert!(error.contains("no material"), "{error}"); +} + +/// Replaces the material node feeding a part with a new one of `op` holding `path`. +fn swap_material(graph: &mut NatureGraph, part: NodeId, op: &'static str, path: &str) -> NodeId { + let old = graph + .links + .iter() + .find(|l| l.to == part && l.input == 1) + .map(|l| l.from) + .expect("the part has a material node"); + graph.remove(old); + let node = graph.add(op, Point::new(0.0, 0.0)); + graph.set_string(node, 0, path.to_owned()); + assert!(graph.connect(node, 0, part, 1)); + node } #[test] @@ -340,11 +348,20 @@ fn nodes_can_be_mixed_freely() { let part = g.add_with( "part", Point::new(0.0, 0.0), - &[ - ("name", ops::part_name_index("rock")), - ("material", ops::material_index("Bark · Oak")), - ], + &[("name", ops::part_name_index("rock"))], + ); + let bark = g.add_with( + "mat_library", + Point::new(0.0, 0.0), + &[( + "preset", + ops::LIBRARY_LABELS + .iter() + .position(|l| *l == "Bark · Oak") + .unwrap() as f32, + )], ); + assert!(g.connect(bark, 0, part, 1)); let out = g.add("output", Point::new(0.0, 0.0)); assert!( g.connect(ico, 0, lump, 0) @@ -496,10 +513,15 @@ fn baked_masks_and_rock_surface_describe_the_geometry() { fn leaf_atlas_gives_varied_folded_drooping_leaves() { use super::tree; let graph = preset("Oak").graph(); - assert!(graph - .nodes + // The texture wired into the Leaves node is the atlas. + let leaves_node = graph.nodes.iter().find(|n| n.op == "leaves").unwrap().id; + let texture = graph + .links .iter() - .any(|n| n.op == "leaves" && graph.get(n.id, "shapes") == Some(1.0))); + .find(|l| l.to == leaves_node && l.input == 1) + .unwrap() + .from; + assert_eq!(graph.node(texture).unwrap().op, "mat_cards"); let model = graph.build(Quality::Balanced).unwrap(); let leaves = model .parts @@ -558,3 +580,89 @@ fn leaf_atlas_gives_varied_folded_drooping_leaves() { assert_eq!(seen.len(), 8, "every cell is a different leaf"); assert!(crate::uikit::texture_graph::atlas("Atlas · Nothing").is_none()); } + +#[test] +fn nothing_is_hidden_inside_a_part_every_material_is_a_node() { + for p in presets() { + let graph = p.graph(); + for part in graph.nodes.iter().filter(|n| n.op == "part") { + let wired = graph.links.iter().find(|l| l.to == part.id && l.input == 1); + let source = wired.and_then(|l| graph.node(l.from)); + assert!( + source.is_some_and(|n| n.def().category == "Materials") + || preset_has_surface(&graph), + "{}: a part without a material node", + p.name + ); + } + } + // A part with nothing wired in refuses to build and names the part. + let mut g = preset("Oak").graph(); + let trunk = g + .nodes + .iter() + .find(|n| n.op == "part" && g.get(n.id, "name") == Some(ops::part_name_index("trunk"))) + .unwrap() + .id; + let material = g + .links + .iter() + .find(|l| l.to == trunk && l.input == 1) + .unwrap() + .from; + g.remove(material); + let error = g.build(Quality::Balanced).unwrap_err(); + assert!(error.contains("trunk part has no material"), "{error}"); +} + +fn preset_has_surface(graph: &NatureGraph) -> bool { + graph.nodes.iter().any(|n| n.op == "surface") +} + +#[test] +fn leaf_size_scales_with_the_tree_and_the_texture_sets_the_atlas() { + let mut graph = preset("Oak").graph(); + let size_of = |g: &NatureGraph| { + let model = g.build(Quality::Balanced).unwrap(); + let leaves = model.parts.iter().find(|p| p.name == "leaves").unwrap(); + let (lo, hi) = leaves.bounds(); + ((hi[0] - lo[0]).max(hi[2] - lo[2]), leaves.triangle_count()) + }; + let leaves = graph.nodes.iter().find(|n| n.op == "leaves").unwrap().id; + let (_, _) = size_of(&graph); + // A leaf is a share of the tree: tripling the share makes each leaf (and the crown) larger. + let base = graph.get(leaves, "size").unwrap(); + assert!( + base > 1.0 && base < 15.0, + "a sensible default share: {base} %" + ); + let height_of = |g: &NatureGraph| { + let grow = g.nodes.iter().find(|n| n.op == "grow").unwrap().id; + match g.evaluate(grow, Quality::Balanced).unwrap().remove(0) { + super::graph::Value::Skeleton(s) => s.height, + _ => unreachable!(), + } + }; + let tall = height_of(&graph); + graph.set(leaves, "size", base * 3.0); + let bigger = size_of(&graph).0; + graph.set(leaves, "size", base); + assert!(bigger > size_of(&graph).0); + assert!(tall > 1.0); + // The Leaves node reads the atlas from the texture wired into it. + let texture = graph + .links + .iter() + .find(|l| l.to == leaves && l.input == 1) + .map(|l| l.from) + .unwrap(); + assert_eq!(graph.node(texture).unwrap().op, "mat_cards"); + let triangles = |g: &NatureGraph| size_of(g).1; + let with_atlas = triangles(&graph); + let single = graph.nodes.iter().find(|n| n.op == "mat_cards").unwrap().id; + graph.set(single, "card", 0.0); // a single leaf picture + assert!( + triangles(&graph) < with_atlas, + "single-leaf cards are fewer than atlas cards" + ); +} diff --git a/doppio/crates/ui/src/uikit/panels/nature_generator.rs b/doppio/crates/ui/src/uikit/panels/nature_generator.rs index f65e89e..82ee3b0 100644 --- a/doppio/crates/ui/src/uikit/panels/nature_generator.rs +++ b/doppio/crates/ui/src/uikit/panels/nature_generator.rs @@ -95,6 +95,7 @@ fn accent(category: &str) -> iced::Color { "Trees" => theme::SUCCESS, "Plants" => theme::ICON_TEAL, "Scatter" => theme::ICON_ORANGE, + "Materials" => theme::ICON_PINK, "Combine" => theme::TEXT_MUTED, _ => theme::WARNING, } @@ -105,6 +106,7 @@ fn port_kind(kind: Kind) -> node_canvas::PortKind { Kind::Mesh => node_canvas::PortKind::Mesh, Kind::Skeleton => node_canvas::PortKind::Skeleton, Kind::Points => node_canvas::PortKind::Points, + Kind::Material => node_canvas::PortKind::Material, } } @@ -478,15 +480,7 @@ fn properties<'a, Message: Clone + 'a>( .size(8) .color(theme::TEXT_MUTED), ); - let material_choice = node.op == "part"; for (index, spec) in def.params.iter().enumerate() { - // The custom colour only matters for "Solid · Custom colour". - if material_choice - && matches!(spec.key, "r" | "g" | "b" | "roughness") - && node.params[1].round() as usize != 21 - { - continue; - } let value = node.params[index]; let param_emit = emit.clone(); match spec.kind { @@ -530,13 +524,11 @@ fn properties<'a, Message: Clone + 'a>( } } } - // The parts material choice is a plain dropdown in the node table (`material`), so it is above; - // "your own" assets add a picker for the matching project files. - if material_choice { - let choice = node.params[1].round() as usize; - let (options, label): (&[String], &str) = match choice { - 22 => (&view.project_materials, "Your .mat"), - 23 => (&view.project_textures, "Your image"), + // Material nodes that point at your own project assets list the matching files. + { + let (options, label): (&[String], &str) = match node.op { + "mat_project" => (&view.project_materials, "Your .mat"), + "mat_texture" => (&view.project_textures, "Your image"), _ => (&[], ""), }; if !label.is_empty() { diff --git a/doppio/crates/ui/src/uikit/panels/water_generator.rs b/doppio/crates/ui/src/uikit/panels/water_generator.rs index dac5373..be429e1 100644 --- a/doppio/crates/ui/src/uikit/panels/water_generator.rs +++ b/doppio/crates/ui/src/uikit/panels/water_generator.rs @@ -44,6 +44,8 @@ pub enum Edit { DeleteNode(NodeId), /// Node, parameter index, value. SetParam(NodeId, usize, f32), + /// Node, string index, text (an asset path). + SetString(NodeId, usize, String), Undo, Redo, Fit, @@ -76,6 +78,7 @@ pub struct View<'a> { pub stats: &'a str, pub status: Option<&'a str>, pub dirty: bool, + pub project_materials: Vec, } fn accent(category: &str) -> iced::Color { @@ -491,6 +494,24 @@ fn properties<'a, Message: Clone + 'a>( } } } + if node.op == "look_asset" { + let current = node.strings.first().cloned().unwrap_or_default(); + let pick_emit = emit.clone(); + body = body.push(dropdown::property( + id::watergen_param("asset"), + "Your .mat", + view.project_materials.clone(), + Some(current.clone()).filter(|c| !c.is_empty()), + move |choice| pick_emit(Edit::SetString(node_id, 0, choice)), + )); + let text_emit = emit.clone(); + body = body.push(text_field::property( + id::watergen_param("asset_path"), + "Path", + ¤t, + move |value| text_emit(Edit::SetString(node_id, 0, value)), + )); + } container(body) .width(Length::Fill) .padding(4) diff --git a/doppio/crates/ui/src/uikit/theme.rs b/doppio/crates/ui/src/uikit/theme.rs index 10c6359..3a6700c 100644 --- a/doppio/crates/ui/src/uikit/theme.rs +++ b/doppio/crates/ui/src/uikit/theme.rs @@ -33,6 +33,7 @@ pub const OVERLAY_SPHERE_EDGE: Color = Color::from_rgba(0.85, 0.88, 1.0, 0.22); pub const OVERLAY_WHITE: Color = Color::from_rgb(1.0, 1.0, 1.0); pub const OVERLAY_PLATE: Color = Color::from_rgba(0.06, 0.07, 0.09, 0.62); pub const ICON_ORANGE: Color = Color::from_rgba8(0xf0, 0x9a, 0x4a, 1.0); +pub const ICON_PINK: Color = Color::from_rgba8(0xe8, 0x7f, 0xb4, 1.0); pub fn background(_theme: &Theme) -> container::Style { container::Style { diff --git a/doppio/crates/ui/src/uikit/water/mod.rs b/doppio/crates/ui/src/uikit/water/mod.rs index 3eab337..449c772 100644 --- a/doppio/crates/ui/src/uikit/water/mod.rs +++ b/doppio/crates/ui/src/uikit/water/mod.rs @@ -41,11 +41,13 @@ const fn port(label: &'static str, kind: Kind) -> PortDef { } /// Colour, clarity and shading of the water. -#[derive(Debug, Clone, Copy, PartialEq)] +#[derive(Debug, Clone, PartialEq)] pub struct Look { pub albedo: [f32; 4], pub roughness: f32, pub foam_threshold: f32, + /// The `.mat` asset the water is drawn with, when the look comes from one. + pub asset: Option, } #[derive(Debug, Clone)] @@ -56,6 +58,7 @@ pub enum Value { pub struct Args<'a> { pub params: &'a [f32], + pub strings: &'a [String], pub inputs: Vec>, } @@ -81,6 +84,8 @@ pub struct NodeDef { pub inputs: &'static [PortDef], pub outputs: &'static [PortDef], pub params: &'static [ParamSpec], + /// Labels of the text fields the node has (asset paths). + pub strings: &'static [&'static str], pub eval: fn(&Args) -> Vec, } @@ -300,10 +305,24 @@ fn eval_look(a: &Args) -> Vec { albedo: [a.f(0), a.f(1), a.f(2), a.f(3)], roughness: a.f(4), foam_threshold: a.f(5), + asset: None, })] } -const OUTPUT_IN: &[PortDef] = &[port("Waves", Kind::Waves), port("Look", Kind::Look)]; +/// Your own `.mat`: the water is drawn with it exactly as it is. +fn eval_look_asset(a: &Args) -> Vec { + match a.strings.first().filter(|p| !p.is_empty()) { + Some(path) => vec![Value::Look(Look { + albedo: [0.05, 0.25, 0.35, 0.85], + roughness: 0.08, + foam_threshold: 0.72, + asset: Some(path.clone()), + })], + None => Vec::new(), + } +} + +const OUTPUT_IN: &[PortDef] = &[port("Waves", Kind::Waves), port("Material", Kind::Look)]; const RESOLUTIONS: &[&str] = &["32", "64", "96", "128", "192", "256"]; const OUTPUT_P: &[ParamSpec] = &[ float("size_x", "Size X (m)", 2.0, 1000.0, 64.0, 1.0), @@ -327,6 +346,7 @@ macro_rules! node { inputs: $in, outputs: $out, params: $params, + strings: &[], eval: $eval, } }; @@ -375,13 +395,23 @@ pub static NODES: &[NodeDef] = &[ ), node!( "look", - "Water Look", + "Water Material", "Look", NONE, LOOK_OUT, LOOK_P, eval_look ), + NodeDef { + id: "look_asset", + title: "Your Water Material (.mat)", + category: "Look", + inputs: NONE, + outputs: LOOK_OUT, + params: &[], + strings: &["Your material (.mat)"], + eval: eval_look_asset, + }, node!( "output", "Output", @@ -404,6 +434,7 @@ pub struct WaterNode { pub id: NodeId, pub op: &'static str, pub params: Vec, + pub strings: Vec, pub position: Point, } @@ -437,6 +468,7 @@ impl WaterGraph { id, op: def.id, params: def.params.iter().map(|p| p.default).collect(), + strings: def.strings.iter().map(|_| String::new()).collect(), position, }); id @@ -487,6 +519,24 @@ impl WaterGraph { self.links.retain(|l| l.from != id && l.to != id); } + pub fn set_string(&mut self, id: NodeId, index: usize, text: String) { + if let Some(slot) = self + .node_mut(id) + .and_then(|node| node.strings.get_mut(index)) + { + *slot = text; + } + } + + /// The `.mat` the water uses, when its material node points at one. + pub fn look_asset(&self) -> Option { + self.nodes + .iter() + .find(|n| n.op == "look_asset") + .and_then(|n| n.strings.first().cloned()) + .filter(|p| !p.is_empty()) + } + pub fn output_node(&self) -> Option { self.nodes.iter().find(|n| n.op == "output").map(|n| n.id) } @@ -555,6 +605,7 @@ impl WaterGraph { .collect(); let values = (def.eval)(&Args { params: &node.params, + strings: &node.strings, inputs, }); stack.pop(); @@ -599,13 +650,15 @@ impl WaterGraph { phase: 0.0, }); } + // Water is nothing without its material: it is wired in, never assumed. let look = match value(1) { - Some(Value::Look(look)) => *look, - _ => Look { - albedo: [0.03, 0.16, 0.30, 0.78], - roughness: 0.05, - foam_threshold: 0.72, - }, + Some(Value::Look(look)) => look.clone(), + _ => { + return Err( + "The water has no material: wire a Water Material node (Look category) into the Output's Material port" + .to_owned(), + ) + } }; let p = &node.params; let resolution = [32u32, 64, 96, 128, 192, 256][(p[4].round().max(0.0) as usize).min(5)]; @@ -660,6 +713,17 @@ impl WaterGraph { for v in &node.params { text.push_str(&format!(" {v}")); } + if !node.strings.is_empty() { + text.push_str(&format!(" {}", node.strings.len())); + for s in &node.strings { + text.push(' '); + if s.is_empty() { + text.push_str("%00"); + } else { + text.push_str(&s.replace('%', "%25").replace(' ', "%20")); + } + } + } text.push('\n'); } for l in &self.links { @@ -691,11 +755,25 @@ impl WaterGraph { *slot = word.parse().ok()?; } } + let mut strings: Vec = + def.strings.iter().map(|_| String::new()).collect(); + if let Some(count) = w.get(6 + n).and_then(|c| c.parse::().ok()) { + for (i, word) in w.get(7 + n..7 + n + count)?.iter().enumerate() { + if let Some(slot) = strings.get_mut(i) { + *slot = if *word == "%00" { + String::new() + } else { + word.replace("%20", " ").replace("%25", "%") + }; + } + } + } graph.next_id = graph.next_id.max(id + 1); graph.nodes.push(WaterNode { id, op: def.id, params, + strings, position, }); } diff --git a/doppio/crates/ui/src/uikit/water/tests.rs b/doppio/crates/ui/src/uikit/water/tests.rs index 4bba021..2f1ba46 100644 --- a/doppio/crates/ui/src/uikit/water/tests.rs +++ b/doppio/crates/ui/src/uikit/water/tests.rs @@ -4,6 +4,13 @@ fn preset(name: &str) -> WaterPreset { presets().into_iter().find(|p| p.name == name).expect(name) } +/// Gives a hand-built graph the Water Material its Output requires. +fn with_material(g: &mut WaterGraph) { + let out = g.output_node().unwrap(); + let look = g.add("look", Point::ORIGIN); + assert!(g.connect(look, 0, out, 1)); +} + fn peak(water: &Water) -> f32 { let mut peak = 0.0f32; for i in 0..60 { @@ -87,6 +94,7 @@ fn wind_raises_taller_longer_waves() { let out = g.add("output", Point::ORIGIN); let w = g.add_with("wind", Point::ORIGIN, &[("wind", wind)]); assert!(g.connect(w, 0, out, 0)); + with_material(&mut g); g.build().unwrap() }; let (calm, gale) = (height(4.0), height(20.0)); @@ -140,6 +148,7 @@ fn merge_keeps_the_strongest_sixteen_and_scale_modifies() { assert!(g.connect(w, 0, merge, i)); } assert!(g.connect(merge, 0, out, 0)); + with_material(&mut g); let water = g.build().unwrap(); assert_eq!(water.waves.len(), MAX_WATER_WAVES); let min = water @@ -213,6 +222,7 @@ fn waves_finer_than_the_mesh_fade_out_instead_of_aliasing() { ], ); assert!(g.connect(rip, 0, out, 0)); + with_material(&mut g); g.build_report().unwrap() }; // 100 m over 96 cells = 1.04 m per cell: 0.3 m ripples cannot be shown. @@ -249,3 +259,36 @@ fn presets_keep_every_wave_their_mesh_can_show() { assert!(dropped <= 1, "{} drops {dropped} waves", p.name); } } + +#[test] +fn water_cannot_exist_without_its_material() { + let mut g = WaterGraph::new(); + let out = g.add("output", Point::ORIGIN); + let wave = g.add("wave", Point::ORIGIN); + assert!(g.connect(wave, 0, out, 0)); + let error = g.build().unwrap_err(); + assert!( + error.contains("no material") && error.contains("Water Material"), + "{error}" + ); + // Wiring the material makes it build, and the colour comes from that node. + let look = g.add_with( + "look", + Point::ORIGIN, + &[("r", 0.1), ("g", 0.6), ("b", 0.4), ("opacity", 0.5)], + ); + assert!(g.connect(look, 0, out, 1)); + let water = g.build().unwrap(); + assert_eq!(water.albedo, [0.1, 0.6, 0.4, 0.5]); + // Every preset wires an explicit Water Material node. + for p in presets() { + let graph = p.graph(); + let output = graph.output_node().unwrap(); + let link = graph + .links + .iter() + .find(|l| l.to == output && l.input == 1) + .expect(p.name); + assert_eq!(graph.node(link.from).unwrap().op, "look", "{}", p.name); + } +} diff --git a/doppio/crates/ui/src/windows/main.rs b/doppio/crates/ui/src/windows/main.rs index 42dfed7..c0c27d0 100644 --- a/doppio/crates/ui/src/windows/main.rs +++ b/doppio/crates/ui/src/windows/main.rs @@ -8522,7 +8522,13 @@ impl App { id::PANE_WATER_GENERATOR, "Water Generator", Some(format!("{} · {}", self.watergen.name, self.watergen.stats)), - water_generator_panel::view(self.watergen.view_state(), Message::WaterGen), + { + let (materials, _) = self.nature_assets(); + water_generator_panel::view( + self.watergen.view_state(materials), + Message::WaterGen, + ) + }, ), PaneKind::TerrainGenerator => ( id::PANE_TERRAIN_GENERATOR, diff --git a/doppio/crates/ui/src/windows/main/naturegen.rs b/doppio/crates/ui/src/windows/main/naturegen.rs index 13a2e33..32e673f 100644 --- a/doppio/crates/ui/src/windows/main/naturegen.rs +++ b/doppio/crates/ui/src/windows/main/naturegen.rs @@ -411,6 +411,11 @@ impl App { self.nature.load(graph.0); self.nature.dirty = true; self.nature.status = None; + // A preset is only a mould: its materials become project assets right away. + if let Err(error) = self.materialize_nature_assets() { + self.nature.status = + Some(format!("Could not write the materials: {error}")); + } let name = self.nature.name.clone(); self.log(LogLevel::Action, format!("Nature preset: {name}")); } @@ -465,6 +470,10 @@ impl App { Some("Open a project first: models are written to its assets folder".to_owned()); return; }; + if let Err(error) = self.materialize_nature_assets() { + self.nature.status = Some(format!("Could not write the materials: {error}")); + return; + } let name = self.nature.name.clone(); let model = match self.nature.graph.build(self.nature.quality) { Ok(model) => model, @@ -560,13 +569,82 @@ impl App { }) } + /// Golden rule: every material in the graph is a real asset. The library, texture and colour + /// nodes are only moulds: this writes each one's picture and `.mat` into the project and turns + /// the node into **Your Material** pointing at them, so nothing is left hidden in the UI and + /// the user can open and change the files (or point the node somewhere else) at will. + pub(super) fn materialize_nature_assets(&mut self) -> Result { + let Some(dir) = self.nature_dir() else { + return Ok(0); + }; + let graph = &self.nature.graph; + let mut jobs: Vec<(NodeId, MaterialSpec)> = Vec::new(); + for node in &graph.nodes { + let spec = match node.op { + "mat_library" | "mat_cards" => { + let (labels, key) = if node.op == "mat_library" { + (nature::ops::LIBRARY_LABELS, "preset") + } else { + (nature::ops::CARD_LABELS, "card") + }; + let i = graph.get(node.id, key).unwrap_or(0.0).max(0.0) as usize; + // The real material, whatever the quality: low poly only changes the model. + nature::ops::spec_for_label( + labels[i.min(labels.len() - 1)], + nature::Quality::Balanced, + ) + } + "mat_solid" => MaterialSpec::Solid { + rgb: [ + graph.get(node.id, "r").unwrap_or(0.4), + graph.get(node.id, "g").unwrap_or(0.4), + graph.get(node.id, "b").unwrap_or(0.4), + ], + roughness: graph.get(node.id, "roughness").unwrap_or(0.8), + }, + _ => continue, + }; + jobs.push((node.id, spec)); + } + let count = jobs.len(); + for (id, spec) in jobs { + let path = self.ensure_nature_material(&spec, &dir)?; + let atlas = nature::ops::atlas_of(&spec); + if let Some(node) = self.nature.graph.node_mut(id) { + node.op = "mat_project"; + node.params = vec![atlas.0 as f32, atlas.1 as f32]; + node.strings = vec![path]; + } + } + if count > 0 { + self.nature.dirty = true; + } + Ok(count) + } + + /// True when a part's material cuts its shape out of a picture (leaves, petals, blades). + fn material_is_cutout(&self, spec: &MaterialSpec) -> bool { + match spec { + MaterialSpec::Cards(_) | MaterialSpec::ProjectTexture(..) => true, + MaterialSpec::Project(path, atlas) => { + *atlas != (1, 1) + || self.asset_root_dir().is_some_and(|root| { + std::fs::read_to_string(root.join(path)) + .map(|text| text.to_lowercase().contains("cutout")) + .unwrap_or(false) + }) + } + _ => false, + } + } + fn ensure_nature_material( &mut self, spec: &MaterialSpec, dir: &Path, ) -> Result { // Your own material is used exactly as it is. - if let MaterialSpec::Project(path) = spec { + if let MaterialSpec::Project(path, _) = spec { return Ok(path.clone()); } let engine = self.engine.as_ref().ok_or("The engine is not available")?; @@ -637,7 +715,7 @@ impl App { material.uv_object_scale = false; } } - MaterialSpec::ProjectTexture(path) => { + MaterialSpec::ProjectTexture(path, _) => { // A cut-out material around your image, referencing it where it is. material.albedo_map = engine .asset_project_path(path) @@ -652,7 +730,7 @@ impl App { material.albedo = [rgb[0], rgb[1], rgb[2], 1.0]; material.roughness = *roughness; } - MaterialSpec::Project(_) => unreachable!("handled above"), + MaterialSpec::Project(..) => unreachable!("handled above"), } if write { engine @@ -791,6 +869,11 @@ impl App { .as_ref() .and_then(|e| e.asset_path("").ok()) .is_some_and(|root| !root.is_empty()); + let cutouts: Vec = model + .parts + .iter() + .map(|part| self.material_is_cutout(&part.material)) + .collect(); let engine = self.engine.as_mut().expect("checked above"); let group = match engine.create_entity(&name) { Ok(id) => id, @@ -801,7 +884,13 @@ impl App { }; let _ = engine.set_position(group, [focus[0], 0.0, focus[2]]); let mut problems = Vec::new(); - for ((part, file), material) in model.parts.iter().zip(files.iter()).zip(materials.iter()) { + for (((part, file), material), cutout) in model + .parts + .iter() + .zip(files.iter()) + .zip(materials.iter()) + .zip(cutouts.iter()) + { let Ok(child) = engine.create_entity(&format!("{name} {}", part.name)) else { continue; }; @@ -838,10 +927,7 @@ impl App { Ok(renderer) => { // Cut-out cards (leaves, petals, blades) would only shadow each other: let the // sun fall through them and keep the shadows for trunks, rocks and moss. - if matches!( - part.material, - MaterialSpec::Cards(_) | MaterialSpec::ProjectTexture(_) - ) { + if *cutout { let _ = set_component_field( engine, child, diff --git a/doppio/crates/ui/src/windows/main/tests.rs b/doppio/crates/ui/src/windows/main/tests.rs index f0af215..cc35ee8 100644 --- a/doppio/crates/ui/src/windows/main/tests.rs +++ b/doppio/crates/ui/src/windows/main/tests.rs @@ -5019,9 +5019,69 @@ fn nature_models_export_and_place_in_the_scene_with_their_own_materials() { std::fs::remove_dir_all(root).ok(); } +/// Swaps the material node feeding `part` for one that points at your own project asset. +fn use_project_asset(harness: &mut Harness, part: u64, op: &'static str, path: &str) { + let graph = &mut harness.app.nature.graph; + let old = graph + .links + .iter() + .find(|l| l.to == part && l.input == 1) + .map(|l| l.from) + .expect("a material node"); + graph.remove(old); + let node = graph.add(op, iced::Point::new(0.0, 0.0)); + graph.set_string(node, 0, path.to_owned()); + assert!(graph.connect(node, 0, part, 1)); + harness.app.nature.refresh(); +} + +#[test] +fn nature_presets_write_their_materials_as_project_assets() { + use crate::uikit::panels::nature_generator as ng; + let Some(mut harness) = engine_harness() else { + return; + }; + let root = test_temp_root("nature-materialized"); + std::fs::create_dir_all(&root).expect("dir"); + harness.app.asset_root_override = Some(root.clone()); + let oak = harness + .app() + .nature + .presets + .iter() + .position(|p| p.name == "Oak") + .unwrap(); + harness.dispatch(Message::NatureGen(ng::Edit::ApplyPreset(oak))); + let graph = &harness.app().nature.graph; + // Nothing is left as a hidden built-in: every material node points at a file in the project. + assert!(!graph + .nodes + .iter() + .any(|n| matches!(n.op, "mat_library" | "mat_cards" | "mat_solid"))); + let materials: Vec<_> = graph + .nodes + .iter() + .filter(|n| n.op == "mat_project") + .collect(); + assert!(materials.len() >= 2, "trunk and leaves both have one"); + for node in &materials { + assert!(root.join(&node.strings[0]).is_file(), "{}", node.strings[0]); + } + // The leaf picture stays an atlas and the picture is a real PNG beside its .mat. + assert!(materials.iter().any(|n| n.params == vec![4.0, 2.0])); + assert!(std::fs::read_dir(root.join("nature/materials")) + .unwrap() + .any(|e| e.unwrap().path().extension().is_some_and(|x| x == "png"))); + assert!(harness + .app + .nature + .graph + .build(harness.app.nature.quality) + .is_ok()); +} + #[test] fn nature_parts_can_use_your_own_materials_and_textures() { - use crate::uikit::nature::ops; use crate::uikit::panels::nature_generator as ng; let Some(mut harness) = engine_harness() else { return; @@ -5064,18 +5124,7 @@ fn nature_parts_can_use_your_own_materials_and_textures() { .find(|n| n.op == "part") .unwrap() .id; - let params = ops::find("part").unwrap().params; - let material_index = params.iter().position(|p| p.key == "material").unwrap(); - harness.dispatch(Message::NatureGen(ng::Edit::SetParam( - part, - material_index, - ops::material_index("Your material (.mat)"), - ))); - harness.dispatch(Message::NatureGen(ng::Edit::SetString( - part, - 0, - mat.to_string_lossy().into_owned(), - ))); + use_project_asset(&mut harness, part, "mat_project", &mat.to_string_lossy()); harness.dispatch(Message::NatureGen(ng::Edit::Place)); let status = harness.app().nature.status.clone().unwrap_or_default(); assert!(status.starts_with("Placed Boulder"), "{status}"); @@ -5116,16 +5165,7 @@ fn nature_parts_can_use_your_own_materials_and_textures() { .find(|n| n.op == "part") .unwrap() .id; - harness.dispatch(Message::NatureGen(ng::Edit::SetParam( - part, - material_index, - ops::material_index("Your texture (cut-out PNG)"), - ))); - harness.dispatch(Message::NatureGen(ng::Edit::SetString( - part, - 0, - png.to_string_lossy().into_owned(), - ))); + use_project_asset(&mut harness, part, "mat_texture", &png.to_string_lossy()); harness.dispatch(Message::NatureGen(ng::Edit::Place)); let status = harness.app().nature.status.clone().unwrap_or_default(); assert!( @@ -5349,6 +5389,42 @@ fn water_generator_is_a_node_graph_tab_with_a_live_preview() { ); } +#[test] +fn water_presets_write_their_material_and_keep_your_edits() { + use crate::uikit::panels::water_generator as wg; + let Some(mut harness) = engine_harness() else { + return; + }; + let root = test_temp_root("water-materialized"); + harness.app.asset_root_override = Some(root.clone()); + let lake = harness + .app() + .watergen + .presets + .iter() + .position(|p| p.name == "Calm Lake") + .unwrap(); + harness.dispatch(Message::WaterGen(wg::Edit::ApplyPreset(lake))); + // The material exists as a file as soon as the preset is applied, before anything is placed. + let file = root.join("water/calm_lake.mat"); + assert!(file.is_file()); + let graph = &harness.app().watergen.graph; + assert!(graph + .look_asset() + .is_some_and(|p| p.ends_with("water/calm_lake.mat"))); + // Your edits to the file survive applying the preset again. + std::fs::write(&file, "edited by the user").unwrap(); + harness.dispatch(Message::WaterGen(wg::Edit::ApplyPreset(lake))); + assert_eq!( + std::fs::read_to_string(&file).unwrap(), + "edited by the user" + ); + // The reference round-trips through the saved graph text. + let text = crate::uikit::water::to_text("Calm Lake", &harness.app().watergen.graph); + let (_, back) = crate::uikit::water::from_text(&text).unwrap(); + assert_eq!(back.look_asset(), harness.app().watergen.graph.look_asset()); +} + #[test] fn placing_water_creates_an_animated_engine_surface() { use crate::uikit::panels::water_generator as wg; @@ -5375,10 +5451,40 @@ fn placing_water_creates_an_animated_engine_surface() { assert!(status.starts_with("Placed Open Sea"), "{status}"); assert_eq!(harness.app().entities.len(), before + 1); let id = harness.app().entities[harness.app().selected].id; + // The colour the preset's Water Material node had when it was turned into the asset. + let look = { + let graph = harness.app().watergen.presets[sea].graph(); + let node = graph.nodes.iter().find(|n| n.op == "look").unwrap(); + [ + node.params[0], + node.params[1], + node.params[2], + node.params[3], + ] + }; + // After placing, the node is the project's material, not a hidden built-in. + let graph = &harness.app().watergen.graph; + assert!(graph.nodes.iter().any(|n| n.op == "look_asset")); + assert!(!graph.nodes.iter().any(|n| n.op == "look")); let engine = harness.app.engine.as_mut().expect("engine"); let water = engine.water(id).expect("a water component"); assert_eq!(water.size, [300.0, 300.0]); assert!(water.waves.len() >= 8); + // The water's material is a real project asset assigned to the entity, written from the + // Water Material node: it is not hidden in the surface. + let material = engine.entity_material(id).expect("a material"); + assert!(material.ends_with("water/open_sea.mat"), "{material}"); + let file = root.join("water/open_sea.mat"); + let text = std::fs::read_to_string(&file).expect("the .mat exists"); + assert!( + text.contains("clearcoat") || text.contains("transmission"), + "{text}" + ); + let saved = engine + .load_material(&file.to_string_lossy()) + .expect("loads"); + assert!((saved.albedo[2] - look[2]).abs() < 0.01 && (saved.albedo[3] - look[3]).abs() < 0.01); + assert_eq!(saved.alpha_mode, doppio_engine::MaterialAlphaMode::Blend); // Ticking builds the surface; the waves move the height over time. for _ in 0..3 { engine.tick(0.05); @@ -5417,6 +5523,8 @@ fn water_presets_render_in_the_engine() { let Ok(dir) = std::env::var("DOPPIO_WATER_DUMP") else { return; }; + let root = test_temp_root("water-render"); + harness.app.asset_root_override = Some(root.clone()); let light = crate::uikit::prefabs::PREFABS .iter() .position(|p| p.label == "Directional Light") diff --git a/doppio/crates/ui/src/windows/main/watergen.rs b/doppio/crates/ui/src/windows/main/watergen.rs index a68c7cc..789f934 100644 --- a/doppio/crates/ui/src/windows/main/watergen.rs +++ b/doppio/crates/ui/src/windows/main/watergen.rs @@ -173,7 +173,7 @@ impl WaterGen { } } - pub fn view_state(&self) -> panel::View<'_> { + pub fn view_state(&self, materials: Vec) -> panel::View<'_> { panel::View { graph: &self.graph, selected: self.selected, @@ -190,10 +190,57 @@ impl WaterGen { stats: &self.stats, status: self.status.as_deref(), dirty: self.dirty, + project_materials: materials, } } } +/// Writes the Water Material node's colour, opacity and roughness as a `.mat` in the project and +/// returns the path to assign (asset-root relative when the project has one). +fn write_water_material( + engine: &doppio_engine::Engine, + dir: &std::path::Path, + name: &str, + albedo: [f32; 4], + roughness: f32, +) -> Result { + std::fs::create_dir_all(dir).map_err(|e| e.to_string())?; + let slug = crate::uikit::nature::slug(name); + let file = dir.join(format!("{slug}.mat")); + let relative = format!("water/{slug}.mat"); + let rooted = engine + .asset_path("") + .map(|root| !root.is_empty()) + .unwrap_or(false); + let path = if rooted { + relative + } else { + file.display().to_string() + }; + // An existing material is the user's now: it is never overwritten. + if file.exists() { + return Ok(path); + } + let mut material = engine.new_material().map_err(|e| format!("{e:?}"))?; + material.name = format!("{name} water"); + material.albedo = albedo; + material.roughness = roughness; + material.metallic = 0.0; + // Water: a low base reflectance (the Fresnel term does the rest), a thin sharp coat for the sky + // reflection, see-through, and the index of refraction of water. + material.reflectance = 0.5; + material.alpha_mode = doppio_engine::MaterialAlphaMode::Blend; + material.transmission = 0.12; + material.ior = 1.333; + material.clearcoat = 0.35; + material.clearcoat_roughness = 0.03; + material.uv_object_scale = false; + engine + .save_material(&file.to_string_lossy(), &material) + .map_err(|e| format!("{e:?}"))?; + Ok(path) +} + fn snap_position(point: Point, snap: bool) -> Point { if snap { Point::new( @@ -206,6 +253,42 @@ fn snap_position(point: Point, snap: bool) -> Point { } impl App { + /// Golden rule: the water's material is a real asset. The Water Material node is only a mould: + /// this writes its `.mat` into the project (once; an existing file is never overwritten) and + /// turns the node into **Your Water Material** pointing at it. + pub(super) fn materialize_water_assets(&mut self) -> Result<(), String> { + let Some(dir) = self.water_dir() else { + return Ok(()); + }; + let name = self.watergen.name.clone(); + let jobs: Vec<(crate::uikit::water::NodeId, [f32; 4], f32)> = self + .watergen + .graph + .nodes + .iter() + .filter(|n| n.op == "look") + .map(|n| { + ( + n.id, + [n.params[0], n.params[1], n.params[2], n.params[3]], + n.params[4], + ) + }) + .collect(); + for (id, albedo, roughness) in jobs { + let engine = self.engine.as_ref().ok_or("The engine is not available")?; + let path = write_water_material(engine, &dir, &name, albedo, roughness) + .map_err(|e| format!("Could not write the water material: {e}"))?; + if let Some(node) = self.watergen.graph.node_mut(id) { + node.op = "look_asset"; + node.params.clear(); + node.strings = vec![path]; + } + self.watergen.dirty = true; + } + Ok(()) + } + pub(super) fn show_water_pane(&mut self) { self.panes.restore(); let mut target = None; @@ -372,6 +455,11 @@ impl App { self.watergen.push(Some(format!("param:{id}:{index}"))); self.watergen.refresh(); } + Edit::SetString(id, index, text) => { + self.watergen.graph.set_string(id, index, text); + self.watergen.push(Some(format!("string:{id}:{index}"))); + self.watergen.refresh(); + } Edit::Undo => { if self.watergen.cursor > 0 { self.watergen.cursor -= 1; @@ -400,6 +488,10 @@ impl App { self.watergen.name = preset.name.to_owned(); self.watergen.load(graph); self.watergen.dirty = false; + // A preset is only a mould: its material becomes a project asset right away. + if let Err(error) = self.materialize_water_assets() { + self.watergen.status = Some(error); + } } } Edit::SetName(name) => self.watergen.name = name, @@ -438,12 +530,19 @@ impl App { /// Creates the water body in the scene as an animated engine water surface. pub(super) fn place_water(&mut self) { + if let Err(error) = self.materialize_water_assets() { + self.watergen.status = Some(error); + return; + } + self.watergen.refresh(); let Some(water) = self.watergen.water.clone() else { self.watergen.status = Some("Graph: nothing to place".to_owned()); return; }; + let material_path = self.watergen.graph.look_asset(); let name = self.watergen.name.clone(); let focus = self.camera.focus; + let water_dir = self.water_dir(); let Some(engine) = self.engine.as_mut() else { self.watergen.status = Some("The engine is not available".to_owned()); return; @@ -465,6 +564,19 @@ impl App { )); return; } + // The water's material is a real project asset (`water/.mat`), assigned to the + // entity: open it in the Material tab to change it. + let _ = water_dir; + let Some(path) = material_path else { + self.watergen.status = Some( + "Open a project first: the water material is saved in its assets folder".to_owned(), + ); + return; + }; + if let Err(error) = engine.apply_material(id, &path) { + self.watergen.status = Some(format!("Could not assign the water material: {error:?}")); + return; + } self.entities = super::projectloader::read_entities(engine); if let Some(index) = self.entities.iter().position(|entity| entity.id == id) { self.select_index(index); diff --git a/doppio/docs/nature-generator-guide.md b/doppio/docs/nature-generator-guide.md index aa617b1..fab371f 100644 --- a/doppio/docs/nature-generator-guide.md +++ b/doppio/docs/nature-generator-guide.md @@ -21,7 +21,9 @@ cycle (the status line says why a link was refused): | **Points** | positions, orientations and scales produced by *Scatter Points* | Every mesh that should end up in the model goes through a **Part** node into the **Output** node (one input -per part). A part carries a name and a material; the engine gives one material per mesh, so each part +per part). A Part is a mesh **and its material, both wired in**: its *Material* port takes a node from the +**Materials** category, and nothing is chosen inside the Part. A part with no material refuses to build ("The +trunk part has no material: wire a material node..."). The engine gives one material per mesh, so each part becomes its own entity when placed. Interaction: add nodes from the left palette (search box, categories) or drag from it; drag nodes by their @@ -39,6 +41,7 @@ Everything is deterministic: the same graph, quality and seeds always build the | Trees | **Grow Branches** (skeleton), **Roots**, **Branch Tubes**, **Leaves** (folded, drooping cards with a leaf-shape atlas, or blobs) | | Plants | **Grass Blades**, **Fern Fronds**, **Leafy Bush**, **Stem**, **Petals** | | Scatter | **Scatter Points**, **Instance on Points** (moss, pebbles, small leaves on any mesh) | +| Materials | **Library Material** (rock, bark, ground presets), **Leaf / Petal Texture** (cards and atlases), **Solid Colour**, **Your Material (.mat)**, **Your Texture (PNG)** | | Output | **Part**, **Output** | Rocks are `Icosphere → Noise Displace → Cut Planes → Noise Displace (grain) → Flat Base → Transform → Place @@ -70,22 +73,30 @@ the graph is for: **Mossy Rock** (moss cards scattered over the rock), **Ancient branches and a dense crown) and **Fern Patch** (a scatter of fern clumps). Low-poly presets: Low-poly Rock, Low-poly Tree and Low-poly Pine. -## 4. Your own materials and textures +## 4. Materials are nodes, and they are real assets -The **Part** node has a *Material* choice: +Nothing about a material is hidden inside a generated object. Every part has a **material node** wired into its +Part, and the preset graphs show them (a bark node feeding the trunk, a leaf texture feeding the leaves): -| Choice | Meaning | +| Node | Gives | |---|---| -| Library presets (rock, bark, moss, ...) | baked once from the PBR library into `nature/materials/` | -| Texture Generator cards | a procedural cut-out card (leaf, blade, petal) baked to RGBA | -| **Leaf atlases** (*Broadleaf Mix*, *Autumn Mix*) | one image with **eight different leaf shapes and tints** (4 x 2); pair it with the Leaves node's *Leaf shapes: Atlas 4x2* | -| Solid colours / custom colour | only a `.mat`, ideal for low poly | -| **Your material (.mat)** | pick any `.mat` of the project; it is applied **as it is**, never copied or rebaked | -| **Your texture (cut-out PNG)** | pick a PNG with alpha; a **Cutout** material is made around it (`nature/materials/project_.mat`) | +| **Library Material** | a preset from the PBR library (rock, bark, ground), baked once into `nature/materials/` | +| **Leaf / Petal Texture** | a procedural cut-out card (leaf, petal) or an **atlas** (*Broadleaf Mix*, *Autumn Mix*: eight leaf shapes and tints in one image) baked to RGBA | +| **Solid Colour** | a plain colour and roughness, ideal for low poly | +| **Your Material (.mat)** | any `.mat` of the project, used **as it is**, never copied or rebaked | +| **Your Texture (PNG)** | a PNG with alpha; a **Cutout** material is made around it (`nature/materials/project_.mat`) | -The pickers list the project's materials and textures. Project assets are never replaced when the quality -is Stylized, so a hand-painted bark stays on a low-poly trunk. UVs come from the nodes (UV Box for rocks, -tube UVs for trunks, card UVs for leaves) so your textures tile as expected. +When you **Place in scene**, each part's material is written to the project as a normal asset and assigned to +the entity: open it in the **Material** tab or the Texture Generator and change it. Swap a node (a Solid Colour +for your own `.mat`) to change what the whole model uses. Low poly (*Stylized*) turns library and card +materials into solid colours, but **your own assets are never replaced**. + +The **Leaves** node also takes the leaf texture on its *Texture* port (the same node that feeds the leaves' +Part), which is how it knows the atlas layout, and sizes the leaves as a **percentage of the tree's height** +(*Leaf size*, default 7 %), so the proportions follow the tree instead of being a number in metres. + +UVs come from the nodes (UV Box for rocks, tube UVs for trunks, card UVs for leaves) so your textures tile as +expected. Saved `.nature` files from before this change have no material nodes and need one wired in. ## 4b. Generated surfaces: a texture set baked from the model itself @@ -205,3 +216,13 @@ oak crown with varied, curved leaves. ./scripts/render-nature-docs.sh # the three preview sheets (software renderer, no engine) ./scripts/capture-nature-docs.sh # headless screenshots of the tab and the placed scene (needs libcaffeine-capi) ``` + +## Golden rule: every material is an asset + +The Library Material, Leaf / Petal Texture and Solid Colour nodes (and every preset) are only +**moulds**. Applying a preset, or placing a model, writes each material's picture and `.mat` into +`nature/materials/` in your project and turns the node into **Your Material (.mat)** pointing at +them. Nothing stays hidden in the menu: open the `.mat` in the Material tab, repaint the PNG, or +point the node at another file. A material is only written once, so your edits to it are kept. +Your Material and Your Texture carry *Shapes across / down*, the atlas layout of the picture, which +the Leaves node reads to know how many leaf shapes it holds. diff --git a/doppio/docs/water-generator-guide.md b/doppio/docs/water-generator-guide.md index 974f938..82dc9a1 100644 --- a/doppio/docs/water-generator-guide.md +++ b/doppio/docs/water-generator-guide.md @@ -16,13 +16,13 @@ Two typed ports (two colours); a link only connects ports of the same type and n | Port | Carries | |---|---| | **Waves** | a list of Gerstner waves (direction, wavelength, amplitude, steepness, phase) | -| **Look** | colour, opacity (low = clear), roughness and foam threshold | +| **Look** | the **Water Material**: colour, opacity (low = clear), roughness and foam threshold | | Category | Nodes | |---|---| | Waves | **Gerstner Wave** (one explicit wave), **Wind Sea** (a spectrum from wind speed, direction, spread and choppiness), **Swell** (long regular trains from afar), **Ripples** (short waves from many directions) | | Modifiers | **Merge Waves** (up to four sources; keeps the strongest 16), **Scale Waves** (amplitude, wavelength, choppiness, rotation) | -| Look | **Water Look** | +| Look | **Water Material** | | Output | **Output**: size X/Z, water level, depth, mesh resolution, time scale, seed | Interaction is the same as the other generators: palette on the left, canvas in the middle, parameters and @@ -31,6 +31,16 @@ the animated **Surface preview** on the right. Undo/redo cover every edit, *Expo the entity. The preview is a top-down render of the same Gerstner sum the engine animates (sun-lit slopes, a Fresnel sky reflection, foam where crests compress); it is a shape preview, not the final shading. +## 1b. The water always has its material + +Water cannot exist without a material: the Output's **Material** port needs a **Water Material** node, and a graph +without one does not build ("The water has no material: wire a Water Material node..."). **Place in scene** writes +that node as a real project asset, `water/.mat` (colour and opacity, roughness, a low base reflectance, a thin +clearcoat, transmission and the refraction index of water, alpha blend), and assigns it to the water entity, so the +material is visible in the Assets panel and editable in the **Material** tab like any other. The engine renders the +water with the entity's material whenever it has one (without a material it falls back to a built-in water look). +Placing again regenerates the `.mat` from the node; keep your edits by assigning your own material afterwards. + ## 2. Why this is modular and cheap * **Waves are the unit of work.** A sea is a handful of well-chosen waves, not a texture or a simulation. The @@ -125,7 +135,7 @@ This is the foundation of the rework, not all of it. Honest status: * **No dedicated water shader yet.** The surface is still the engine's PBR transparent material. What is missing and next: **depth-based absorption and colour** (shallow turquoise to deep blue), **refraction**, **foam and shoreline** from depth/Jacobian, **caustics**, and a **normal-map detail layer** so ripples need - no vertices. Until then the look in the engine is paler and flatter than the Look node suggests; it also + no vertices. Until then the look in the engine is paler and flatter than the Water Material node suggests; it also reflects a lot of sky at grazing angles. * **Vertex-displaced mesh only**, up to 256 x 256 cells, rebuilt on the CPU each frame. A **clipmap/LOD mesh** around the camera and moving the waves to the **vertex shader** are what make an ocean scale; the graph @@ -143,3 +153,11 @@ This is the foundation of the rework, not all of it. Honest status: ./scripts/capture-water-docs.sh # the tab (headless, no engine) DOPPIO_WATER_DUMP=/tmp/water cargo test -p doppio-ui --lib water_presets_render # engine renders of every preset ``` + +## The material is an asset from the start + +The Water Material node is a mould. Applying a preset (or placing) writes `water/.mat` into the +project and turns the node into **Your Water Material (.mat)** pointing at it. An existing file is +never overwritten, so repainting it in the Material tab, or pointing the node at your own `.mat`, +sticks. The terrain's splat layers are still shaded by the engine; making them project materials +needs an engine change and is on the list. From 168529736c1c80ceff0949e1568feb26d820efc9 Mon Sep 17 00:00:00 2001 From: lyeepedro Date: Wed, 18 Nov 2026 12:57:12 +0000 Subject: [PATCH 3/3] Terrain: layer pictures are project assets; add headless render example The Output node holds four texture slots filled from the material library into terrain/layers/*.png and written to the terrain component's Splat Layer Paths. doppio-engine gains examples/render_scene.rs, a scene built and rendered to PNG through the C ABI. Co-Authored-By: Claude Sonnet 5.5 --- doppio/crates/engine/examples/render_scene.rs | 139 ++++++++++++++++++ .../ui/src/uikit/panels/terrain_generator.rs | 21 +++ doppio/crates/ui/src/uikit/terrain/mod.rs | 74 ++++++++-- doppio/crates/ui/src/windows/main.rs | 8 +- .../crates/ui/src/windows/main/terraingen.rs | 95 +++++++++++- doppio/crates/ui/src/windows/main/tests.rs | 10 ++ 6 files changed, 335 insertions(+), 12 deletions(-) create mode 100644 doppio/crates/engine/examples/render_scene.rs diff --git a/doppio/crates/engine/examples/render_scene.rs b/doppio/crates/engine/examples/render_scene.rs new file mode 100644 index 0000000..ee7855b --- /dev/null +++ b/doppio/crates/engine/examples/render_scene.rs @@ -0,0 +1,139 @@ +//! Builds a tiny scene through the C ABI and renders it to a PNG, with no editor and no window. +//! +//! ```text +//! cmake --build build --target caffeine-capi -j +//! cd doppio && cargo run -p doppio-engine --example render_scene -- /tmp/scene.png +//! ``` +//! +//! `CAFFEINE_CAPI_LIB` points at another `libcaffeine-capi` when it is not in `build/`. +//! See `caffeine-website/content/en/docs/api/headless-engine-api.md`. + +use doppio_engine::{Engine, FieldValue}; + +/// Adds a component by name and sets fields by name: the whole "scene description" language. +struct Scene<'a> { + engine: &'a mut Engine, +} + +impl Scene<'_> { + fn component(&mut self, entity: u32, name: &str) -> u32 { + let type_id = self + .engine + .component_types() + .iter() + .find(|t| t.name == name) + .unwrap_or_else(|| panic!("no component named {name}")) + .id; + self.engine.add_component(entity, type_id).expect("add"); + type_id + } + + fn set(&mut self, entity: u32, type_id: u32, field: &str, value: FieldValue) { + let component = self + .engine + .entity_components(entity) + .iter() + .position(|c| c.type_id == type_id) + .expect("component was added") as u32; + let index = self + .engine + .component_types() + .iter() + .find(|t| t.id == type_id) + .and_then(|t| t.fields.iter().position(|f| f.name == field)) + .unwrap_or_else(|| panic!("no field named {field}")) as u32; + self.engine + .set_component_field(entity, component, index, &value) + .expect("set field"); + } + + /// An entity drawn as a built-in shape (`Cube`, `Sphere`, `Plane`...). + fn shape(&mut self, name: &str, primitive: &str, at: [f32; 3], scale: [f32; 3]) -> u32 { + let entity = self.engine.create_entity(name).expect("entity"); + let filter = self.component(entity, "Mesh Filter"); + let option = self + .engine + .component_types() + .iter() + .find(|t| t.id == filter) + .and_then(|t| t.fields.iter().find(|f| f.name == "Primitive")) + .and_then(|f| f.options.iter().position(|o| o == primitive)) + .unwrap_or_else(|| panic!("no primitive named {primitive}")); + self.set(entity, filter, "Primitive", FieldValue::Enum(option as i32)); + self.component(entity, "Mesh Renderer"); + self.engine.set_position(entity, at).expect("position"); + self.engine.set_scale(entity, scale).expect("scale"); + entity + } +} + +fn main() { + let out = std::env::args() + .nth(1) + .unwrap_or_else(|| "scene.png".to_owned()); + let mut engine = + Engine::load_default().expect("libcaffeine-capi not found (see CAFFEINE_CAPI_LIB)"); + + // A project folder for the materials (any folder works). + let root = std::env::temp_dir().join("caffeine-render-scene"); + std::fs::create_dir_all(&root).expect("folder"); + engine + .set_asset_root(&root.to_string_lossy()) + .expect("asset root"); + + let mut scene = Scene { + engine: &mut engine, + }; + let ground = scene.shape("Ground", "Plane", [0.0, 0.0, 0.0], [10.0, 1.0, 10.0]); + let cube = scene.shape("Cube", "Cube", [-1.2, 0.5, 0.0], [1.0, 1.0, 1.0]); + let ball = scene.shape("Ball", "Sphere", [1.2, 0.5, 0.0], [1.0, 1.0, 1.0]); + + let sun = scene.engine.create_entity("Sun").expect("entity"); + let light = scene.component(sun, "Light"); + scene.set(sun, light, "Intensity", FieldValue::F32(1.2)); + scene.component(sun, "Directional Light"); + scene + .engine + .set_rotation(sun, [-40.0, 130.0, 0.0]) + .expect("rotation"); + + // Materials are `.mat` assets: write them, then assign them to entities by path. + for (entity, name, albedo, roughness) in [ + (ground, "ground", [0.25, 0.4, 0.2, 1.0], 0.9), + (cube, "red", [0.8, 0.1, 0.1, 1.0], 0.4), + (ball, "steel", [0.7, 0.7, 0.75, 1.0], 0.2), + ] { + let mut material = scene.engine.new_material().expect("material"); + material.albedo = albedo; + material.roughness = roughness; + let path = root.join(format!("{name}.mat")); + scene + .engine + .save_material(&path.to_string_lossy(), &material) + .expect("save"); + scene + .engine + .apply_material(entity, &path.to_string_lossy()) + .expect("apply"); + } + + // The camera orbits a focus point: yaw/pitch in radians, distance in metres. + engine + .set_camera(doppio_engine::Camera { + yaw: 0.6, + pitch: 0.35, + distance: 6.0, + focus: [0.0, 0.5, 0.0], + }) + .expect("camera"); + + // The editor grid is on by default; a clean picture turns it off. + let mut settings = engine.viewport_settings().expect("settings"); + settings.show_grid = false; + engine.set_viewport_settings(settings).expect("settings"); + + let (width, height) = (960, 540); + let pixels = engine.render(width, height).expect("render"); + image::save_buffer(&out, &pixels, width, height, image::ColorType::Rgba8).expect("png"); + println!("wrote {out} ({width}x{height})"); +} diff --git a/doppio/crates/ui/src/uikit/panels/terrain_generator.rs b/doppio/crates/ui/src/uikit/panels/terrain_generator.rs index d55d889..6f90e4a 100644 --- a/doppio/crates/ui/src/uikit/panels/terrain_generator.rs +++ b/doppio/crates/ui/src/uikit/panels/terrain_generator.rs @@ -44,6 +44,8 @@ pub enum Edit { DeleteNode(NodeId), /// Node, parameter index, value. SetParam(NodeId, usize, f32), + /// Node, string index, text (a texture path). + SetString(NodeId, usize, String), Undo, Redo, Fit, @@ -64,6 +66,7 @@ pub enum Edit { } pub struct View<'a> { + pub project_textures: Vec, pub graph: &'a TerrainGraph, pub selected: Option, pub selected_link: Option<(NodeId, usize)>, @@ -484,6 +487,24 @@ fn properties<'a, Message: Clone + 'a>( } } } + for (index, label) in def.strings.iter().enumerate() { + let current = node.strings.get(index).cloned().unwrap_or_default(); + let pick_emit = emit.clone(); + body = body.push(dropdown::property( + id::terraingen_param(&format!("layer{index}")), + *label, + view.project_textures.clone(), + Some(current.clone()).filter(|c| !c.is_empty()), + move |choice| pick_emit(Edit::SetString(node_id, index, choice)), + )); + let text_emit = emit.clone(); + body = body.push(text_field::property( + id::terraingen_param(&format!("layer{index}_path")), + "Path", + ¤t, + move |value| text_emit(Edit::SetString(node_id, index, value)), + )); + } container(body) .width(Length::Fill) .padding(4) diff --git a/doppio/crates/ui/src/uikit/terrain/mod.rs b/doppio/crates/ui/src/uikit/terrain/mod.rs index 6f2e0b5..5a32f60 100644 --- a/doppio/crates/ui/src/uikit/terrain/mod.rs +++ b/doppio/crates/ui/src/uikit/terrain/mod.rs @@ -66,6 +66,8 @@ pub struct NodeDef { pub inputs: &'static [PortDef], pub outputs: &'static [PortDef], pub params: &'static [ParamSpec], + /// Labels of the text fields the node has (asset paths). + pub strings: &'static [&'static str], pub eval: fn(&Args) -> Vec, } @@ -419,6 +421,14 @@ fn eval_hydraulic(a: &Args) -> Vec { // ------------------------------------------------------------------ output const RESOLUTIONS: &[&str] = &["129", "257", "513"]; +/// The four splat layer pictures the terrain is painted with: project textures, not built-ins. +pub const LAYER_LABELS: &[&str] = &[ + "Ground texture", + "Rock texture", + "Dirt texture", + "Mud texture", +]; + const OUTPUT_IN: &[PortDef] = &[port("Height")]; const OUTPUT_P: &[ParamSpec] = &[ float("size_x", "Size X (m)", 50.0, 8000.0, 1000.0, 10.0), @@ -443,6 +453,7 @@ macro_rules! node { inputs: $in, outputs: $out, params: $params, + strings: &[], eval: $eval, } }; @@ -596,15 +607,16 @@ pub static NODES: &[NodeDef] = &[ HYDRO_P, eval_hydraulic ), - node!( - "output", - "Output", - "Output", - OUTPUT_IN, - NONE, - OUTPUT_P, - eval_output - ), + NodeDef { + id: "output", + title: "Output", + category: "Output", + inputs: OUTPUT_IN, + outputs: NONE, + params: OUTPUT_P, + strings: LAYER_LABELS, + eval: eval_output, + }, ]; pub fn find(id: &str) -> Option<&'static NodeDef> { @@ -618,6 +630,7 @@ pub struct TerrainNode { pub id: NodeId, pub op: &'static str, pub params: Vec, + pub strings: Vec, pub position: Point, } @@ -663,6 +676,7 @@ impl TerrainGraph { id, op: def.id, params: def.params.iter().map(|p| p.default).collect(), + strings: def.strings.iter().map(|_| String::new()).collect(), position, }); id @@ -713,6 +727,23 @@ impl TerrainGraph { self.links.retain(|l| l.from != id && l.to != id); } + pub fn set_string(&mut self, id: NodeId, index: usize, text: String) { + if let Some(slot) = self + .node_mut(id) + .and_then(|node| node.strings.get_mut(index)) + { + *slot = text; + } + } + + /// The four layer texture paths on the Output node (empty until they are written). + pub fn layer_paths(&self) -> Vec { + self.output_node() + .and_then(|id| self.node(id)) + .map(|n| n.strings.clone()) + .unwrap_or_default() + } + pub fn output_node(&self) -> Option { self.nodes.iter().find(|n| n.op == "output").map(|n| n.id) } @@ -844,6 +875,17 @@ impl TerrainGraph { for v in &node.params { text.push_str(&format!(" {v}")); } + if !node.strings.is_empty() { + text.push_str(&format!(" {}", node.strings.len())); + for s in &node.strings { + text.push(' '); + if s.is_empty() { + text.push_str("%00"); + } else { + text.push_str(&s.replace('%', "%25").replace(' ', "%20")); + } + } + } text.push('\n'); } for l in &self.links { @@ -875,11 +917,25 @@ impl TerrainGraph { *slot = word.parse().ok()?; } } + let mut strings: Vec = + def.strings.iter().map(|_| String::new()).collect(); + if let Some(count) = w.get(6 + n).and_then(|c| c.parse::().ok()) { + for (i, word) in w.get(7 + n..7 + n + count)?.iter().enumerate() { + if let Some(slot) = strings.get_mut(i) { + *slot = if *word == "%00" { + String::new() + } else { + word.replace("%20", " ").replace("%25", "%") + }; + } + } + } graph.next_id = graph.next_id.max(id + 1); graph.nodes.push(TerrainNode { id, op: def.id, params, + strings, position, }); } diff --git a/doppio/crates/ui/src/windows/main.rs b/doppio/crates/ui/src/windows/main.rs index c0c27d0..71f916d 100644 --- a/doppio/crates/ui/src/windows/main.rs +++ b/doppio/crates/ui/src/windows/main.rs @@ -8537,7 +8537,13 @@ impl App { "{} · {}", self.terraingen.name, self.terraingen.stats )), - terrain_generator_panel::view(self.terraingen.view_state(), Message::TerrainGen), + { + let (_, textures) = self.nature_assets(); + terrain_generator_panel::view( + self.terraingen.view_state(textures), + Message::TerrainGen, + ) + }, ), PaneKind::TextureGenerator => ( id::PANE_TEXTURE_GENERATOR, diff --git a/doppio/crates/ui/src/windows/main/terraingen.rs b/doppio/crates/ui/src/windows/main/terraingen.rs index dc4aead..f002d3b 100644 --- a/doppio/crates/ui/src/windows/main/terraingen.rs +++ b/doppio/crates/ui/src/windows/main/terraingen.rs @@ -166,8 +166,9 @@ impl TerrainGen { } } - pub fn view_state(&self) -> panel::View<'_> { + pub fn view_state(&self, textures: Vec) -> panel::View<'_> { panel::View { + project_textures: textures, graph: &self.graph, selected: self.selected, selected_link: self.link, @@ -226,7 +227,7 @@ impl App { } } - fn terrain_dir(&self) -> Option { + pub(super) fn terrain_dir(&self) -> Option { self.asset_root_dir().map(|root| root.join("terrain")) } @@ -356,8 +357,17 @@ impl App { self.terraingen.name = preset.name.to_owned(); self.terraingen.load(graph); self.terraingen.dirty = false; + // A preset is only a mould: its layer pictures become project assets now. + if let Err(error) = self.materialize_terrain_assets() { + self.terraingen.status = Some(error); + } } } + Edit::SetString(id, index, text) => { + self.terraingen.graph.set_string(id, index, text); + self.terraingen.push(Some(format!("string:{id}:{index}"))); + self.terraingen.refresh(); + } Edit::SetName(name) => self.terraingen.name = name, Edit::New => { let mut graph = TerrainGraph::new(); @@ -425,8 +435,74 @@ impl App { }); } + /// Golden rule: the terrain's layer pictures are project assets. Empty slots on the Output node + /// are filled by baking material-library pictures into `terrain/layers/`; existing files and + /// paths you chose are never touched. + pub(super) fn materialize_terrain_assets(&mut self) -> Result<(), String> { + let Some(dir) = self.terrain_dir() else { + return Ok(()); + }; + let Some(output) = self.terraingen.graph.output_node() else { + return Ok(()); + }; + // Ground, rock, dirt and mud, from the material library. + const SOURCES: [(&str, &str); 4] = [ + ("ground", "Ground · Lawn Grass"), + ("rock", "Rock · Cliff Granite"), + ("dirt", "Rock · Sandstone"), + ("mud", "Ground · Pine Needles"), + ]; + let layers = self.terraingen.graph.layer_paths(); + for (i, (slug, label)) in SOURCES.iter().enumerate() { + if layers.get(i).is_some_and(|p| !p.is_empty()) { + continue; + } + let crate::uikit::nature::mesh::MaterialSpec::Preset(preset) = + crate::uikit::nature::ops::spec_for_label( + label, + crate::uikit::nature::Quality::Balanced, + ) + else { + continue; + }; + let folder = dir.join("layers"); + std::fs::create_dir_all(&folder).map_err(|e| e.to_string())?; + let file = folder.join(format!("{slug}.png")); + if !file.exists() { + let preset = crate::uikit::material_library::presets() + .iter() + .find(|p| p.name == preset) + .ok_or_else(|| format!("unknown material preset `{preset}`"))?; + let mut graph = + preset.build(&crate::uikit::material_library::PresetParams::default()); + graph.resolution = 512; + let baked = graph.bake().map_err(|e| format!("{slug}: {e}"))?; + image::save_buffer(&file, &baked.base, 512, 512, image::ColorType::Rgba8) + .map_err(|e| e.to_string())?; + } + let rooted = self + .engine + .as_ref() + .and_then(|e| e.asset_path("").ok()) + .is_some_and(|root| !root.is_empty()); + let path = if rooted { + format!("terrain/layers/{slug}.png") + } else { + file.display().to_string() + }; + self.terraingen.graph.set_string(output, i, path); + self.terraingen.dirty = true; + } + Ok(()) + } + /// Builds the terrain at the Output node's resolution and places it as an engine terrain. pub(super) fn place_terrain(&mut self) { + if let Err(error) = self.materialize_terrain_assets() { + self.terraingen.status = Some(error); + return; + } + let layers = self.terraingen.graph.layer_paths(); let res = self.terraingen.graph.output_resolution(); let model = match self.terraingen.graph.build(res) { Ok(model) => model, @@ -464,6 +540,21 @@ impl App { )); return; } + // The four layer pictures are the project's textures, written from the Output node. + if let Some(type_id) = super::component_type_id(engine, "Terrain") { + for (i, path) in layers.iter().enumerate().filter(|(_, p)| !p.is_empty()) { + let resolved = engine + .asset_project_path(path) + .unwrap_or_else(|_| path.clone()); + let _ = super::set_component_field( + engine, + id, + type_id, + &format!("Splat Layer Paths {}", i + 1), + doppio_engine::FieldValue::String(resolved), + ); + } + } self.entities = super::projectloader::read_entities(engine); if let Some(index) = self.entities.iter().position(|entity| entity.id == id) { self.select_index(index); diff --git a/doppio/crates/ui/src/windows/main/tests.rs b/doppio/crates/ui/src/windows/main/tests.rs index cc35ee8..c3d673e 100644 --- a/doppio/crates/ui/src/windows/main/tests.rs +++ b/doppio/crates/ui/src/windows/main/tests.rs @@ -5681,6 +5681,16 @@ fn placing_a_terrain_creates_an_engine_terrain_with_splat_layers() { let status = harness.app().terraingen.status.clone().unwrap_or_default(); assert!(status.starts_with("Placed Alpine Range"), "{status}"); assert_eq!(harness.app().entities.len(), before + 1); + // The four layer pictures are real files in the project, written when the preset was applied. + let layers = harness.app().terraingen.graph.layer_paths(); + assert_eq!(layers.len(), 4); + for path in &layers { + assert!(!path.is_empty() && path.ends_with(".png"), "{path}"); + assert!(root.join("terrain/layers").is_dir()); + } + for name in ["ground", "rock", "dirt", "mud"] { + assert!(root.join(format!("terrain/layers/{name}.png")).is_file()); + } let id = harness.app().entities[harness.app().selected].id; let model = harness.app().terraingen.graph.build(257).unwrap(); let engine = harness.app.engine.as_mut().expect("engine");