From 8bdae1157d34daf008a50bed4f8594ca8002fa4c Mon Sep 17 00:00:00 2001 From: PiJellyPin Date: Thu, 5 Nov 2026 02:38:04 +0100 Subject: [PATCH] Fixed Heightmap --- apps/materialcraft-cli/src/main.rs | 4 +- crates/automation/src/headless.rs | 18 +-- crates/automation/src/server.rs | 5 +- crates/engine/src/session.rs | 7 +- crates/engine/src/view_cmds.rs | 5 +- crates/engine/tests/session.rs | 18 +++ crates/render/src/lib.rs | 2 +- crates/render/src/preview.rs | 209 ++++++++++++++++++++++------- crates/ui-egui/src/view3d.rs | 152 ++++++++++++++++++--- crates/ui-egui/src/windows.rs | 2 +- docs/architecture.md | 2 +- docs/control-protocol.md | 2 +- docs/gaps.md | 2 +- docs/target-app-parity.md | 2 +- docs/wires-and-alpha.md | 2 +- 15 files changed, 333 insertions(+), 99 deletions(-) diff --git a/apps/materialcraft-cli/src/main.rs b/apps/materialcraft-cli/src/main.rs index 57868c09..8607d50d 100644 --- a/apps/materialcraft-cli/src/main.rs +++ b/apps/materialcraft-cli/src/main.rs @@ -36,8 +36,8 @@ USAGE: [--yaw ] [--pitch ] [--graph ] [--set =]... [--full] [--tiling ] [--hq [--displacement ]] Render the material on a 3D scene (rounded_cube, cube, sphere, cylinder, plane, torus, - material_ball), or one node's output (--view 2d), to PNG. No GPU needed. --hq is a beauty - render: real displacement from the height output, ambient occlusion and a key light. + material_ball), or one node's output (--view 2d), to PNG. No GPU needed. The height output + raises the surface; --hq is a beauty render with a finer mesh, ambient occlusion and a key light. materialcraft-cli mcp [--bridge ] [--token ] [--read-root ] [--write-root ] MCP server on stdio: headless (file access only below the roots), or bridged to `materialcraft --control `. diff --git a/crates/automation/src/headless.rs b/crates/automation/src/headless.rs index 93feac1c..81ed64e5 100644 --- a/crates/automation/src/headless.rs +++ b/crates/automation/src/headless.rs @@ -5,7 +5,7 @@ use std::path::Path; use materialcraft_engine::core::NodeId; use materialcraft_engine::{Session, commands, file_cmds, inspect}; -use materialcraft_render::{Lighting, Maps, Scene, Settings}; +use materialcraft_render::{Lighting, Maps, Relief, Scene, Settings, VIEW_TRIANGLES}; use serde_json::{Value, json}; use crate::budgets::{HQ_TRIANGLES, MAX_LOCAL_RENDER_SIDE, MAX_PNG_SIDE, check_png, encode_png}; @@ -42,10 +42,9 @@ pub struct RenderOptions { pub full: bool, /// 3D: UV repeats override (the session's view is not changed). pub tiling: Option, - /// 3D: beauty render: the height output displaces a subdivided mesh, with ray-traced - /// ambient occlusion, a shadowed key light and 3×3 supersampling. Slower; for stills. + /// 3D: beauty render: a finer displaced mesh, ray-traced ambient occlusion, a shadowed key light and 3×3 supersampling. pub hq: bool, - /// 3D, with `hq`: displacement depth in scene radii (default 0.04). + /// 3D, with `hq`: displacement depth in scene radii (default: the view's height depth). pub displacement: Option, } @@ -249,6 +248,8 @@ impl Headless { self.light = Some(Lighting::new(&v.environment)); } let tiling = o.tiling.unwrap_or(v.tiling).clamp(0.1, 64.0); + let depth = if o.hq { o.displacement.unwrap_or(v.height_scale) } else { v.height_scale }; + let relief = Relief { depth: depth.clamp(0.0, 0.5), level: v.height_level }; let mut settings = Settings { yaw: o.yaw.unwrap_or(v.yaw), pitch: o.pitch.unwrap_or(v.pitch), @@ -257,7 +258,6 @@ impl Headless { tiling, exposure: v.exposure, env_rotation: v.env_rotation, - height_scale: v.height_scale, show_env: false, supersample: 2, transparency: v.transparency, @@ -267,13 +267,7 @@ impl Headless { let (w, h) = (o.width.unwrap_or(1024).clamp(16, max), o.height.unwrap_or(768).clamp(16, max)); let maps = Maps::from_usages(self.session.material_maps()); let (Some((_, scene)), Some(light)) = (&self.scene, &self.light) else { return (w, h, vec![0; (w * h * 4) as usize]) }; - let displaced = match (o.hq, &maps.height) { - (true, Some(height)) => { - settings.height_scale = 0.0; - Some(Scene::displaced(&scene.mesh, height, tiling, o.displacement.unwrap_or(0.04).clamp(0.0, 0.5) * scene.radius, HQ_TRIANGLES)) - } - _ => None, - }; + let displaced = scene.with_relief(&maps, relief, tiling, if o.hq { HQ_TRIANGLES } else { VIEW_TRIANGLES }); if o.hq { settings.supersample = 3; settings.ao_rays = 8; diff --git a/crates/automation/src/server.rs b/crates/automation/src/server.rs index b80cbed9..8987c3ce 100644 --- a/crates/automation/src/server.rs +++ b/crates/automation/src/server.rs @@ -189,11 +189,10 @@ pub struct RenderParams { /// 3D: UV repeats of the material on the scene for this render only. #[serde(default, skip_serializing_if = "Option::is_none")] pub tiling: Option, - /// 3D beauty render: real displacement from the height output, ambient occlusion and a - /// shadowed key light (slower). + /// 3D beauty render: a finer displaced mesh, ambient occlusion and a shadowed key light (slower). #[serde(default, skip_serializing_if = "Option::is_none")] pub hq: Option, - /// With `hq`: displacement depth in scene radii (default 0.04). + /// With `hq`: displacement depth in scene radii (default: the view's height depth). #[serde(default, skip_serializing_if = "Option::is_none")] pub displacement: Option, } diff --git a/crates/engine/src/session.rs b/crates/engine/src/session.rs index 7dbdeaea..34037cdf 100644 --- a/crates/engine/src/session.rs +++ b/crates/engine/src/session.rs @@ -32,8 +32,10 @@ pub struct View3d { pub environment: String, pub env_rotation: f32, pub exposure: f32, - /// Parallax depth of the height output (0 = off). + /// How far the height output raises the surface (white above black), in mesh radii; 0 = off. pub height_scale: f32, + /// The height (0..1) that stays on the surface: 0 = the relief rises out of the mesh, 0.5 = centered on it. + pub height_level: f32, pub show_axis: bool, pub show_grid: bool, /// See through the mesh where the material's alpha (opacity output, else base color alpha) @@ -55,7 +57,8 @@ impl Default for View3d { environment: "studio".into(), env_rotation: 0.0, exposure: 0.0, - height_scale: 0.012, + height_scale: 0.04, + height_level: 0.0, show_axis: false, show_grid: false, transparency: true, diff --git a/crates/engine/src/view_cmds.rs b/crates/engine/src/view_cmds.rs index 5b3299e3..d1beb70d 100644 --- a/crates/engine/src/view_cmds.rs +++ b/crates/engine/src/view_cmds.rs @@ -29,7 +29,7 @@ pub(crate) fn specs() -> Vec { "3D view settings", [], None, - "{scene? (cube|cylinder|plane|sphere|material_ball|rounded_cube|torus), tiling?, yaw?, pitch?, distance?, target? ([x, y, z] orbit point in mesh radii from its center, within the pan limit preference), environment? (studio|sunset|overcast|night), envRotation?, exposure?, heightScale?, axis?, grid?, transparency? (see through where alpha < 1), alphaView? (show the alpha channel)}", + "{scene? (cube|cylinder|plane|sphere|material_ball|rounded_cube|torus), tiling?, yaw?, pitch?, distance?, target? ([x, y, z] orbit point in mesh radii from its center, within the pan limit preference), environment? (studio|sunset|overcast|night), envRotation?, exposure?, heightScale? (displacement depth in mesh radii, 0..0.5), heightLevel? (height that stays on the surface, 0..1; 0 = rises out), axis?, grid?, transparency? (see through where alpha < 1), alphaView? (show the alpha channel)}", always, view3d ), @@ -138,6 +138,9 @@ fn view3d(s: &mut Session, p: &J) -> Result { if let Some(t) = f32p(p, "heightScale") { v.height_scale = t.clamp(0.0, 0.5); } + if let Some(t) = f32p(p, "heightLevel") { + v.height_level = t.clamp(0.0, 1.0); + } if let Some(b) = boolp(p, "axis") { v.show_axis = b; } diff --git a/crates/engine/tests/session.rs b/crates/engine/tests/session.rs index 60a98866..2c71972c 100644 --- a/crates/engine/tests/session.rs +++ b/crates/engine/tests/session.rs @@ -297,6 +297,24 @@ fn view3d_target_is_validated_clamped_and_reset() { assert_eq!(s.view3d.target, [0.0; 3]); } +/// The height output rises out of the mesh by default; depth and level are clamped and reset with the scene. +#[test] +fn view3d_height_depth_and_level_are_clamped_and_reset() { + let mut s = sample_session(); + assert_eq!(s.view3d.height_level, 0.0, "the relief rises out of the surface by default"); + assert!(s.view3d.height_scale > 0.0); + + let view = run(&mut s, "view.3d", json!({"heightScale": 0.1, "heightLevel": 0.5})); + assert_eq!((view["heightScale"].as_f64(), view["heightLevel"].as_f64()), (Some(0.1f32 as f64), Some(0.5))); + run(&mut s, "view.3d", json!({"heightScale": 9.0, "heightLevel": -3.0})); + assert_eq!((s.view3d.height_scale, s.view3d.height_level), (0.5, 0.0)); + run(&mut s, "view.3d", json!({"heightLevel": 7.0})); + assert_eq!(s.view3d.height_level, 1.0); + + run(&mut s, "view.3d.reset", json!({})); + assert_eq!(s.view3d.height_level, 0.0); +} + #[test] fn camera_prefs_bound_the_pan_and_survive_hostile_values() { use materialcraft_engine::CameraPrefs; diff --git a/crates/render/src/lib.rs b/crates/render/src/lib.rs index 4d42125f..4f853b76 100644 --- a/crates/render/src/lib.rs +++ b/crates/render/src/lib.rs @@ -9,4 +9,4 @@ pub mod ibl; pub mod preview; -pub use preview::{Lighting, Maps, Scene, Settings, builtin_mesh, pan, render, render_cancellable}; +pub use preview::{Displacement, Lighting, Maps, Relief, Scene, Settings, VIEW_TRIANGLES, builtin_mesh, pan, render, render_cancellable}; diff --git a/crates/render/src/preview.rs b/crates/render/src/preview.rs index 634ed0d6..06e494f4 100644 --- a/crates/render/src/preview.rs +++ b/crates/render/src/preview.rs @@ -1,7 +1,7 @@ //! The 3D view's renderer: one ray per pixel (plus 2×2 supersampling when idle) against the -//! scene mesh's BVH, the material's maps sampled with tiling and parallax occlusion from the -//! height output, then metallic/roughness GGX shading under image-based light (SH diffuse, -//! prefiltered specular, an analytic environment BRDF), exposure and ACES tone mapping. +//! scene mesh's BVH, the material's maps sampled with tiling, then metallic/roughness GGX shading +//! under image-based light (SH diffuse, prefiltered specular, an analytic environment BRDF), +//! exposure and ACES tone mapping. The height output displaces real geometry ([`Scene::with_relief`]). use std::collections::HashMap; use std::sync::Arc; @@ -80,37 +80,99 @@ impl Scene { Scene::new(builtin_mesh(id)) } - /// `base` subdivided to at most `max_tris` triangles and pushed along its normals by - /// `depth × (height − 0.5)` (the height map repeated `tiling` times): real silhouettes and - /// self-occlusion for offline renders. Coincident vertices (UV seams, hard edges) move - /// together, so the surface stays closed. - pub fn displaced(base: &Mesh, height: &Image, tiling: f32, depth: f32, max_tris: usize) -> Scene { + /// `base` subdivided and moved along its normals by `depth × (height − level)`; vertices at one spot move together so it stays closed. + pub fn displaced(base: &Mesh, height: &Image, displacement: &Displacement) -> Scene { let mut mesh = base.clone(); if mesh.normals.len() != mesh.positions.len() { mesh.compute_normals(); } - while mesh.triangle_count() > 0 && mesh.triangle_count() * 4 <= max_tris { + while mesh.triangle_count() > 0 && mesh.triangle_count() * 4 <= displacement.max_triangles { mesh = mesh.subdivided(); } - // Pre-filtered so fine detail (left to the normal map) does not spike the silhouette. + + // Pre-filtered so detail finer than the mesh (left to the normal map) does not spike the silhouette let height = height.resize(height.w.min(512), height.h.min(512), true); - let key = |p: Vec3| (p * 1e4).round().as_ivec3().to_array(); - let mut welded: HashMap<[i32; 3], (Vec3, f32, f32)> = HashMap::new(); - for ((p, n), uv) in mesh.positions.iter().zip(&mesh.normals).zip(&mesh.uvs) { - let e = welded.entry(key(*p)).or_default(); - e.0 += *n; - e.1 += height.sample_gray(uv.x * tiling, uv.y * tiling, true); - e.2 += 1.0; + let level = if displacement.level.is_finite() { displacement.level.clamp(0.0, 1.0) } else { 0.0 }; + let depth = if displacement.depth.is_finite() { displacement.depth } else { 0.0 }; + let tiling = if displacement.tiling.is_finite() { displacement.tiling.max(0.01) } else { 1.0 }; + + // Vertices at the same spot (to 0.1 mm) are one point of the surface + let spots: Vec<[i32; 3]> = mesh.positions.iter().map(|p| (*p * 1e4).round().as_ivec3().to_array()).collect(); + let mut spot_sums: HashMap<[i32; 3], (Vec3, f32, f32)> = HashMap::new(); + for ((spot, n), uv) in spots.iter().zip(&mesh.normals).zip(&mesh.uvs) { + let (normal_sum, height_sum, count) = spot_sums.entry(*spot).or_default(); + *normal_sum += *n; + *height_sum += height.sample_gray(uv.x * tiling, uv.y * tiling, true); + *count += 1.0; } - for p in &mut mesh.positions { - if let Some((n, h, count)) = welded.get(&key(*p)) { - *p += n.normalize_or_zero() * depth * (h / count - 0.5); + let offsets: Vec = + spots.iter().map(|spot| spot_sums.get(spot).map_or(Vec3::ZERO, |(n, h, count)| n.normalize_or_zero() * depth * (h / count - level))).collect(); + + if displacement.shade_relief { + // Normals of the displaced surface, shared per spot so seams don't show + let moved = |i: u32| mesh.positions.get(i as usize).zip(offsets.get(i as usize)).map(|(p, o)| *p + *o); + let mut face_sums: HashMap<[i32; 3], Vec3> = HashMap::new(); + for triangle in mesh.indices.chunks_exact(3) { + let (Some(a), Some(b), Some(c)) = (moved(triangle[0]), moved(triangle[1]), moved(triangle[2])) else { continue }; + let face = (b - a).cross(c - a); + for spot in triangle.iter().filter_map(|&i| spots.get(i as usize)) { + *face_sums.entry(*spot).or_default() += face; + } } + for (spot, n) in spots.iter().zip(mesh.normals.iter_mut()) { + if let Some(sum) = face_sums.get(spot).and_then(|s| s.try_normalize()) { + *n = sum; + } + } + mesh.tangents.clear(); + } + + for (p, offset) in mesh.positions.iter_mut().zip(&offsets) { + *p += *offset; } Scene::new(mesh) } + + /// The scene the 3D view shows for `maps`: displaced by the height output, or `None` when nothing moves. + pub fn with_relief(&self, maps: &Maps, relief: Relief, tiling: f32, max_triangles: usize) -> Option { + let height = maps.height.as_ref()?; + if !(relief.depth.is_finite() && relief.depth > 0.0) { + return None; + } + + // Without a normal map the displaced surface's own normals show the relief + let displacement = Displacement { depth: relief.depth * self.radius, level: relief.level, tiling, max_triangles, shade_relief: maps.normal.is_none() }; + Some(Scene::displaced(&self.mesh, height, &displacement)) + } } +/// How the height output shapes the 3D view's mesh. +#[derive(Clone, Copy, Debug, PartialEq)] +pub struct Relief { + /// How far white rises above black, in scene radii; 0 = off. + pub depth: f32, + /// The height (0..1) that stays on the original surface: 0 = everything rises out of it. + pub level: f32, +} + +/// The parameters of [`Scene::displaced`]. +#[derive(Clone, Copy, Debug, PartialEq)] +pub struct Displacement { + /// How far white rises above black, in world units. + pub depth: f32, + /// The height (0..1) that stays on the original surface. + pub level: f32, + /// UV repeats of the height map. + pub tiling: f32, + /// Subdivide while one more step stays within this many triangles. + pub max_triangles: usize, + /// Shade with the displaced surface's normals instead of the original ones. + pub shade_relief: bool, +} + +/// Triangle budget of a displaced scene in the interactive 3D view (builds in about 0.2–0.3 s on two cores). +pub const VIEW_TRIANGLES: usize = 500_000; + /// A built-in mesh by id; unknown ids give the rounded cube. pub fn builtin_mesh(id: &str) -> Mesh { let mut m = materialcraft_geom::primitives::builtin(id).unwrap_or_else(|| materialcraft_geom::primitives::rounded_box(Vec3::ONE, 0.15)); @@ -171,8 +233,6 @@ pub struct Settings { pub exposure: f32, /// Degrees. pub env_rotation: f32, - /// Parallax depth in UV units (0 = off). - pub height_scale: f32, /// Show the (blurred) environment behind the mesh instead of the flat backdrop. pub show_env: bool, /// 1 = one ray per pixel, 2 = 2×2 supersampling. @@ -199,7 +259,6 @@ impl Default for Settings { tiling: 1.0, exposure: 0.0, env_rotation: 0.0, - height_scale: 0.03, show_env: false, supersample: 1, ao_rays: 0, @@ -346,36 +405,8 @@ fn shade(scene: &Scene, maps: &Maps, light: &Lighting, s: &Settings, origin: Vec let tan = (tan - nrm * nrm.dot(tan)).normalize_or_zero(); let bit = nrm.cross(tan) * sign; let uv0 = *m.uvs.get(i0)? * w0 + *m.uvs.get(i1)? * w1 + *m.uvs.get(i2)? * w2; - let mut uv = uv0 * s.tiling; + let uv = uv0 * s.tiling; let v = -dir; - // Parallax occlusion: march the height field along the view direction in tangent space. - if s.height_scale > 0.0 - && let Some(h) = &maps.height - { - let vt = Vec3::new(v.dot(tan), v.dot(bit), v.dot(nrm).max(0.05)); - let steps = 32; - let delta = Vec2::new(vt.x, -vt.y) / vt.z * s.height_scale * s.tiling / steps as f32; - let mut layer = 1.0; - let mut cur = uv; - let mut prev_h = h.sample_gray(cur.x, cur.y, true); - let mut prev_layer = layer; - for _ in 0..steps { - let hv = h.sample_gray(cur.x, cur.y, true); - if hv >= layer { - // Linear refinement between the last two samples. - let a = prev_h - prev_layer; - let b = hv - layer; - let t = if (b - a).abs() > 1e-6 { a / (a - b) } else { 0.0 }; - cur -= delta * (1.0 - t.clamp(0.0, 1.0)); - break; - } - prev_h = hv; - prev_layer = layer; - layer -= 1.0 / steps as f32; - cur -= delta; - } - uv = cur; - } let a = alpha(maps, uv); if s.alpha_view { return Some(Shaded { color: Vec3::splat(a), alpha: 1.0, t: hit.t }); @@ -566,6 +597,80 @@ mod tests { assert_eq!(&px[c..c + 3], &[255, 255, 255]); } + fn flat(value: f32) -> Image { + Image::filled(8, 8, Kind::Gray, [value; 4]) + } + + fn displacement(depth: f32, level: f32) -> Displacement { + Displacement { depth, level, tiling: 1.0, max_triangles: 2048, shade_relief: false } + } + + /// Heights of a displaced plane's vertices (it faces +y and starts at y = 0). + fn plane_heights(height: &Image, displacement: &Displacement) -> Vec { + let plane = materialcraft_geom::primitives::plane(2.0, 4); + Scene::displaced(&plane, height, displacement).mesh.positions.iter().map(|p| p.y).collect() + } + + /// At level 0 the relief rises out of the surface: black stays on it and nothing sinks in. + #[test] + fn the_relief_rises_out_of_the_surface() { + let near = |heights: Vec, expected: f32| heights.iter().all(|y| (y - expected).abs() < 1e-5); + + assert!(near(plane_heights(&flat(0.0), &displacement(0.2, 0.0)), 0.0), "black stays on the surface"); + assert!(near(plane_heights(&flat(1.0), &displacement(0.2, 0.0)), 0.2), "white rises by the depth"); + assert!(near(plane_heights(&flat(0.5), &displacement(0.2, 0.5)), 0.0), "the level height stays on the surface"); + assert!(near(plane_heights(&flat(0.0), &displacement(0.2, 0.5)), -0.1), "below the level sinks"); + assert!(near(plane_heights(&flat(1.0), &displacement(0.2, f32::NAN)), 0.2), "a broken level reads as 0"); + } + + /// Vertices at one spot (UV seams, hard edges) move together, so a displaced cube stays closed. + #[test] + fn a_displaced_cube_stays_closed() { + // No subdivision, so vertex i of the result is vertex i of the cube + let cube = builtin_mesh("cube"); + let ramp = Image::gray(32, 32, |x, y| ((x + y) % 32) as f32 / 31.0); + let displaced = Scene::displaced(&cube, &ramp, &Displacement { max_triangles: 0, ..displacement(0.1, 0.0) }); + assert_eq!(displaced.mesh.positions.len(), cube.positions.len()); + + let spot = |p: Vec3| (p * 1e4).round().as_ivec3().to_array(); + let mut moved_to: HashMap<[i32; 3], Vec3> = HashMap::new(); + for (before, after) in cube.positions.iter().zip(&displaced.mesh.positions) { + let first = *moved_to.entry(spot(*before)).or_insert(*after); + assert!((first - *after).length() < 1e-4, "{before:?} split into {first:?} and {after:?}"); + } + } + + /// Without a normal map the displaced surface's own normals shade the relief; with one, the original normals stay. + #[test] + fn relief_normals_follow_the_displaced_surface_only_when_asked() { + let plane = materialcraft_geom::primitives::plane(2.0, 8); + let slope = Image::gray(16, 16, |x, _| x as f32 / 15.0); + let tilted = |shade_relief| { + let scene = Scene::displaced(&plane, &slope, &Displacement { shade_relief, ..displacement(0.5, 0.0) }); + scene.mesh.normals.iter().map(|n| n.x.abs()).fold(0.0f32, f32::max) + }; + + assert!(tilted(true) > 0.1, "a slope tilts the normals"); + assert!(tilted(false) < 1e-5, "the original normals are kept"); + } + + #[test] + fn with_relief_needs_a_height_output_and_a_depth() { + let scene = Scene::builtin("plane"); + let maps = Maps { height: Some(flat(1.0)), ..Maps::default() }; + let relief = Relief { depth: 0.1, level: 0.0 }; + + assert!(scene.with_relief(&Maps::default(), relief, 1.0, 2048).is_none()); + for depth in [0.0, -1.0, f32::NAN] { + assert!(scene.with_relief(&maps, Relief { depth, ..relief }, 1.0, 2048).is_none(), "{depth}"); + } + + // The depth is in scene radii + let raised = scene.with_relief(&maps, relief, 1.0, 2048).unwrap(); + let top = raised.mesh.positions.iter().map(|p| p.y).fold(f32::MIN, f32::max); + assert!((top - 0.1 * scene.radius).abs() < 1e-4, "{top} vs {}", 0.1 * scene.radius); + } + #[test] fn a_cancelled_render_gives_up_and_an_uncancelled_one_matches_render() { let (scene, light, maps, s) = (Scene::builtin("sphere"), Lighting::new("studio"), Maps::default(), Settings::default()); diff --git a/crates/ui-egui/src/view3d.rs b/crates/ui-egui/src/view3d.rs index 3b517248..e57d4017 100644 --- a/crates/ui-egui/src/view3d.rs +++ b/crates/ui-egui/src/view3d.rs @@ -7,6 +7,8 @@ //! (a panel, divider or window drag changes the size on every step), then renders on a worker //! thread so the UI never waits for it; until it lands the last frame stays up, kept in proportion. //! A frame that is no longer wanted is cancelled. The browser has no threads and renders here. +//! +//! The height output raises the mesh for real ([`Scene::with_relief`]), built on a worker thread and cached until its inputs change. use std::sync::Arc; use std::sync::atomic::{AtomicBool, Ordering}; @@ -16,7 +18,7 @@ use std::time::Duration; use egui::{Color32, ColorImage, Rect, Sense, TextureHandle, TextureOptions, Ui, pos2, vec2}; use egui_phosphor::regular as icon; use materialcraft_engine::view_cmds::{ENVIRONMENTS, SCENES}; -use materialcraft_render::{Lighting, Maps, Scene, Settings}; +use materialcraft_render::{Lighting, Maps, Relief, Scene, Settings}; use serde_json::json; use crate::MaterialCraftApp; @@ -26,9 +28,16 @@ use crate::theme::Tokens; /// Seconds the view's size and the camera rest before the full-quality frame renders. pub const SETTLE: f64 = 0.15; +/// Triangle budget of the displaced mesh; the browser builds it on the UI thread, so it gets a smaller one. +const RELIEF_TRIANGLES: usize = if cfg!(target_arch = "wasm32") { 120_000 } else { materialcraft_render::VIEW_TRIANGLES }; + #[derive(Default)] pub struct View3dState { scene: Option<(String, Arc)>, + /// The scene displaced by the height output, keyed by what it was built from (see [`relief_key`]). + displaced: Option<(u64, Arc)>, + /// The displaced scene building on a worker thread. + relief_job: Option, light: Option>, tex: Option, /// What the texture shows: (content key, full quality). @@ -79,6 +88,13 @@ impl Drop for Job { } } +/// A displaced scene building on a worker thread (`None` arrives when nothing moves). +#[cfg_attr(target_arch = "wasm32", allow(dead_code))] +struct ReliefJob { + key: u64, + rx: Receiver>>, +} + pub fn scene_label(app: &MaterialCraftApp) -> String { let id = &app.session.view3d.scene; if id == "custom" @@ -153,9 +169,13 @@ fn menus(app: &mut MaterialCraftApp, ui: &mut Ui) { } }); ui.menu_button(tr("Renderer"), |ui| { - let mut h = app.session.view3d.height_scale * 100.0; - if crate::widgets::slider(ui, tr("Height (parallax) depth"), &mut h, 0.0..=10.0, 2).changed() { - app.run("view.3d", json!({"heightScale": h / 100.0})); + let mut depth_percent = app.session.view3d.height_scale * 100.0; + if crate::widgets::slider(ui, tr("Height depth (% of the mesh size)"), &mut depth_percent, 0.0..=20.0, 1).changed() { + app.run("view.3d", json!({"heightScale": depth_percent / 100.0})); + } + let mut level = app.session.view3d.height_level; + if crate::widgets::slider(ui, tr("Height level (0 = rises out of the surface)"), &mut level, 0.0..=1.0, 2).changed() { + app.run("view.3d", json!({"heightLevel": level})); } let mut t = app.session.view3d.tiling; if crate::widgets::slider(ui, tr("Tiling"), &mut t, 0.25..=8.0, 2).changed() { @@ -273,12 +293,12 @@ fn frame_rect(rect: Rect, rendered: Option<(u32, u32)>) -> Rect { } } -fn content_key(app: &MaterialCraftApp, w: u32, h: u32, show_env: bool) -> u64 { +fn content_key(app: &MaterialCraftApp, w: u32, h: u32, show_env: bool, relief_shown: Option) -> u64 { use std::hash::{DefaultHasher, Hash, Hasher}; let mut hs = DefaultHasher::new(); let v = &app.session.view3d; - (w, h, show_env, &v.scene, &v.environment, app.session.custom_mesh.as_ref().map(|(n, _)| n), v.transparency, v.alpha_view).hash(&mut hs); - for f in [v.yaw, v.pitch, v.distance, v.target[0], v.target[1], v.target[2], v.tiling, v.exposure, v.env_rotation, v.height_scale] { + (w, h, show_env, &v.scene, &v.environment, app.session.custom_mesh.as_ref().map(|(n, _)| n), v.transparency, v.alpha_view, relief_shown).hash(&mut hs); + for f in [v.yaw, v.pitch, v.distance, v.target[0], v.target[1], v.target[2], v.tiling, v.exposure, v.env_rotation, v.height_scale, v.height_level] { f.to_bits().hash(&mut hs); } if let Ok(g) = app.session.graph() { @@ -298,7 +318,8 @@ fn render(app: &mut MaterialCraftApp, ctx: &egui::Context, rect: Rect, moving: b app.view3d.changed_at = Some(now); } app.view3d.size = Some(size); - let key = content_key(app, size.0, size.1, app.view3d.show_env); + let relief_shown = update_relief(app, ctx); + let key = content_key(app, size.0, size.1, app.view3d.show_env, relief_shown); collect(app, ctx, key); if app.view3d.key == Some((key, true)) || (moving && app.view3d.key == Some((key, false))) { return; @@ -338,23 +359,110 @@ fn collect(app: &mut MaterialCraftApp, ctx: &egui::Context, key: u64) { } } -/// The scene, lighting, maps and settings of the current view (scene and lighting are cached). -fn inputs(app: &mut MaterialCraftApp, supersample: u32) -> Option<(Arc, Arc, Maps, Settings)> { - let v = app.session.view3d.clone(); +/// The plain scene of the current view and its cache key, building it when the scene changed. +fn base_scene(app: &mut MaterialCraftApp) -> (String, Arc) { + let v = &app.session.view3d; let scene_key = match (&*v.scene, &app.session.custom_mesh) { ("custom", Some((name, _))) => format!("custom:{name}"), _ => v.scene.clone(), }; - if app.view3d.scene.as_ref().is_none_or(|(id, _)| *id != scene_key) { - let scene = match (&*v.scene, &app.session.custom_mesh) { - ("custom", Some((_, mesh))) => Scene::new((**mesh).clone()), - _ => Scene::builtin(&v.scene), - }; - app.view3d.scene = Some((scene_key, Arc::new(scene))); + + match &app.view3d.scene { + Some((key, scene)) if *key == scene_key => (scene_key, scene.clone()), + _ => { + let scene = match (&*v.scene, &app.session.custom_mesh) { + ("custom", Some((_, mesh))) => Scene::new((**mesh).clone()), + _ => Scene::builtin(&v.scene), + }; + let scene = Arc::new(scene); + app.view3d.scene = Some((scene_key.clone(), scene.clone())); + (scene_key, scene) + } } +} + +/// What the displaced scene depends on (scene, height output cook, relief settings, normal map); `None` when nothing is raised. +fn relief_key(app: &MaterialCraftApp, scene_key: &str, maps: &Maps) -> Option { + use std::hash::{DefaultHasher, Hash, Hasher}; + + let v = &app.session.view3d; + if maps.height.is_none() || v.height_scale <= 0.0 { + return None; + } + + let graph = app.session.graph().ok()?; + let height_output = materialcraft_engine::eval::outputs(graph, &app.session.cooked).into_iter().find(|(_, usage, _, _)| *usage == "height"); + let height_cook = height_output.and_then(|(id, _, _, _)| app.session.cooked.nodes.get(&id).map(|r| r.key)); + + let mut hasher = DefaultHasher::new(); + (scene_key, height_cook, maps.normal.is_some()).hash(&mut hasher); + for f in [v.height_scale, v.height_level, v.tiling] { + f.to_bits().hash(&mut hasher); + } + Some(hasher.finish()) +} + +/// Collect a finished relief build or start a missing one; returns the key of the displaced scene shown (`None` = plain mesh). +fn update_relief(app: &mut MaterialCraftApp, ctx: &egui::Context) -> Option { + let (scene_key, base) = base_scene(app); + let maps = Maps::from_usages(app.session.material_maps()); + let wanted = relief_key(app, &scene_key, &maps)?; + + if let Some(job) = app.view3d.relief_job.take() { + match job.rx.try_recv() { + Ok(Some(scene)) => app.view3d.displaced = Some((job.key, scene)), + Ok(None) | Err(TryRecvError::Disconnected) => {} + Err(TryRecvError::Empty) if job.key == wanted => app.view3d.relief_job = Some(job), + // An outdated build is dropped; its thread finishes and its result goes nowhere + Err(TryRecvError::Empty) => {} + } + } + + if app.view3d.displaced.as_ref().is_some_and(|(key, _)| *key == wanted) { + return Some(wanted); + } + if app.view3d.relief_job.is_none() { + let v = &app.session.view3d; + let relief = Relief { depth: v.height_scale, level: v.height_level }; + start_relief(app, ctx, wanted, base, maps, relief, v.tiling); + } + None +} + +/// Build the displaced scene on a worker thread. +#[cfg(not(target_arch = "wasm32"))] +fn start_relief(app: &mut MaterialCraftApp, ctx: &egui::Context, key: u64, base: Arc, maps: Maps, relief: Relief, tiling: f32) { + let (tx, rx) = std::sync::mpsc::channel(); + let (repaint, viewport) = (ctx.clone(), ctx.viewport_id()); + let (thread_base, thread_maps) = (base.clone(), maps.clone()); + let spawned = std::thread::Builder::new().name("materialcraft-relief".into()).spawn(move || { + let _ = tx.send(thread_base.with_relief(&thread_maps, relief, tiling, RELIEF_TRIANGLES).map(Arc::new)); + repaint.request_repaint_of(viewport); + }); + + match spawned { + Ok(_) => app.view3d.relief_job = Some(ReliefJob { key, rx }), + Err(e) => { + log::warn!("could not start a 3D view relief thread ({e}); building it here"); + app.view3d.displaced = base.with_relief(&maps, relief, tiling, RELIEF_TRIANGLES).map(|scene| (key, Arc::new(scene))); + } + } +} + +/// The browser has no threads: the displaced scene builds here (the page pauses). +#[cfg(target_arch = "wasm32")] +fn start_relief(app: &mut MaterialCraftApp, _ctx: &egui::Context, key: u64, base: Arc, maps: Maps, relief: Relief, tiling: f32) { + app.view3d.displaced = base.with_relief(&maps, relief, tiling, RELIEF_TRIANGLES).map(|scene| (key, Arc::new(scene))); +} + +/// The scene, lighting, maps and settings of the current view: the displaced scene when it is current, else the plain one. +fn inputs(app: &mut MaterialCraftApp, supersample: u32) -> Option<(Arc, Arc, Maps, Settings)> { + let (scene_key, base) = base_scene(app); + let v = app.session.view3d.clone(); if app.view3d.light.as_ref().is_none_or(|l| l.name != v.environment) { app.view3d.light = Some(Arc::new(Lighting::new(&v.environment))); } + let settings = Settings { yaw: v.yaw, pitch: v.pitch, @@ -363,7 +471,6 @@ fn inputs(app: &mut MaterialCraftApp, supersample: u32) -> Option<(Arc, A tiling: v.tiling, exposure: v.exposure, env_rotation: v.env_rotation, - height_scale: v.height_scale, show_env: app.view3d.show_env, supersample, transparency: v.transparency, @@ -371,8 +478,13 @@ fn inputs(app: &mut MaterialCraftApp, supersample: u32) -> Option<(Arc, A ..Settings::default() }; let maps = Maps::from_usages(app.session.material_maps()); - let (Some((_, scene)), Some(light)) = (&app.view3d.scene, &app.view3d.light) else { return None }; - Some((scene.clone(), light.clone(), maps, settings)) + let wanted = relief_key(app, &scene_key, &maps); + let scene = match &app.view3d.displaced { + Some((key, displaced)) if Some(*key) == wanted => displaced.clone(), + _ => base, + }; + let light = app.view3d.light.clone()?; + Some((scene, light, maps, settings)) } /// Texture pixels for `rect` at `scale` pixels per point. diff --git a/crates/ui-egui/src/windows.rs b/crates/ui-egui/src/windows.rs index 13ee6b82..eae6ea4f 100644 --- a/crates/ui-egui/src/windows.rs +++ b/crates/ui-egui/src/windows.rs @@ -28,7 +28,7 @@ const PREVIEW: u32 = 96; fn render_templates() -> crate::thumbs::Previews { let light = materialcraft_render::Lighting::new("studio"); let scene = materialcraft_render::Scene::builtin("sphere"); - let settings = materialcraft_render::Settings { distance: 2.7, supersample: 2, height_scale: 0.0, ..Default::default() }; + let settings = materialcraft_render::Settings { distance: 2.7, supersample: 2, ..Default::default() }; materialcraft_engine::samples::TEMPLATES .iter() .map(|(id, _)| { diff --git a/docs/architecture.md b/docs/architecture.md index 96f8b9e6..f091578b 100644 --- a/docs/architecture.md +++ b/docs/architecture.md @@ -23,7 +23,7 @@ L2 formats .sbs packages (the main format, sbs.rs), .mcraft packages (zip: pa decode, texture encode (PNG/JPEG/TGA/TIFF/BMP/WEBP/EXR/HDR at 8/16/32 bits), atomic writes L3 engine Session (package, open graph, selection, 2D/3D view state, snapshot undo, cache), the command registry, inspect, sample materials and graph templates -L3 render the 3D view: BVH ray casts, parallax occlusion from the height output, GGX PBR with +L3 render the 3D view: BVH ray casts, the height output displacing a subdivided mesh, GGX PBR with prefiltered IBL + SH diffuse, alpha transparency (layered ray compositing) and an alpha channel view, ACES tone mapping; procedural environments L4 automation MCP server (rmcp), JSON-lines RPC (stdio/TCP with token), bridge client, workspace sandbox diff --git a/docs/control-protocol.md b/docs/control-protocol.md index cdb0a2f7..f23e4183 100644 --- a/docs/control-protocol.md +++ b/docs/control-protocol.md @@ -70,7 +70,7 @@ Types: `move`, `down`, `up`, `click`, `doubleClick`, `drag`, `scroll`, `key` (eg | `graph.node.function` | `{id?, param, function}` drives a parameter by a function graph of the graph's inputs (dynamic parameter); `{id?, param, remove: true}` removes it | | `graph.preset.save` / `.apply` / `.delete` | `{name}`: store, restore or remove the current input values | | `graph.createFromSelection` | `{name?, ids?}`: move nodes into a sub-graph and replace them with an instance | -| `view.2d` / `view.3d` | which node the 2D view shows, channel, tiling, histogram; scene, environment, camera, tiling, parallax depth, `transparency` (see through where the alpha is below one: the opacity output, else the base color's alpha), `alphaView` (show the alpha channel) | +| `view.2d` / `view.3d` | which node the 2D view shows, channel, tiling, histogram; scene, environment, camera, tiling, `heightScale` (how far the height output raises the mesh, in mesh radii) and `heightLevel` (the height that stays on the surface; 0 = the relief rises out of it), `transparency` (see through where the alpha is below one: the opacity output, else the base color's alpha), `alphaView` (show the alpha channel) | | `view.3d.loadMesh` | `{path}` shows an OBJ, glTF or GLB mesh (scene `custom`) | | `library.list` | `{filter?, category?}`: every node with ports and parameters | diff --git a/docs/gaps.md b/docs/gaps.md index e3da2669..1427f748 100644 --- a/docs/gaps.md +++ b/docs/gaps.md @@ -7,7 +7,7 @@ Every known shortfall, most important first. Pick from the top. | # | Gap | Evidence | Impact | Estimate | Parity doc | |---:|---|---|---|---:|---| | 1 | Node library breadth | 227 nodes vs. ~400 in the reference library | Recipes that need scan processing, more grunges, splines or SDF shapes | 30 h | target-app-parity (Node library) | -| 2 | GPU 3D view with tessellation and lights | CPU renderer with parallax only | Displacement previews, light setups | 12 h | target-app-parity (3D view) | +| 2 | GPU 3D view with tessellation and lights | CPU renderer; the height output displaces a subdivided mesh (up to 500k triangles) | GPU tessellation, light setups | 12 h | target-app-parity (3D view) | | 3 | Mesh-based generators and bakers | None | Workflows that start from a mesh | 15 h | target-app-parity (Node library) | | 4 | Portable materials over MCP | `.mcmat` export runs from the app and the CLI; the MCP workspace sandbox refuses `file.*` commands and has no `material_export` tool | Sandboxed agents can't hand a material to TextureCraft | 1 h | target-app-parity (Files) | | 5 | Function loops and reusable functions | Functions live on one parameter or processor | Iterative effects; sharing logic between nodes | 5 h | target-app-parity (Function graphs) | diff --git a/docs/target-app-parity.md b/docs/target-app-parity.md index cea2a179..185d6ee3 100644 --- a/docs/target-app-parity.md +++ b/docs/target-app-parity.md @@ -14,7 +14,7 @@ automation + tests), weighted by how much of the day each area carries. **Remain | Function graphs | 10 | 70% | A compiled, 4-wide evaluator with ~55 ops (constants, $pos/$size, exposed variables, samplers, vectors, swizzles, math, logic, comparison, noise, random, if/else); pixel and value processors; a visual function editor; dynamic parameters (a function on any numeric, color, bool or enum parameter, evaluated from the graph's inputs) | Loops, function graphs as reusable package items | | Graph parameters and instances | 8 | 70% | Exposed inputs (float, int, bool, enum, color) bound to parameters of any compatible type, shown in groups, edited with one shared editor on the graph and on its instances; presets (save, apply, delete); sub-graph instances with their own inputs and outputs; graph attributes; `--set` on the CLI | Visibility conditions, per-instance output sizes, embedded vs. linked packages | | 2D view | 5 | 80% | Pan/zoom, fit and 1:1, RGBA/R/G/B/A isolation, 3×3 tiling check, histogram, pixel readout, size/format line, save image | Color picker to parameters, UV overlay | -| 3D view | 10 | 55% | Rounded cube, cube, sphere, cylinder, plane, torus and material ball; OBJ, glTF and GLB meshes; base color, normal, roughness, metallic, height (parallax occlusion), AO, emissive and opacity; alpha transparency through layered surfaces (opacity output or base color alpha) and an alpha channel view; 4 procedural environments with rotation and exposure; orbit/pan/zoom; tiling; supersampling at rest | GPU renderer with tessellation, lights, material/shader switching, path-traced renderer | +| 3D view | 10 | 55% | Rounded cube, cube, sphere, cylinder, plane, torus and material ball; OBJ, glTF and GLB meshes; base color, normal, roughness, metallic, height (real displacement of a subdivided mesh, rising out of the surface), AO, emissive and opacity; alpha transparency through layered surfaces (opacity output or base color alpha) and an alpha channel view; 4 procedural environments with rotation and exposure; orbit/pan/zoom; tiling; supersampling at rest | GPU renderer with tessellation, lights, material/shader switching, path-traced renderer | | Files | 8 | 70% | `.mcraft` packages with embedded bitmaps; `.mcmat` portable materials (cooked maps, exposed inputs, presets, input nodes, the source package) that TextureCraft paints with and re-cooks through the CLI at its own resolution, values and mesh maps; preview images for input nodes; export of every output (PNG, JPEG, TGA, TIFF, BMP, WEBP, EXR, HDR; 8/16/32 bits; name pattern; sRGB vs. linear by usage); bitmap import (PNG, JPEG, TGA, TIFF, BMP, WEBP, EXR, HDR); mesh import (OBJ, glTF, GLB); open, save, import and export in the browser; atomic writes; autosave; recent files | An MCP tool for portable materials, package dependencies, SVG and font files as resources | | UI and UX | 8 | 70% | Dockable/floatable panels (explorer, library, graph, 3D, 2D, properties, console, history), menus, main toolbar, graph toolbar with atomic quick-insert, library with live previews, properties with curve/gradient/color editors and a Levels editor over the input histogram, New graph dialog with rendered templates, export dialog, preferences (brightness, accent, scale, preview size, autosave, 3D pan limit and speed), shortcuts list, home screen at startup (samples and recent files), visual function editor, presets bar, accessible names on every widget, status bar | Translations, keymap editor, minimap, multi-graph tabs | | Platforms | 4 | 50% | Windows, macOS, Linux, FreeBSD and web builds compile; browser file I/O; packaging scripts and release workflows | First release run | diff --git a/docs/wires-and-alpha.md b/docs/wires-and-alpha.md index 685234fe..00a3fdcf 100644 --- a/docs/wires-and-alpha.md +++ b/docs/wires-and-alpha.md @@ -106,7 +106,7 @@ Where the alpha is below one, the surface lets light through: each camera ray co surfaces it meets front to back (`color × alpha`, the rest passes on) through up to eight layers, then shows what lies behind: the backdrop, or the environment when **Display ▸ Environment background** is on. Back faces seen through a clear front are shaded facing the viewer, so a -cut-out sphere shows its inside. Parallax from the height output applies to every layer. +cut-out sphere shows its inside. Every layer is the mesh as the height output displaced it. **Display ▸ Transparency (alpha)** turns this off, so the alpha is ignored and the mesh is opaque. It is on by default.