diff --git a/crates/automation/src/render.rs b/crates/automation/src/render.rs index c12ce621..024e183a 100644 --- a/crates/automation/src/render.rs +++ b/crates/automation/src/render.rs @@ -162,7 +162,12 @@ fn trace_inputs(s: &mut Session) -> (TraceScene, TraceDisplay) { .texture_sets .iter() .zip(&s.caches) - .map(|(ts, c)| TraceSet { material: ts.material, composite: c.composite.clone(), height_strength: ts.atlas_height_strength() }) + .map(|(ts, c)| TraceSet { + material: ts.material, + composite: c.composite.clone(), + height_strength: ts.atlas_height_strength(), + height_in_normal: ts.height_in_normal(), + }) .collect(); let d = &s.doc.project.display; let env_image = d.environment_resource().and_then(|n| s.images.get(n)); @@ -199,6 +204,7 @@ pub fn shade(s: &Session) -> Shade { }; Shade { height_strength: s.doc.project.texture_sets.get(s.ts()).map(|t| t.atlas_height_strength()).unwrap_or(1.0), + height_in_normal: s.doc.project.texture_sets.get(s.ts()).is_none_or(|t| t.height_in_normal()), view_mode, channel, // Only the 2D view uses this default diff --git a/crates/core/src/project.rs b/crates/core/src/project.rs index 4212d787..b0d8d846 100644 --- a/crates/core/src/project.rs +++ b/crates/core/src/project.rs @@ -193,6 +193,11 @@ impl TextureSet { self.height_strength / self.tile_grid().map_or(1.0, |g| g.cols as f32) } + /// Whether the height slope joins the shaded normal ([`NormalMixing::Replace`] leaves it out) + pub fn height_in_normal(&self) -> bool { + self.normal_mixing == NormalMixing::Combine + } + /// Texels across and down: [`TextureSet::block_resolution`] per block of the atlas grid. pub fn size(&self) -> (u32, u32) { let (cols, rows) = self.tile_grid().map_or((1, 1), |g| (g.cols, g.rows)); diff --git a/crates/engine/src/inspect.rs b/crates/engine/src/inspect.rs index 14863420..421aec82 100644 --- a/crates/engine/src/inspect.rs +++ b/crates/engine/src/inspect.rs @@ -274,6 +274,10 @@ pub fn texture_set(session: &Session, index: usize) -> Value { "parts": crate::set_cmds::parts(session, index), "baked": crate::project_cmds::baked_json(session.doc.baked.get(&index)), "visible": texture_set.visible, + "normalMixing": match texture_set.normal_mixing { + texturecraft_core::NormalMixing::Combine => "combine", + texturecraft_core::NormalMixing::Replace => "replace", + }, "active": index == session.ts(), }) } diff --git a/crates/engine/src/set_cmds.rs b/crates/engine/src/set_cmds.rs index 2251a182..5fa7fd49 100644 --- a/crates/engine/src/set_cmds.rs +++ b/crates/engine/src/set_cmds.rs @@ -1,7 +1,7 @@ //! Texture set commands (Texture Set List / Texture Set Settings). use serde_json::{Value, json}; -use texturecraft_core::{Channel, ChannelBlend, ChannelFormat}; +use texturecraft_core::{Channel, ChannelBlend, ChannelFormat, NormalMixing}; use std::sync::Arc; @@ -38,7 +38,15 @@ pub fn specs() -> Vec { visibility ), cmd!("textureSet.rename", "Rename texture set", [], None, "{ts?, name}", always, rename), - cmd!("textureSet.settings", "Texture set settings", [], None, "{ts?, description?, heightStrength?, normalFormat?: openGl|directX}", always, settings), + cmd!( + "textureSet.settings", + "Texture set settings", + [], + None, + "{ts?, description?, heightStrength?, normalMixing?: combine|replace, normalFormat?: openGl|directX}", + always, + settings + ), cmd!( "textureSet.parts", "List mesh parts", @@ -281,6 +289,12 @@ fn rename(s: &mut Session, p: &Value) -> Result { fn settings(s: &mut Session, p: &Value) -> Result { let ts = ts_param(s, p, "textureSet.settings")?; let nf = normal_format_param("textureSet.settings", p)?; + let normal_mixing = match strp(p, "normalMixing") { + None => None, + Some("combine") => Some(NormalMixing::Combine), + Some("replace") => Some(NormalMixing::Replace), + Some(other) => return Err(bad("textureSet.settings", format!("unknown normal mixing {other:?} (combine or replace)"))), + }; s.edit("Texture set settings", |s| { if let Some(n) = nf { s.doc.project.normal_format = n; @@ -292,6 +306,9 @@ fn settings(s: &mut Session, p: &Value) -> Result { if let Some(h) = f32p(p, "heightStrength") { set.height_strength = h.clamp(0.0, 100.0); } + if let Some(mixing) = normal_mixing { + set.normal_mixing = mixing; + } Ok(()) })?; Ok(Value::Null) @@ -314,4 +331,19 @@ mod tests { assert_eq!(run(json!({"mode": "showAll"})).unwrap(), json!([true, true])); assert!(run(json!({"mode": "sideways"})).is_err() && run(json!({"mode": "solo", "ts": 9})).is_err()); } + + #[test] + fn normal_mixing_replace_keeps_height_out_of_the_normal_and_undoes() { + let mut s = Session::new_project("t", texturecraft_geom::primitives::material_ball(), "builtin:material_ball", None, 128).unwrap(); + let mixing = |s: &Session| crate::inspect::texture_set(s, 0)["normalMixing"].clone(); + assert_eq!(mixing(&s), json!("combine")); + + crate::execute(&mut s, "textureSet.settings", &json!({"ts": 0, "normalMixing": "replace"})).unwrap(); + assert_eq!(mixing(&s), json!("replace")); + assert!(!s.doc.project.texture_sets[0].height_in_normal() && s.doc.project.texture_sets[1].height_in_normal()); + assert!(crate::execute(&mut s, "textureSet.settings", &json!({"normalMixing": "blend"})).is_err()); + + crate::execute(&mut s, "edit.undo", &Value::Null).unwrap(); + assert_eq!(mixing(&s), json!("combine")); + } } diff --git a/crates/formats/src/export/mod.rs b/crates/formats/src/export/mod.rs index f2134a0c..17086f28 100644 --- a/crates/formats/src/export/mod.rs +++ b/crates/formats/src/export/mod.rs @@ -19,7 +19,7 @@ use craft_image_codecs::{ChannelLayout, EncodeOptions, Format as CodecFormat, Im use rayon::prelude::*; use serde::{Deserialize, Serialize}; use texturecraft_compose::{BakedMaps, Composite}; -use texturecraft_core::{AoMixing, BakedMap, BlockScales, Channel, ChannelKind, NormalFormat, NormalMixing, Project, TextureSet}; +use texturecraft_core::{AoMixing, BakedMap, BlockScales, Channel, ChannelKind, NormalFormat, Project, TextureSet}; use texturecraft_geom::glam::Vec3; use texturecraft_texel::{ColorSpace, DilationMap, linear_to_srgb}; @@ -826,7 +826,7 @@ impl Sampler<'_> { let At::Texel(x, y) = at else { return Vec3::Z }; let base = if self.set.baked.contains(&BakedMap::Normal) { unpack(self.baked(BakedMap::Normal, at)) } else { Vec3::Z }; let mut detail = if self.set.has_channel(Channel::Normal) { unpack(self.channel(Channel::Normal, at)) } else { Vec3::Z }; - if self.set.normal_mixing == NormalMixing::Combine && self.set.has_channel(Channel::Height) && self.set.height_strength != 0.0 { + if self.set.height_in_normal() && self.set.has_channel(Channel::Height) && self.set.height_strength != 0.0 { detail = rnm(self.height_normal(x, y), detail); } rnm(base, detail) diff --git a/crates/render/src/displace.rs b/crates/render/src/displace.rs index f2e2b19a..1ebed5dc 100644 --- a/crates/render/src/displace.rs +++ b/crates/render/src/displace.rs @@ -141,7 +141,7 @@ mod tests { img.tile_mut(x, y, &[texturecraft_texel::to_u16_signed(height)]); } } - TraceSet { material: 0, composite, height_strength: strength } + TraceSet { material: 0, composite, height_strength: strength, height_in_normal: true } } #[test] diff --git a/crates/render/src/gpu_trace.rs b/crates/render/src/gpu_trace.rs index 5b04af34..5778d88a 100644 --- a/crates/render/src/gpu_trace.rs +++ b/crates/render/src/gpu_trace.rs @@ -416,7 +416,7 @@ impl GpuTracer { sigma: scene.scatter_sigma, rotation: scene.env_rotation, env_camera: scene.env_camera, - heights: scene.sets.iter().map(|s| s.height_strength).collect(), + heights: scene.sets.iter().map(crate::trace::TraceSet::normal_height_strength).collect(), ior: scene.ior, lens: scene.lens.map_or([0.0; 2], |[focus, aperture]| [focus, aperture.max(0.0) * scene.radius]), }); @@ -826,7 +826,7 @@ mod tests { } let mesh = Arc::new(primitives::sphere(1.0, 32, 16)); let bvh = Arc::new(Bvh::new(&mesh)); - TraceScene::new(mesh, bvh, vec![TraceSet { material: 0, composite, height_strength: 0.0 }], Arc::new(env), 0.0) + TraceScene::new(mesh, bvh, vec![TraceSet { material: 0, composite, height_strength: 0.0, height_in_normal: true }], Arc::new(env), 0.0) } fn gpu() -> Option<(Headless, GpuTracer)> { @@ -1006,7 +1006,7 @@ mod tests { let mesh = Arc::new(primitives::sphere(1.0, 32, 16)); let bvh = Arc::new(Bvh::new(&mesh)); let env = crate::ibl::environment("Studio Contrast", 256); - let scene = TraceScene::new(mesh, bvh, vec![TraceSet { material: 0, composite, height_strength: 0.0 }], Arc::new(env), 0.0); + let scene = TraceScene::new(mesh, bvh, vec![TraceSet { material: 0, composite, height_strength: 0.0, height_in_normal: true }], Arc::new(env), 0.0); let d = TraceDisplay { exposure: 1.0, aces: true, env_opacity: 0.5, denoise: false, background: crate::DEFAULT_BACKGROUND }; let settings = TraceSettings { bounces: 4 }; let (_, _, gpu) = t.render(&h.device, &h.queue, &h.renderer, &scene, &camera(), &settings, &d, [48, 36], 1024).unwrap(); diff --git a/crates/render/src/renderer.rs b/crates/render/src/renderer.rs index 0fd677bf..fea99716 100644 --- a/crates/render/src/renderer.rs +++ b/crates/render/src/renderer.rs @@ -157,6 +157,8 @@ pub struct Shade { pub env_opacity: f32, pub ao_intensity: f32, pub height_strength: f32, + /// The height slope joins the shaded normal (normal mixing Combine; Replace leaves it out) + pub height_in_normal: bool, /// -1 for DirectX normal maps in the normal channel, 1 for OpenGL. pub normal_y: f32, /// 0 material, 1 channel, 2 mesh map (aux texture), 3 UV checker. @@ -295,6 +297,7 @@ impl Default for Shade { env_opacity: 0.0, ao_intensity: 0.75, height_strength: 1.0, + height_in_normal: true, normal_y: 1.0, view_mode: 0, channel: 0, @@ -2130,7 +2133,7 @@ impl Renderer { material: [if s.spec_gloss { 1.0 } else { 0.0 }, if s.parallax { 1.0 } else { 0.0 }, sample as f32, s.ior], scatter: [s.scatter[0], s.scatter[1], s.scatter[2], if sss.is_some() { 1.0 } else { 0.0 }], fwd: [fwd.x, fwd.y, fwd.z, 0.0], - disp, + disp: [disp[0], disp[1], disp[2], if s.height_in_normal { 1.0 } else { 0.0 }], refr: [if refraction { 1.0 } else { 0.0 }, (BEHIND_LEVELS - 1) as f32, REFRACTION_DEPTH * radius, 0.0], highlight: highlight_globals(s.highlight, HIGHLIGHT_OPACITY, s, data), highlight_shift: highlight_shift(frame.size), diff --git a/crates/render/src/shaders/mesh.wgsl b/crates/render/src/shaders/mesh.wgsl index 8e82daa9..1c6a08ba 100644 --- a/crates/render/src/shaders/mesh.wgsl +++ b/crates/render/src/shaders/mesh.wgsl @@ -22,7 +22,7 @@ struct Globals { material: vec4, // x specular/glossiness shading (1), y parallax occlusion (1), z accumulation sample index, w IOR of transmission scatter: vec4, // xyz per-channel diffuse wrap at scattering weight 1 (0 = Lambert), w G-buffer holds the scattering light (1) fwd: vec4, // xyz camera view direction (unit), w - - disp: vec4, // x displacement on (1), y world units per unit of height at strength 1, z vertex spacing in UV units, w - + disp: vec4, // x displacement on (1), y world units per unit of height at strength 1, z vertex spacing in UV units, w height slope in the shaded normal (1) or not (0) refr: vec4, // x screen-space refraction on (1), y lods of the scene behind, z refraction depth (world units), w - highlight: vec4, // rgb highlighted set's edge color in the scene (before exposure and tone mapping), a opacity highlight_shift: vec4, // xy sideways shift of each highlight line copy (clip units), zw - @@ -483,7 +483,7 @@ fn shade_mesh(i: VOut, front: bool) -> Shaded { // Match export: a unit height over 1/16 of the width tilts 45° // Combine the height gradient with the tangent-space normal - let k = g.mode.z * dims.x / 16.0 * tile_scale(uv); + let k = g.mode.z * g.disp.w * dims.x / 16.0 * tile_scale(uv); let n_height = normalize(vec3(-(hr - hl) * 0.5 * k, (hd - hu) * 0.5 * k, 1.0)); // The Normal texture holds the signed normal in half floats (flat is exactly +z) @@ -728,7 +728,7 @@ fn fs_uv(i: VOut) -> @location(0) vec4 { let hr = textureSample(t_height, samp, i.uv + vec2(ts.x, 0.0)).r; let hu = textureSample(t_height, samp, i.uv - vec2(0.0, ts.y)).r; let hd = textureSample(t_height, samp, i.uv + vec2(0.0, ts.y)).r; - let k = g.mode.z * dims.x / 16.0 * tile_scale(i.uv); + let k = g.mode.z * g.disp.w * dims.x / 16.0 * tile_scale(i.uv); let n_height = normalize(vec3(-(hr - hl) * 0.5 * k, (hd - hu) * 0.5 * k, 1.0)); var n_detail = clamp(textureSample(t_nrm, samp, i.uv).rgb, vec3(-1.0), vec3(1.0)); n_detail.y *= g.mode.w; diff --git a/crates/render/src/trace.rs b/crates/render/src/trace.rs index 034330b0..01e973d7 100644 --- a/crates/render/src/trace.rs +++ b/crates/render/src/trace.rs @@ -35,7 +35,16 @@ pub struct TraceSet { /// Mesh material the set covers. pub material: usize, pub composite: Composite, + /// Height displacement and, with `height_in_normal`, height-to-normal strength pub height_strength: f32, + pub height_in_normal: bool, +} + +impl TraceSet { + /// The strength of the height slope in the shaded normal (0 when normal mixing replaces it) + pub fn normal_height_strength(&self) -> f32 { + if self.height_in_normal { self.height_strength } else { 0.0 } + } } /// Everything a pass reads (cheap to clone: shared or copy-on-write data). @@ -575,7 +584,7 @@ fn surface(scene: &TraceScene, tri: u32, u: f32, v: f32, o: Vec3, d: Vec3, t: f3 // A UV tile smaller than its atlas block has fewer texels per UV unit: slopes per texel shrink. let k = set.map_or(0.0, |s| { let (x, y) = texel(s, 0, 0); - s.height_strength * s.composite.resolution as f32 / 16.0 * s.composite.block_scales.at(x, y) + s.normal_height_strength() * s.composite.resolution as f32 / 16.0 * s.composite.block_scales.at(x, y) }); let n_height = if k != 0.0 { let h = |dx, dy| ch(Channel::Height, dx, dy)[0]; @@ -1233,7 +1242,7 @@ mod tests { } } } - TraceScene::new(mesh, bvh, vec![TraceSet { material: 0, composite, height_strength: 0.0 }], env, 0.0) + TraceScene::new(mesh, bvh, vec![TraceSet { material: 0, composite, height_strength: 0.0, height_in_normal: true }], env, 0.0) } /// Mean radiance of parallel rays over the whole disc of the sphere (grazing hits included) diff --git a/crates/ui-egui/src/render_mode.rs b/crates/ui-egui/src/render_mode.rs index 7fa38fe1..56dbe6af 100644 --- a/crates/ui-egui/src/render_mode.rs +++ b/crates/ui-egui/src/render_mode.rs @@ -268,7 +268,12 @@ fn trace_scene(app: &TextureCraftApp) -> TraceScene { .texture_sets .iter() .zip(&session.caches) - .map(|(set, cache)| TraceSet { material: set.material, composite: cache.composite.clone(), height_strength: set.atlas_height_strength() }) + .map(|(set, cache)| TraceSet { + material: set.material, + composite: cache.composite.clone(), + height_strength: set.atlas_height_strength(), + height_in_normal: set.height_in_normal(), + }) .collect(); let env_image = display.environment_resource().and_then(|n| session.images.get(n)); @@ -327,7 +332,7 @@ fn work(app: &TextureCraftApp, size: (u32, u32)) -> Work { /// revisions bump with every composited chunk, so while textures load this changes every frame). fn scene_key(session: &texturecraft_engine::Session, composites: bool) -> String { let revisions: Vec = if composites { session.caches.iter().map(|cache| cache.revision).collect() } else { Vec::new() }; - let sets: Vec<_> = session.doc.project.texture_sets.iter().map(|set| (set.material, set.atlas_height_strength())).collect(); + let sets: Vec<_> = session.doc.project.texture_sets.iter().map(|set| (set.material, set.atlas_height_strength(), set.height_in_normal())).collect(); let display = &session.doc.project.display; let env_image = display.environment_resource().and_then(|name| session.images.get(name)).map(Arc::as_ptr); diff --git a/crates/ui-egui/src/viewport.rs b/crates/ui-egui/src/viewport.rs index 4c1fe3c7..30922d2f 100644 --- a/crates/ui-egui/src/viewport.rs +++ b/crates/ui-egui/src/viewport.rs @@ -381,12 +381,15 @@ fn shade(app: &TextureCraftApp) -> Shade { ViewMode::NormalHeightMesh => (VIEW_MODE_NORMAL_HEIGHT_MESH, 0), }; let set_index = app.session.ts(); - let height_strength = app.session.doc.project.texture_sets.get(set_index).map(|texture_set| texture_set.atlas_height_strength()).unwrap_or(1.0); + let active_set = app.session.doc.project.texture_sets.get(set_index); + let height_strength = active_set.map(|texture_set| texture_set.atlas_height_strength()).unwrap_or(1.0); + let height_in_normal = active_set.is_none_or(|texture_set| texture_set.height_in_normal()); // Polygon fill shows the polygons it fills without changing the saved wireframe toggles let polygon_fill_tool = tool_acts(app) && app.session.tool.tool == Tool::PolygonFill; Shade { height_strength, + height_in_normal, view_mode, channel, wireframe: wireframe_shown(&app.ui, polygon_fill_tool),