diff --git a/crates/render/src/renderer.rs b/crates/render/src/renderer.rs index 481cb6d4..0fd677bf 100644 --- a/crates/render/src/renderer.rs +++ b/crates/render/src/renderer.rs @@ -100,6 +100,7 @@ struct GlobalsRaw { refr: [f32; 4], highlight: [f32; 4], highlight_shift: [f32; 4], + set_hover: [f32; 4], bake_high: [f32; 4], bake_matching_error: [f32; 4], bake_cage: [f32; 4], @@ -137,6 +138,9 @@ const HIGHLIGHT_WIDTH_PX: f32 = 1.5; /// Opacity of the highlighted set's edge lines const HIGHLIGHT_OPACITY: f32 = 0.9; +/// Opacity of the texture-set hover tint over the shaded material. +const SET_HOVER_OPACITY: f32 = 0.35; + /// Copies of each highlight line, shifted diagonally to the four corners of its extra width (`vs_wire_highlight`) const HIGHLIGHT_SHIFTS: u32 = 4; @@ -194,6 +198,8 @@ pub struct Shade { pub wireframe_opacity: f32, /// One texture set's mesh edges in a highlight color over the 3D view (the set under a shelf drag) pub highlight: Option, + /// The texture set whose visible surfaces are tinted in the 3D view. + pub set_hover: Option, /// Specular/glossiness shading: base color is the diffuse color and the Specular channel the /// F0 color (roughness arrives as 1 - glossiness from the display conversion). pub spec_gloss: bool, @@ -308,6 +314,7 @@ impl Default for Shade { wireframe_3d: false, wireframe_opacity: 0.4, highlight: None, + set_hover: None, spec_gloss: false, parallax: false, taa: false, @@ -1941,8 +1948,8 @@ impl Renderer { ranges: &'a [(u32, u32, usize)], visible: &'a [bool], only: Option, - ) -> impl Iterator, &'a SetGpu)> + 'a { - drawable_ranges(ranges, &self.material_sets, visible, only).filter_map(|(range, ts)| Some((range, self.sets.get(ts)?))) + ) -> impl Iterator, usize, &'a SetGpu)> + 'a { + drawable_ranges(ranges, &self.material_sets, visible, only).filter_map(|(range, texture_set)| Some((range, texture_set, self.sets.get(texture_set)?))) } /// Keep the key-light shadow map current; returns its view-projection. `light` points to @@ -2003,7 +2010,7 @@ impl Renderer { let geo = m.dense.as_ref().filter(|_| displacing).unwrap_or(&m.geo); pass.set_vertex_buffer(0, geo.vb.slice(..)); pass.set_index_buffer(geo.ib.slice(..), wgpu::IndexFormat::Uint32); - for (range, set) in self.drawable(&geo.draws, visible, None) { + for (range, _, set) in self.drawable(&geo.draws, visible, None) { pass.set_bind_group(1, &set.bind_group, &[]); pass.draw_indexed(range, 0, 0..1); } @@ -2125,8 +2132,9 @@ impl Renderer { fwd: [fwd.x, fwd.y, fwd.z, 0.0], disp, refr: [if refraction { 1.0 } else { 0.0 }, (BEHIND_LEVELS - 1) as f32, REFRACTION_DEPTH * radius, 0.0], - highlight: highlight_globals(s, data), + highlight: highlight_globals(s.highlight, HIGHLIGHT_OPACITY, s, data), highlight_shift: highlight_shift(frame.size), + set_hover: highlight_globals(s.set_hover, SET_HOVER_OPACITY, s, data), ..bake_globals(s.bake) }; let flag = |b: bool| if b { 1.0 } else { 0.0 }; @@ -2135,11 +2143,12 @@ impl Renderer { b: [fx(s.vignette), fx(s.sharpen), fx(s.grain), BLOOM_THRESHOLD], c: dof_c, d: sss_d, - e: [flag(cam.ortho), sample as f32, 0.0, 0.0], + e: [flag(cam.ortho), sample as f32, raw.set_hover[3], 0.0], back_top: [s.background[0][0], s.background[0][1], s.background[0][2], 0.0], back_bottom: [s.background[1][0], s.background[1][1], s.background[1][2], 0.0], }; let Some(v) = self.targets(device, frame.view_id, frame.size, bloom, fx_on, refraction) else { return }; + queue.write_buffer(&v.globals, 0, bytemuck::bytes_of(&raw)); queue.write_buffer(&v.post_buf, 0, bytemuck::bytes_of(&post)); upload_overlay(device, queue, v, &frame.overlay, (!data).then_some(s.exposure_ev)); @@ -2214,9 +2223,13 @@ impl Renderer { let geo = self.geometry(m, frame); pass.set_vertex_buffer(0, geo.vb.slice(..)); pass.set_index_buffer(geo.ib.slice(..), wgpu::IndexFormat::Uint32); - for (range, set) in self.drawable(&geo.draws, &frame.visible, None) { + + // Instance index 1 lets the G-buffer mark the hovered set for the scattering composite + let hover_set = frame.shade.set_hover.filter(|_| frame.kind == ViewKind::Scene).map(|hover| hover.set); + for (range, texture_set, set) in self.drawable(&geo.draws, &frame.visible, None) { pass.set_bind_group(1, &set.bind_group, &[]); - pass.draw_indexed(range, 0, 0..1); + let first_instance = u32::from(hover_set == Some(texture_set)); + pass.draw_indexed(range, 0, first_instance..first_instance + 1); } } @@ -2341,22 +2354,25 @@ impl Renderer { let bake = frame.shade.bake.filter(|_| uv_set.is_none()); let low_poly_shown = bake.is_none_or(|bake| bake.low_poly.shown); let (highlight, highlight_set) = highlight.filter(|(_, set)| low_poly_shown && uv_set.is_none_or(|only| only == *set)).unzip(); + let hover_set = frame.shade.set_hover.filter(|_| uv_set.is_none()).map(|hover| hover.set); // The wireframe and the highlight draw the mesh's own edges (displaced in the vertex shader too) let passes = [ - (low_poly_shown.then_some(mesh_pipeline), &geometry.vb, &geometry.ib, &geometry.draws, uv_set, 1), - (wire.filter(|_| low_poly_shown), &mesh.geo.vb, &mesh.lines, &mesh.line_draws, uv_set, 1), - (highlight, &mesh.geo.vb, &mesh.lines, &mesh.line_draws, highlight_set, HIGHLIGHT_SHIFTS), + (low_poly_shown.then_some(mesh_pipeline), &geometry.vb, &geometry.ib, &geometry.draws, uv_set, 1, hover_set), + (wire.filter(|_| low_poly_shown), &mesh.geo.vb, &mesh.lines, &mesh.line_draws, uv_set, 1, None), + (highlight, &mesh.geo.vb, &mesh.lines, &mesh.line_draws, highlight_set, HIGHLIGHT_SHIFTS, None), ]; - for (pipeline, vertices, indices, ranges, only_set, instances) in passes { + for (pipeline, vertices, indices, ranges, only_set, instances, hover_set) in passes { let Some(pipeline) = pipeline else { continue }; pass.set_pipeline(pipeline); pass.set_vertex_buffer(0, vertices.slice(..)); pass.set_index_buffer(indices.slice(..), wgpu::IndexFormat::Uint32); - for (range, set) in self.drawable(ranges, &frame.visible, only_set) { + for (range, texture_set, set) in self.drawable(ranges, &frame.visible, only_set) { + // Instance index 1 lets the mesh shader tint the hovered draw + let first_instance = u32::from(hover_set == Some(texture_set)); pass.set_bind_group(1, &set.bind_group, &[]); - pass.draw_indexed(range, 0, 0..instances); + pass.draw_indexed(range, 0, first_instance..first_instance + instances); } } @@ -2370,7 +2386,7 @@ impl Renderer { pass.set_pipeline(&self.uv_missing_seam_pipeline); pass.set_vertex_buffer(0, mesh.geo.vb.slice(..)); pass.set_index_buffer(seams.lines.slice(..), wgpu::IndexFormat::Uint32); - for (range, set) in self.drawable(&seams.line_draws, &frame.visible, Some(texture_set)) { + for (range, _, set) in self.drawable(&seams.line_draws, &frame.visible, Some(texture_set)) { pass.set_bind_group(1, &set.bind_group, &[]); pass.draw_indexed(range, 0, 0..1); } @@ -2404,7 +2420,7 @@ impl Renderer { pass.set_pipeline(&self.missing_seam_pipeline); pass.set_vertex_buffer(0, low_poly.geo.vb.slice(..)); pass.set_index_buffer(seams.lines.slice(..), wgpu::IndexFormat::Uint32); - for (range, set) in self.drawable(&seams.line_draws, &frame.visible, None) { + for (range, _, set) in self.drawable(&seams.line_draws, &frame.visible, None) { pass.set_bind_group(1, &set.bind_group, &[]); pass.draw_indexed(range, 0, 0..1); } @@ -2541,12 +2557,12 @@ fn upload_overlay(device: &wgpu::Device, queue: &wgpu::Queue, view: &mut ViewTar } } -/// Globals `highlight`: the highlight's color and opacity, all zero without one. Data views skip exposure and tone mapping, so they take the color as it is -fn highlight_globals(shade: &Shade, data: bool) -> [f32; 4] { - let Some(highlight) = shade.highlight else { return [0.0; 4] }; +/// The highlight's color and opacity. Data views take the color as it is. +fn highlight_globals(highlight: Option, opacity: f32, shade: &Shade, data: bool) -> [f32; 4] { + let Some(highlight) = highlight else { return [0.0; 4] }; let [r, g, b] = if data { highlight.color } else { highlight.scene_color(shade.exposure_ev, shade.aces) }; - [r, g, b, HIGHLIGHT_OPACITY] + [r, g, b, opacity] } /// The globals of bake mode's overlays and neutral material for `bake` (all zero without it) @@ -2678,8 +2694,8 @@ mod tests { let color = [0.8, 0.25, 0.08]; let shade = Shade { highlight: Some(SetHighlight { set: 0, color }), exposure_ev: 1.0, ..Shade::default() }; - assert_eq!(highlight_globals(&shade, true), [0.8, 0.25, 0.08, HIGHLIGHT_OPACITY]); - assert_ne!(highlight_globals(&shade, false)[..3], color, "the material view undoes exposure and tone mapping"); + assert_eq!(highlight_globals(shade.highlight, HIGHLIGHT_OPACITY, &shade, true), [0.8, 0.25, 0.08, HIGHLIGHT_OPACITY]); + assert_ne!(highlight_globals(shade.highlight, HIGHLIGHT_OPACITY, &shade, false)[..3], color, "the material view undoes exposure and tone mapping"); } #[test] diff --git a/crates/render/src/set_highlight.rs b/crates/render/src/set_highlight.rs index cc29879e..574b5bbd 100644 --- a/crates/render/src/set_highlight.rs +++ b/crates/render/src/set_highlight.rs @@ -1,4 +1,4 @@ -//! A texture set's mesh edges drawn over the 3D view in a highlight color (the set under a shelf drag) +//! Texture-set highlighting in the 3D viewport. /// Brightest on-screen value the tone curve can reach without an infinite scene value const MAX_ACES_SCREEN_VALUE: f32 = 0.99; @@ -6,16 +6,16 @@ const MAX_ACES_SCREEN_VALUE: f32 = 0.99; /// Scene scale the post pass applies before its ACES curve (`aces` in post.wgsl) const ACES_INPUT_SCALE: f32 = 0.6; -/// Draw texture set `set`'s mesh edges over the 3D view in `color` +/// A texture set to highlight in the 3D viewport. #[derive(Clone, Copy, Debug, PartialEq)] pub struct SetHighlight { pub set: usize, - /// The lines' color on screen, linear RGB + /// The highlight color on screen, linear RGB. pub color: [f32; 3], } impl SetHighlight { - /// The scene color the lines are drawn with so that exposure `exposure_ev` and the tone curve (ACES when `aces`) show them in [`Self::color`] + /// The scene color that exposure `exposure_ev` and the tone curve (ACES when `aces`) show as [`Self::color`]. pub fn scene_color(&self, exposure_ev: f32, aces: bool) -> [f32; 3] { scene_color_showing(self.color, exposure_ev, aces) } diff --git a/crates/render/src/shaders/fx.wgsl b/crates/render/src/shaders/fx.wgsl index 333664ce..36235a72 100644 --- a/crates/render/src/shaders/fx.wgsl +++ b/crates/render/src/shaders/fx.wgsl @@ -1,7 +1,6 @@ -// Scene effects between the scene pass and the post pass, appended to util.wgsl and post.wgsl -// (uses `src`, `src_samp`, `post`, `fx_a`): the screen-space subsurface blur and depth of field. -// Both read the G-buffer of `fs_gbuf` (mesh.wgsl): rgb the scattering part of the diffuse light, -// a the view depth (0: background). Colors are linear HDR premultiplied by scene coverage. +// Screen-space subsurface blur and depth of field run between the scene and post passes +// G-buffer RGB holds scattering light in linear HDR premultiplied by scene coverage +// G-buffer alpha holds view depth, with zero for background and a negative sign for hover @group(0) @binding(5) var fx_b: texture_2d; @group(0) @binding(6) var fx_c: texture_2d; @@ -31,19 +30,22 @@ fn px_per_world(z: f32) -> f32 { return select(post.d.w / max(z, 1e-4), post.d.w, post.e.x > 0.5); } -// One direction of the blur over `src` (rgb light, a depth) at pixel `p` (same-size target). +// The blur changes RGB and carries the centre's signed depth unchanged fn sss_blur(p: vec2, dir: vec2) -> vec4 { let c = texel_at(src, p); - let sigma = post.d.xyz * px_per_world(c.a); + let z = abs(c.a); + let sigma = post.d.xyz * px_per_world(z); let smax = max(sigma.r, max(sigma.g, sigma.b)); - if (c.a <= 0.0 || smax < 0.5) { + + if (z <= 0.0 || smax < 0.5) { return c; } + let stride = dir * (smax * 3.0 / f32(SSS_TAPS)); let depth_range = 3.0 * max(post.d.x, max(post.d.y, post.d.z)); let inv = 1.0 / (2.0 * sigma * sigma + vec3(1e-4)); - // Wide blurs space their taps pixels apart: shifting them per pixel (interleaved gradient - // noise) and per accumulated frame turns what would show as copies of edges into fine grain. + + // Jitter the wide blur taps so copies of edges become fine grain let ign = fract(52.9829189 * fract(dot(p, vec2(0.06711056, 0.00583715)))); let jitter = fract(ign + post.e.y * 0.618034) - 0.5; var sum = c.rgb; @@ -52,30 +54,35 @@ fn sss_blur(p: vec2, dir: vec2) -> vec4 { if (k == 0) { continue; } + let o = f32(k) + jitter; let t = texel_at(src, p + stride * o); let x = o * smax * 3.0 / f32(SSS_TAPS); - let wd = select(0.0, max(1.0 - abs(t.a - c.a) / depth_range, 0.0), t.a > 0.0); + let tz = abs(t.a); + let wd = select(0.0, max(1.0 - abs(tz - z) / depth_range, 0.0), tz > 0.0); let w = exp(-x * x * inv); sum += mix(c.rgb, t.rgb, wd) * w; wsum += w; } + return vec4(sum / wsum, c.a); } -// src: the G-buffer. +// Read scattering light and depth from the G-buffer @fragment fn fs_sss_h(i: FsOut) -> @location(0) vec4 { return sss_blur(i.pos.xy, vec2(1.0, 0.0)); } -// src: the horizontal pass, fx_a: the scene (without its scattering light, see `fs_mesh`). Adds -// the blurred scattering light. +// Restore scattering light from the horizontal pass to the main scene in fx_a +// Apply hover opacity at the destination so neighbouring sets keep the light they receive @fragment fn fs_sss_v(i: FsOut) -> @location(0) vec4 { - let blurred = sss_blur(i.pos.xy, vec2(0.0, 1.0)).rgb; + let blurred = sss_blur(i.pos.xy, vec2(0.0, 1.0)); let scene = texel_at(fx_a, i.pos.xy); - return scene + vec4(blurred * clamp(scene.a, 0.0, 1.0), 0.0); + let scattering_weight = select(1.0, 1.0 - post.e.z, blurred.a < 0.0); + + return scene + vec4(blurred.rgb * scattering_weight * clamp(scene.a, 0.0, 1.0), 0.0); } // ---- Depth of field: a thin lens. Scatter-as-gather over a golden-angle spiral at half @@ -103,27 +110,28 @@ struct DofOut { @location(1) near: vec4, }; -// src: the scene (full resolution), fx_a: the G-buffer. +// Read full-resolution scene colors from src and depths from fx_a @fragment fn fs_dof_gather(i: FsOut) -> DofOut { let px = 1.0 / vec2(textureDimensions(src)); - let zc = texel(fx_a, i.uv).a; + let zc = abs(texel(fx_a, i.uv).a); let cc = abs(coc(zc)); let rmax = post.c.z; - // Half the spacing of the taps: the soft edge of each tap's reach. + + // Half the spacing of the taps softens the edge of each tap's reach let h = max(rmax * sqrt(PI_FX / f32(DOF_TAPS)) * 0.5, 0.5); var acc = textureSampleLevel(src, src_samp, i.uv, 0.0); var tot = 1.0; var near = 0.0; - // The spiral turns per pixel (interleaved gradient noise) and per accumulated frame, so the - // taps' pattern averages into smooth discs instead of showing as dots in bright highlights. + + // Rotate the taps per pixel and frame so bright highlights average into smooth discs let ign = fract(52.9829189 * fract(dot(i.pos.xy, vec2(0.06711056, 0.00583715)))); let turn = (ign + post.c.w * 0.618034) * 6.2831853; for (var k = 0; k < DOF_TAPS; k++) { let r = rmax * sqrt((f32(k) + 0.5) / f32(DOF_TAPS)); let a = f32(k) * GOLDEN_ANGLE + turn; let uv = i.uv + vec2(cos(a), sin(a)) * (r * px); - let z = texel(fx_a, uv).a; + let z = abs(texel(fx_a, uv).a); let nearer = z > 0.0 && (zc <= 0.0 || z < zc); var size = abs(coc(z)); if (!nearer) { @@ -136,20 +144,23 @@ fn fs_dof_gather(i: FsOut) -> DofOut { near = max(near, m * smoothstep(0.5, 1.5, size)); } } + return DofOut(acc / tot, vec4(near)); } const PI_FX: f32 = 3.14159265; -// src: the sharp scene, fx_a: the gathered blur, fx_b: the G-buffer, fx_c: the near coverage. +// Use G-buffer depth and near coverage to blend the half-resolution blur into the scene @fragment fn fs_dof(i: FsOut) -> @location(0) vec4 { let sharp = texel_at(src, i.pos.xy); - let f = max(smoothstep(0.5, 1.5, abs(coc(texel_at(fx_b, i.pos.xy).a))), textureSampleLevel(fx_c, src_samp, i.uv, 0.0).r); - // In focus with nothing blurred in front: the sharp pixel itself (no blend through the - // half-resolution blur at all). - if (f <= 0.0) { + let depth = abs(texel_at(fx_b, i.pos.xy).a); + let blur_weight = max(smoothstep(0.5, 1.5, abs(coc(depth))), textureSampleLevel(fx_c, src_samp, i.uv, 0.0).r); + + // Preserve the full-resolution pixel where no blur reaches it + if (blur_weight <= 0.0) { return sharp; } - return mix(sharp, textureSampleLevel(fx_a, src_samp, i.uv, 0.0), f); + + return mix(sharp, textureSampleLevel(fx_a, src_samp, i.uv, 0.0), blur_weight); } diff --git a/crates/render/src/shaders/mesh.wgsl b/crates/render/src/shaders/mesh.wgsl index 31fd19df..8e82daa9 100644 --- a/crates/render/src/shaders/mesh.wgsl +++ b/crates/render/src/shaders/mesh.wgsl @@ -26,6 +26,7 @@ struct Globals { 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 - + set_hover: vec4, // rgb hovered set's scene color, a opacity bake_high: vec4, // bake mode: rgb high poly color, a - bake_matching_error: vec4, // rgb color where the bake's rays miss the high poly, a its strength (0 hidden) bake_cage: vec4, // rgb cage surface color, a opacity @@ -70,6 +71,7 @@ struct VOut { @location(1) nrm: vec3, @location(2) tan: vec4, @location(3) uv: vec2, + @location(4) @interpolate(flat) hover: u32, }; // The vertex moved along its normal by the height channel (displacement). @@ -81,7 +83,7 @@ fn displaced(v: VIn) -> vec3 { } @vertex -fn vs_mesh(v: VIn) -> VOut { +fn vs_mesh(v: VIn, @builtin(instance_index) instance_index: u32) -> VOut { var o: VOut; let p = displaced(v); o.clip = g.view_proj * vec4(p, 1.0); @@ -89,6 +91,7 @@ fn vs_mesh(v: VIn) -> VOut { o.nrm = v.nrm; o.tan = v.tan; o.uv = v.uv; + o.hover = instance_index; return o; } @@ -350,16 +353,26 @@ fn unlit(c: vec4) -> Shaded { fn mesh_color(i: VOut, front: bool) -> vec4 { let o = shade_mesh(i, front); + + // The subsurface pass restores the scattering light after blurring if (g.scatter.w > 0.5) { - // The subsurface blur pass adds the scattering light back, blurred (fx.wgsl). return o.color - vec4(o.sss, 0.0); } + return o.color; } +const HOVERED_SET_INSTANCE: u32 = 1u; + @fragment fn fs_mesh(i: VOut, @builtin(front_facing) front: bool) -> @location(0) vec4 { - return mesh_color(i, front); + let color = mesh_color(i, front); + + if (i.hover == HOVERED_SET_INSTANCE) { + return vec4(mix(color.rgb, g.set_hover.rgb * color.a, g.set_hover.a), color.a); + } + + return color; } // The scene behind transmissive surfaces: everything but them (what they refract). @@ -373,17 +386,23 @@ fn fs_opaque(i: VOut, @builtin(front_facing) front: bool) -> @location(0) vec4 @location(0) vec4 { - let z = max(dot(i.wpos - g.eye.xyz, g.fwd.xyz), 1e-4); + var z = max(dot(i.wpos - g.eye.xyz, g.fwd.xyz), 1e-4); var sss = vec3(0.0); + if (g.scatter.w > 0.5) { sss = shade_mesh(i, front).sss; + if (i.hover == HOVERED_SET_INSTANCE) { + z = -z; + } } else if (textureSample(t_base, samp, i.uv).a < hash12(i.clip.xy)) { discard; } + return vec4(sss, z); } diff --git a/crates/render/src/shaders/post.wgsl b/crates/render/src/shaders/post.wgsl index e5df0cd8..df984040 100644 --- a/crates/render/src/shaders/post.wgsl +++ b/crates/render/src/shaders/post.wgsl @@ -7,7 +7,7 @@ struct Post { b: vec4, // x vignette, y sharpen, z grain, w bloom threshold c: vec4, // depth of field (fx.wgsl): x circle of confusion at infinity (pixels), y focus depth, z largest circle radius (pixels), w accumulation sample d: vec4, // subsurface blur (fx.wgsl): xyz mean free path per channel (world units), w pixels per world unit at depth 1 - e: vec4, // x orthographic camera (1: pixels per world unit don't fall off with depth), y accumulation sample, zw - + e: vec4, // x orthographic camera, y accumulation sample, z hover tint opacity for the scattering composite, w - back_top: vec4, // rgb background color at the top of the view (linear), a - back_bottom: vec4, // rgb background color at the bottom of the view (linear), a - }; diff --git a/crates/render/tests/headless.rs b/crates/render/tests/headless.rs index 042a59c9..62c9aa0a 100644 --- a/crates/render/tests/headless.rs +++ b/crates/render/tests/headless.rs @@ -1076,6 +1076,58 @@ fn subsurface_blur_spreads_only_scattering_light() { assert!((m1 - m0).abs() < 2.0, "the blur moves light, it adds none: {m0} -> {m1}"); } +#[test] +fn the_hover_tint_covers_the_blurred_scattering_light_too() { + let Some((mut h, frame)) = setup() else { return }; + + // Read coverage in the flat base-color view so lighting cannot hide a set at its edge + let base_color_view = shaded(&frame, |shade| shade.view_mode = 1); + let hovered_set_mask = mesh_mask(&mut h, &base_color_view, &[0]); + let neighbour_mask = mesh_mask(&mut h, &base_color_view, &[1]); + let lit = shaded(&frame, |s| s.light = LIGHT); + fill(&mut h, &[0, 1], DisplayKind::BaseColor, &[150, 150, 150, 255]); + fill(&mut h, &[0, 1], DisplayKind::Emissive, &[0, 0, 0, 255]); + + let blur = shaded(&lit, |s| s.sss_blur = Some([0.06, 0.024, 0.015])); + let hover = |frame: &Frame| shaded(frame, |s| s.set_hover = Some(texturecraft_render::SetHighlight { set: 0, color: [1.0, 0.5, 0.0] })); + let mean = |img: &Img| region_mean(&hovered_set_mask, |x, y| img.luma(x, y)); + let plain = mean(&render(&mut h, &lit, "hover_sss_plain")); + let blurred = mean(&render(&mut h, &blur, "hover_sss_blur")); + let hovered_blur = mean(&render(&mut h, &hover(&blur), "hover_sss_blur_hovered")); + let hovered_plain = mean(&render(&mut h, &hover(&lit), "hover_sss_plain_hovered")); + + assert!(hovered_plain != plain, "the hover tint changes the set"); + + // Hover must dim the light restored by the blur along with the rest of the material + assert!( + ((hovered_blur - hovered_plain) - (blurred - plain)).abs() < 1.0, + "the blur changes the plain set by {} and the hovered set by {}", + blurred - plain, + hovered_blur - hovered_plain + ); + + // Use a wide blur so scattering light crosses the boundary between the two sets + let wide = shaded(&lit, |s| s.sss_blur = Some([0.2, 0.08, 0.05])); + let blurred_img = render(&mut h, &wide, "hover_sss_wide"); + let hovered_blur_img = render(&mut h, &hover(&wide), "hover_sss_wide_hovered"); + + // Skip pixels that legitimately include samples of the hovered set after MSAA resolve + let width = blurred_img.w; + let mut checked = 0; + let mut worst_delta = 0.0f32; + for (index, &neighbour) in neighbour_mask.iter().enumerate() { + if neighbour && !hovered_set_mask[index] { + let (x, y) = (index as u32 % width, index as u32 / width); + let delta = (hovered_blur_img.luma(x, y) - blurred_img.luma(x, y)).abs(); + checked += 1; + worst_delta = worst_delta.max(delta); + } + } + + assert!(checked > 0, "the neighbour has pixels with no coverage from the hovered set"); + assert!(worst_delta <= 1.0, "hovering set 0 changes the neighbouring set by up to {worst_delta} luma across {checked} pixels"); +} + /// An environment that is bright only around `dir` (world space, rotation 0). fn spot_environment(dir: texturecraft_geom::glam::Vec3) -> ImageRes { let (w, hh) = (256u32, 128u32); diff --git a/crates/ui-egui/src/bake_mode/mod.rs b/crates/ui-egui/src/bake_mode/mod.rs index 3acf83a0..1efb19d3 100644 --- a/crates/ui-egui/src/bake_mode/mod.rs +++ b/crates/ui-egui/src/bake_mode/mod.rs @@ -61,7 +61,7 @@ pub fn texture_sets(app: &mut TextureCraftApp, ui: &mut Ui) { .collect(); ui.push_id(set_index, |ui| { - ui.horizontal(|ui| { + let row = ui.horizontal(|ui| { let button_size = ui.spacing().interact_size.y; if icon_button(ui, if visible { icon::EYE } else { icon::EYE_SLASH }, tr("Show or hide the texture set"), false, button_size).clicked() { app.run("textureSet.visible", json!({ "ts": set_index })); @@ -88,6 +88,10 @@ pub fn texture_sets(app: &mut TextureCraftApp, ui: &mut Ui) { } }); + if ui.is_enabled() && ui.rect_contains_pointer(row.response.rect) { + app.next_hovered_texture_set = Some((app.session.project_id, set_index)); + } + if !tiles.is_empty() { egui::CollapsingHeader::new(format!("{} ({})", tr("UV tiles (UDIM)"), tiles.len())).default_open(true).show(ui, |ui| { for (tile, override_resolution, enabled) in &tiles { diff --git a/crates/ui-egui/src/dock.rs b/crates/ui-egui/src/dock.rs index e51abaca..c1d3124a 100644 --- a/crates/ui-egui/src/dock.rs +++ b/crates/ui-egui/src/dock.rs @@ -78,6 +78,9 @@ pub(crate) fn texture_set_list(app: &mut TextureCraftApp, ui: &mut Ui) { egui::ScrollArea::vertical().id_salt("ts_scroll").show(ui, |ui| { for (i, (name, size, visible)) in sets.into_iter().enumerate() { let (rect, resp) = ui.allocate_exact_size(vec2(ui.available_width(), 22.0), Sense::click()); + resp.widget_info(|| egui::WidgetInfo::labeled(egui::Role::ListItem, ui.is_enabled(), &name)); + ui.ctx().accesskit_node_builder(resp.id, |node| node.set_selected(i == active)); + let p = ui.painter(); let bg = if i == active { tk.row_selected @@ -90,10 +93,18 @@ pub(crate) fn texture_set_list(app: &mut TextureCraftApp, ui: &mut Ui) { if i == active { p.rect_stroke(rect, 2.0, Stroke::new(1.0, tk.accent), egui::StrokeKind::Inside); } + if resp.has_focus() { + p.rect_stroke(rect.shrink(2.0), 2.0, Stroke::new(1.0, tk.text_strong), egui::StrokeKind::Inside); + } + let eye = Rect::from_min_size(rect.min + vec2(4.0, 3.0), vec2(16.0, 16.0)); let eye_resp = ui.interact(eye, ui.scope_id().with(("ts_eye", i)), Sense::click()).on_hover_text(tr("Show or hide the texture set")); p.text(eye.center(), egui::Align2::CENTER_CENTER, if visible { ic::EYE } else { ic::EYE_SLASH }, egui::FontId::proportional(13.0), tk.text); + if ui.is_enabled() && (resp.contains_pointer() || eye_resp.contains_pointer()) { + app.next_hovered_texture_set = Some((app.session.project_id, i)); + } + // Narrow panels drop the shader label, then the resolution, before cutting the name let cy = rect.center().y; let mut right = rect.right() - 6.0; @@ -3318,3 +3329,36 @@ mod layer_layout_tests { assert!(show_blend); } } + +#[cfg(all(test, not(target_arch = "wasm32")))] +mod texture_set_list_tests { + use egui_kittest::Harness; + use egui_kittest::kittest::{NodeT, Queryable}; + + use super::*; + + #[test] + fn keyboard_selection_updates_the_texture_set_list_items() { + let session = texturecraft_engine::Session::new_project( + "Texture set selection", + texturecraft_engine::geom::primitives::material_ball(), + "builtin:material_ball", + None, + 128, + ) + .unwrap(); + let first = session.doc.project.texture_sets[0].name.clone(); + let second = session.doc.project.texture_sets[1].name.clone(); + let mut harness = Harness::builder().with_size(vec2(1600.0, 960.0)).build_eframe(|context| TextureCraftApp::new(context, session)); + harness.run_steps(4); + + harness.get_by_role_and_label(egui::Role::ListItem, &second).focus(); + harness.run_steps(2); + harness.key_press(egui::Key::Enter); + harness.run_steps(3); + + assert_eq!(harness.state().session.ts(), 1); + assert_eq!(harness.get_by_role_and_label(egui::Role::ListItem, &first).accesskit_node().is_selected(), Some(false)); + assert_eq!(harness.get_by_role_and_label(egui::Role::ListItem, &second).accesskit_node().is_selected(), Some(true)); + } +} diff --git a/crates/ui-egui/src/lib.rs b/crates/ui-egui/src/lib.rs index 16c8dd1d..ed85f4fc 100644 --- a/crates/ui-egui/src/lib.rs +++ b/crates/ui-egui/src/lib.rs @@ -299,6 +299,10 @@ pub struct TextureCraftApp { pub(crate) live_preview: bake_mode::LivePreview, /// Last frame's viewport rect (logical points), for scripted input. pub viewport_rect: egui::Rect, + /// Project and texture-set index from the last completed UI pass. + hovered_texture_set: Option<(u64, usize)>, + /// The set under the pointer in this pass, independent of dock drawing order. + next_hovered_texture_set: Option<(u64, usize)>, pub fps: f32, /// User smart materials found in the library folder (refreshed on demand). pub library: Option>, @@ -444,6 +448,8 @@ impl TextureCraftApp { bake_map_thumbnails: bake_mode::MapThumbnails::default(), live_preview: bake_mode::LivePreview::default(), viewport_rect: egui::Rect::NOTHING, + hovered_texture_set: None, + next_hovered_texture_set: None, fps: 0.0, ui_ms: 0.0, profiler: profile::Profiler::default(), @@ -1251,6 +1257,13 @@ impl eframe::App for TextureCraftApp { // The dock keeps the cards' gutter from the bars and rails around it let panel_frame = if hide_ui { egui::Frame::NONE.fill(tokens.viewport) } else { egui::Frame::NONE.fill(tokens.chrome).inner_margin(theme::GUTTER) }; egui::CentralPanel::default().frame(panel_frame).show(ui, |ui| if hide_ui { viewport::central(self, ui) } else { docking::show(self, ui) }); + + let hovered_texture_set = self.next_hovered_texture_set.take(); + if self.hovered_texture_set != hovered_texture_set { + self.hovered_texture_set = hovered_texture_set; + ctx.request_repaint(); + } + windows::show(self, &ctx); // Finish after the dock and windows have requested their thumbnails diff --git a/crates/ui-egui/src/viewport.rs b/crates/ui-egui/src/viewport.rs index bcddd78f..c1441993 100644 --- a/crates/ui-egui/src/viewport.rs +++ b/crates/ui-egui/src/viewport.rs @@ -381,9 +381,14 @@ fn shade(app: &TextureCraftApp) -> Shade { /// The texture set a shelf material or image dragged over the 3D view `response` would drop on, its edges drawn in the accent color fn drop_highlight(app: &TextureCraftApp, ui: &Ui, response: &egui::Response) -> Option { let set = crate::shelf::drop_set(app, ui, response)?; + + Some(set_highlight(ui, set)) +} + +fn set_highlight(ui: &Ui, texture_set: usize) -> SetHighlight { let accent = egui::Rgba::from(Tokens::get(ui.ctx()).viewport_accent); - Some(SetHighlight { set, color: [accent.r(), accent.g(), accent.b()] }) + SetHighlight { set: texture_set, color: [accent.r(), accent.g(), accent.b()] } } /// Show what the GPU side reported (each message once while its toast is up). @@ -450,7 +455,15 @@ fn frame_size_in_pixels(ui: &Ui, rect: Rect) -> [u32; 2] { [pixels(rect.left(), rect.right()), pixels(rect.top(), rect.bottom())] } +#[cfg(test)] +const TEST_SCENE_SET_HOVER: &str = "scene_frame_set_hover"; + fn add_callback(app: &mut TextureCraftApp, ui: &Ui, rect: Rect, mut frame: Frame, sync: &mut PendingSync) { + #[cfg(test)] + if frame.view_id == VIEW_3D { + ui.data_mut(|data| data.insert_temp(egui::Id::unique(TEST_SCENE_SET_HOVER), frame.shade.set_hover.map(|highlight| highlight.set))); + } + let tokens = Tokens::get(ui.ctx()); let bake = bake_visualization(app); frame.shade.bake = bake; @@ -1044,12 +1057,16 @@ fn view_3d(app: &mut TextureCraftApp, ui: &mut Ui, rect: Rect, sync: &mut Pendin } } + let set_hover = app + .hovered_texture_set + .filter(|&(project_id, _)| project_id == app.session.project_id && !app.ui.hide_ui && !crate::docking::input_blocked(app, ui.ctx())) + .map(|(_, texture_set)| set_highlight(ui, texture_set)); let frame = Frame { view_id: crate::viewport::VIEW_3D, size: frame_size_in_pixels(ui, rect), kind: ViewKind::Scene, camera: app.session.camera, - shade: Shade { highlight: drop_highlight(app, ui, &response), ..shade(app) }, + shade: Shade { highlight: drop_highlight(app, ui, &response), set_hover, ..shade(app) }, visible: app.session.doc.project.texture_sets.iter().map(|texture_set| texture_set.visible).collect(), overlay: crate::symmetry::scene_overlay(app, ui, rect), }; @@ -2519,6 +2536,46 @@ fn eyedrop(app: &mut TextureCraftApp, ctx: &egui::Context, bar: egui::Id, pixel: #[cfg(test)] mod tests { use super::*; + #[cfg(not(target_arch = "wasm32"))] + #[test] + fn hovering_a_texture_set_row_previews_it_without_selecting_it() { + use crate::state::Mode; + use egui_kittest::Harness; + use egui_kittest::kittest::Queryable; + + // App creation and frames both set the shared UI language + let _language_guard = crate::i18n::TEST_LANGUAGE.lock().unwrap_or_else(std::sync::PoisonError::into_inner); + + let session = + Session::new_project("Texture set hover", texturecraft_engine::geom::primitives::material_ball(), "builtin:material_ball", None, 128).unwrap(); + let hovered_set = 1; + let name = session.doc.project.texture_sets[hovered_set].name.clone(); + let selected_set = session.ts(); + assert_ne!(hovered_set, selected_set); + + let mut harness = Harness::builder().with_size(egui::vec2(1600.0, 1500.0)).build_eframe(|context| TextureCraftApp::new(context, session)); + let preview = |harness: &Harness<'_, TextureCraftApp>| { + harness.ctx.data(|data| data.get_temp::>(egui::Id::unique(TEST_SCENE_SET_HOVER))).expect("the 3D view submitted a scene frame") + }; + + for mode in [Mode::Painting, Mode::Baking] { + harness.state_mut().ui.mode = mode; + harness.run_steps(4); + assert_eq!(preview(&harness), None, "{mode:?}: the preview starts clear"); + + harness.get_by_label(&name).hover(); + harness.run_steps(3); + assert_eq!(preview(&harness), Some(hovered_set), "{mode:?}: the hovered set reaches the viewport"); + assert_eq!(harness.state().session.ts(), selected_set, "{mode:?}: hover keeps the selected set"); + + let away = harness.state().viewport_rect.center(); + harness.event(egui::Event::PointerMoved(away)); + harness.run_steps(3); + assert_eq!(preview(&harness), None, "{mode:?}: leaving the row clears the preview"); + assert_eq!(harness.state().session.ts(), selected_set, "{mode:?}: leaving the row keeps the selected set"); + } + } + #[test] fn the_hover_label_finds_the_tile_under_the_cursor_in_a_turned_view() { let session = Session::new_project("Tiles", texturecraft_engine::geom::primitives::udim_plane(), "builtin:udim_plane", None, 128).unwrap(); diff --git a/crates/ui-egui/src/windows.rs b/crates/ui-egui/src/windows.rs index a172926a..44ebc529 100644 --- a/crates/ui-egui/src/windows.rs +++ b/crates/ui-egui/src/windows.rs @@ -747,7 +747,7 @@ mod tests { harness.state_mut().ui.windows.export = true; harness.run_steps(5); let footer = harness.get_by_role_and_label(egui::Role::Button, "Reset all").rect(); - let first = harness.get_by_label("Export set 1"); + let first = harness.get_by_role_and_label(egui::Role::Button, "Export set 1"); first.hover(); harness.run_steps(2); @@ -759,7 +759,7 @@ mod tests { source: egui::MouseWheelSource::Wheel, }); harness.run_steps(15); - let last = harness.get_by_label("Export set 39"); + let last = harness.get_by_role_and_label(egui::Role::Button, "Export set 39"); last.click(); harness.run_steps(4); diff --git a/crates/ui-egui/tests/it/export_progress.rs b/crates/ui-egui/tests/it/export_progress.rs index b46b84a1..dc090d60 100644 --- a/crates/ui-egui/tests/it/export_progress.rs +++ b/crates/ui-egui/tests/it/export_progress.rs @@ -124,7 +124,10 @@ fn the_list_is_a_tree_per_texture_set_with_the_console_beside_it() { h.state_mut().ui.export.tab = 2; h.run_steps(4); let set = h.state().session.doc.project.texture_sets[0].name.clone(); - assert!(h.query_by_label(&set).is_some()); + assert!( + h.query_by_role_and_label(egui::Role::DisclosureTriangle, &set).is_some(), + "the export tree has a node for the set (the dock list row carries the same name)" + ); assert!(h.query_all_by_label("256x256 (Texture Set size)").next().is_some()); assert!(h.query_all_by_label("png").next().is_some() && h.query_all_by_label("16 bits").next().is_some()); assert!(h.query_by_label("Include all").is_none() && h.query_by_label("Reset all").is_none());