diff --git a/crates/engine/src/lib.rs b/crates/engine/src/lib.rs index 2f5887a6..cedf6cdb 100644 --- a/crates/engine/src/lib.rs +++ b/crates/engine/src/lib.rs @@ -22,13 +22,14 @@ pub mod layer_cmds; pub mod layer_ops; pub mod link_cmds; pub mod mask_cmds; -pub mod mask_preview; -mod mask_preview_camera; mod mask_preview_pixel; pub mod material_lib; +mod material_preview_pixel; pub mod materials; pub mod materialx_cmds; pub mod meshmap_cmds; +mod orb_camera; +pub mod orb_preview; pub mod painting; pub mod path_tool; // Mesh reimport reads files: native only. diff --git a/crates/engine/src/mask_preview.rs b/crates/engine/src/mask_preview.rs deleted file mode 100644 index a44757fc..00000000 --- a/crates/engine/src/mask_preview.rs +++ /dev/null @@ -1,161 +0,0 @@ -//! Smart mask previews share one baked [`primitives::preview_orb`] -//! Presets use `mask.smart.apply` and the compositor, matching document masks - -use serde_json::json; -use texturecraft_core::{BakeResolution, BakedMap, CurvatureMethod, LayerId}; -use texturecraft_geom::glam::Vec3; -use texturecraft_geom::primitives; - -use crate::mask_preview_camera::MaskPreviewCamera; -pub use crate::mask_preview_pixel::MaskPreviewPixel; -use crate::{EngineError, Result, Session}; - -/// Bake resolution in texels; 256 loses the thin edge lines -const TEXTURE_PX: u32 = 512; -/// Camera rays per preview pixel along each axis (anti-aliased outline) -const SUPERSAMPLE: usize = 2; -/// Bound camera samples and output allocations for shelf previews -pub const MAX_PREVIEW_SIZE_PX: usize = 512; -/// AO and thickness rays per texel; thumbnail detail needs fewer than the default -const OCCLUSION_RAYS: u32 = 12; -/// Curvature rays per texel; thumbnail detail needs fewer than the default -const CURVATURE_RAYS: u32 = 12; -/// Radius relative to the bounding box; isolates panel edges from the round body -const CURVATURE_RADIUS: f32 = 0.005; -/// The mesh maps the smart mask generators read -const MAPS: [BakedMap; 3] = [BakedMap::Curvature, BakedMap::AmbientOcclusion, BakedMap::Thickness]; -/// Keep camera views for the thumbnail and hover preview sizes -const CAMERAS_KEPT: usize = 2; - -/// The baked preview shape and, per preview size, what its camera sees -pub struct MaskPreview { - session: Session, - layer: LayerId, - /// Cached camera views, least recently used first - cameras: Vec, -} - -impl MaskPreview { - /// Bake the preview shape once (previews of any size reuse it) - pub fn new() -> Result { - let mut session = Session::new_project("Mask preview", primitives::preview_orb(), "builtin:preview_orb", None, TEXTURE_PX)?; - let set = session.doc.project.texture_set_mut(0)?; - set.bake.common.resolution = BakeResolution::from_pixels(TEXTURE_PX).ok_or_else(|| EngineError::Other("invalid bake resolution".into()))?; - set.bake.high_poly.use_low_as_high = true; - set.bake.maps.curvature.parameters.method = CurvatureMethod::Mesh; - set.bake.maps.curvature.parameters.mesh.sampling_radius = CURVATURE_RADIUS; - set.bake.maps.curvature.parameters.mesh.rays = CURVATURE_RAYS; - set.bake.maps.ao.parameters.rays.rays = OCCLUSION_RAYS; - set.bake.maps.thickness.parameters.rays.rays = OCCLUSION_RAYS; - for map in BakedMap::ALL { - set.bake.maps.set_enabled(map, MAPS.contains(&map)); - } - let layer = *set.stack.first().ok_or_else(|| EngineError::Other("the preview has no layer".into()))?; - session.bake_now(0, false)?; - - Ok(MaskPreview { session, layer, cameras: Vec::new() }) - } - - /// Row-major `size²` pixels, with None outside the shape - /// Returns None for unknown masks or sizes outside 1..=[`MAX_PREVIEW_SIZE_PX`] - pub fn render(&mut self, id: &str, size: usize) -> Option>> { - if !(1..=MAX_PREVIEW_SIZE_PX).contains(&size) { - return None; - } - - crate::execute(&mut self.session, "mask.smart.apply", &json!({ "name": id, "layer": self.layer.0 })).ok()?; - // Previews need no undo history; retaining snapshots grows memory across presets - self.session.undo.clear(); - - let camera = camera_for(&mut self.cameras, &self.session, size)?; - let values = self.session.mask_at(self.layer, &camera.texels)?; - - let sub_pixels = (SUPERSAMPLE * SUPERSAMPLE) as f32; - let pixels = (0..size * size) - .map(|i| { - let (x, y) = (i % size, i / size); - let (mut mask, mut normal, mut hits) = (0.0, Vec3::ZERO, 0.0); - for sy in 0..SUPERSAMPLE { - for sx in 0..SUPERSAMPLE { - let ray = (y * SUPERSAMPLE + sy) * camera.rays_per_side + x * SUPERSAMPLE + sx; - let Some(&Some((texel, n))) = camera.samples.get(ray) else { continue }; - - mask += values.get(texel).copied().unwrap_or(0.0); - normal += n; - hits += 1.0; - } - } - (hits > 0.0).then(|| MaskPreviewPixel { mask: mask / hits, normal: normal.normalize_or_zero(), coverage: hits / sub_pixels }) - }) - .collect(); - Some(pixels) - } -} - -/// Cache one camera per preview size, evicting the least recently used view -fn camera_for<'a>(cameras: &'a mut Vec, session: &Session, size: usize) -> Option<&'a MaskPreviewCamera> { - let rays_per_side = size * SUPERSAMPLE; - let camera = match cameras.iter().position(|c| c.rays_per_side == rays_per_side) { - Some(i) => cameras.remove(i), - None => MaskPreviewCamera::new(session, TEXTURE_PX, rays_per_side), - }; - if cameras.len() >= CAMERAS_KEPT { - cameras.remove(0); - } - - cameras.push(camera); - cameras.last() -} - -#[cfg(test)] -mod tests { - use super::*; - - /// Mean absolute difference of the masks of two previews over the pixels both see - fn difference(a: &[Option], b: &[Option]) -> f32 { - let pairs: Vec<(f32, f32)> = a.iter().zip(b).filter_map(|(a, b)| Some((a.as_ref()?.mask, b.as_ref()?.mask))).collect(); - pairs.iter().map(|(a, b)| (a - b).abs()).sum::() / pairs.len().max(1) as f32 - } - - #[test] - fn invalid_preview_sizes_are_rejected_before_changing_the_shape() { - let session = Session::new_project("Mask preview", primitives::cube(2.0), "builtin:cube", None, 128).unwrap(); - let layer = session.doc.project.texture_set(0).unwrap().stack[0]; - let mut preview = MaskPreview { session, layer, cameras: Vec::new() }; - for size in [0, MAX_PREVIEW_SIZE_PX + 1, usize::MAX / 2 + 1, usize::MAX] { - assert!(preview.render("edges_sharp", size).is_none(), "size {size} should be rejected before rendering"); - assert!(preview.cameras.is_empty(), "invalid sizes must not allocate a camera"); - assert!(preview.session.doc.project.layer(layer).unwrap().mask.is_none(), "invalid sizes must not apply a mask"); - } - } - - #[test] - fn smart_mask_previews_are_in_range_tell_edges_from_cavities_and_render_at_any_size() { - let size = 24; - let mut preview = MaskPreview::new().unwrap(); - for sm in crate::smart_masks::SMART_MASKS { - let px = preview.render(sm.id, size).unwrap_or_else(|| panic!("{}", sm.id)); - assert_eq!(px.len(), size * size, "{}", sm.id); - assert!(px[0].is_none(), "{}: the corners are outside the shape", sm.id); - let seen: Vec<&MaskPreviewPixel> = px.iter().flatten().collect(); - assert!(seen.len() > size * size / 3, "{}: the shape fills the frame", sm.id); - for p in seen { - assert!((0.0..=1.0).contains(&p.mask) && (0.0..=1.0).contains(&p.coverage) && p.coverage > 0.0, "{}: {p:?}", sm.id); - assert!(p.normal.is_finite(), "{}: {p:?}", sm.id); - } - } - - let (edges, cavities) = (preview.render("edges_sharp", size).unwrap(), preview.render("dirt_cavities", size).unwrap()); - let shows = |px: &[Option]| px.iter().flatten().any(|p| p.mask > 0.5); - assert!(shows(&edges) && shows(&cavities), "both masks find something on the shape"); - assert!(difference(&edges, &cavities) > 0.05, "edges and cavities differ: {}", difference(&edges, &cavities)); - assert!(preview.render("nope", size).is_none()); - - let big = preview.render("edges_sharp", size * 3).unwrap(); - let mean = |px: &[Option]| px.iter().flatten().map(|p| p.mask).sum::() / px.iter().flatten().count().max(1) as f32; - assert_eq!(big.len(), size * size * 9); - assert!((mean(&big) - mean(&edges)).abs() < 0.05, "{} vs {}", mean(&big), mean(&edges)); - preview.render("edges_sharp", size * 2).unwrap(); - assert_eq!(preview.cameras.len(), CAMERAS_KEPT, "only the most recent sizes keep their camera"); - } -} diff --git a/crates/engine/src/mask_preview_pixel.rs b/crates/engine/src/mask_preview_pixel.rs index bcde5629..14ad5842 100644 --- a/crates/engine/src/mask_preview_pixel.rs +++ b/crates/engine/src/mask_preview_pixel.rs @@ -1,4 +1,4 @@ -//! One pixel of a smart mask preview (see [`crate::mask_preview::MaskPreview`]). +//! One pixel of a smart mask preview (see [`crate::orb_preview::OrbPreview::mask`]) use texturecraft_geom::glam::Vec3; diff --git a/crates/engine/src/material_preview_pixel.rs b/crates/engine/src/material_preview_pixel.rs new file mode 100644 index 00000000..7b83422e --- /dev/null +++ b/crates/engine/src/material_preview_pixel.rs @@ -0,0 +1,16 @@ +//! One pixel of a smart material preview (see [`crate::orb_preview::OrbPreview::material`]) + +use texturecraft_geom::glam::Vec3; + +use crate::preview::Sample; + +/// The material values seen at a preview pixel, with what a display needs to light the shape +#[derive(Clone, Copy, Debug, PartialEq)] +pub struct MaterialPreviewPixel { + /// Linear material values, averaged over the pixel + pub sample: Sample, + /// Surface normal in view space (+X right, +Y up, +Z towards the viewer) + pub normal: Vec3, + /// Fraction of the pixel the shape covers (0..=1, anti-aliased outline) + pub coverage: f32, +} diff --git a/crates/engine/src/mask_preview_camera.rs b/crates/engine/src/orb_camera.rs similarity index 69% rename from crates/engine/src/mask_preview_camera.rs rename to crates/engine/src/orb_camera.rs index ea3d6d1f..d0015361 100644 --- a/crates/engine/src/mask_preview_camera.rs +++ b/crates/engine/src/orb_camera.rs @@ -1,4 +1,4 @@ -//! Cached camera rays for one smart mask preview size +//! Cached camera rays for one preview orb size use std::collections::HashMap; @@ -11,11 +11,11 @@ use crate::Session; const CAMERA_PITCH_DEG: f32 = 35.0; const CAMERA_YAW_DEG: f32 = -34.4; -/// Index into [`MaskPreviewCamera::texels`] and view-space normal; None on a miss +/// Index into [`OrbCamera::texels`] and view-space normal; None on a miss pub(crate) type CameraSample = Option<(usize, Vec3)>; -/// What each ray of a square orthographic view of the preview shape sees -pub(crate) struct MaskPreviewCamera { +/// What each ray of a square orthographic view of the orb sees +pub(crate) struct OrbCamera { /// Rays along each side of the view pub rays_per_side: usize, /// The texels (x, y) the camera sees, each once @@ -24,12 +24,12 @@ pub(crate) struct MaskPreviewCamera { pub samples: Vec, } -impl MaskPreviewCamera { +impl OrbCamera { /// Trace a square orthographic view onto a `texture_px²` texture - pub fn new(session: &Session, texture_px: u32, rays_per_side: usize) -> MaskPreviewCamera { - let (lo, hi) = session.mesh.bounds(); - let center = (lo + hi) * 0.5; - let radius = session.mesh.positions.iter().map(|p| p.distance(center)).fold(0.0f32, f32::max); + pub fn new(session: &Session, texture_px: u32, rays_per_side: usize) -> OrbCamera { + let (min, max) = session.mesh.bounds(); + let center = (min + max) * 0.5; + let radius = session.mesh.positions.iter().map(|position| position.distance(center)).fold(0.0f32, f32::max); let pitch = CAMERA_PITCH_DEG.to_radians(); let turn = Quat::from_rotation_y(CAMERA_YAW_DEG.to_radians()); let forward = turn * Vec3::new(0.0, -pitch.sin(), -pitch.cos()); @@ -40,9 +40,9 @@ impl MaskPreviewCamera { let mut texels = Vec::new(); let mut index_of = HashMap::new(); let samples = (0..rays_per_side * rays_per_side) - .map(|i| { + .map(|ray| { let side = rays_per_side as f32; - let ndc = Vec2::new(((i % rays_per_side) as f32 + 0.5) / side * 2.0 - 1.0, 1.0 - ((i / rays_per_side) as f32 + 0.5) / side * 2.0); + let ndc = Vec2::new(((ray % rays_per_side) as f32 + 0.5) / side * 2.0 - 1.0, 1.0 - ((ray / rays_per_side) as f32 + 0.5) / side * 2.0); // Start well outside the shape so every ray enters it from the front let origin = center + (right * ndc.x + up * ndc.y) * radius - forward * radius * 4.0; let hit = session.bvh.closest(origin, forward, radius * 8.0)?; @@ -52,10 +52,12 @@ impl MaskPreviewCamera { texels.push(texel); texels.len() - 1 }); - let n = surface.nrm; - Some((index, Vec3::new(n.dot(right), n.dot(up), -n.dot(forward)))) + + let normal = surface.nrm; + Some((index, Vec3::new(normal.dot(right), normal.dot(up), -normal.dot(forward)))) }) .collect(); - MaskPreviewCamera { rays_per_side, texels, samples } + + OrbCamera { rays_per_side, texels, samples } } } diff --git a/crates/engine/src/orb_preview.rs b/crates/engine/src/orb_preview.rs new file mode 100644 index 00000000..f29a247d --- /dev/null +++ b/crates/engine/src/orb_preview.rs @@ -0,0 +1,297 @@ +//! Smart mask and smart material previews share one baked [`primitives::preview_orb`] +//! Presets use `mask.smart.apply`, materials use [`materials::apply`], both read back from the compositor + +use std::collections::{BTreeMap, BTreeSet}; + +use serde_json::json; +use texturecraft_core::{BakeResolution, BakedMap, Channel, CurvatureMethod, LayerId}; +use texturecraft_geom::glam::Vec3; +use texturecraft_geom::primitives; +use texturecraft_texel::TILE; + +pub use crate::mask_preview_pixel::MaskPreviewPixel; +pub use crate::material_preview_pixel::MaterialPreviewPixel; +use crate::orb_camera::OrbCamera; +use crate::preview::Sample; +use crate::session::Document; +use crate::{EngineError, Result, Session, materials}; + +/// Bake resolution in texels; 256 loses the thin edge lines +const TEXTURE_PX: u32 = 512; +/// Camera rays per preview pixel along each axis (anti-aliased outline) +const SUPERSAMPLE: usize = 2; +/// Bound camera samples and output allocations for shelf previews +pub const MAX_PREVIEW_SIZE_PX: usize = 512; +/// AO and thickness rays per texel; thumbnail detail needs fewer than the default +const OCCLUSION_RAYS: u32 = 12; +/// Curvature rays per texel; thumbnail detail needs fewer than the default +const CURVATURE_RAYS: u32 = 12; +/// Radius relative to the bounding box; isolates panel edges from the round body +const CURVATURE_RADIUS: f32 = 0.005; +/// The mesh maps the smart mask generators read; smart materials build on the same presets +const MAPS: [BakedMap; 3] = [BakedMap::Curvature, BakedMap::AmbientOcclusion, BakedMap::Thickness]; +/// Keep camera views for the thumbnail and hover preview sizes +const CAMERAS_KEPT: usize = 2; +/// The channels a material preview shows, in [`Sample`] order +const MATERIAL_CHANNELS: [Channel; 4] = [Channel::BaseColor, Channel::Metallic, Channel::Roughness, Channel::Height]; +/// The orb's only texture set +const SET: usize = 0; + +/// The baked orb and, per preview size, what its camera sees +pub struct OrbPreview { + session: Session, + /// The layer smart masks are applied to + layer: LayerId, + /// The baked document and selection, restored before each material + bare: (Document, BTreeMap), + /// Cached camera views, least recently used first + cameras: Vec, +} + +impl OrbPreview { + /// Bake the orb once (previews of any size reuse it) + pub fn new() -> Result { + let mut session = Session::new_project("Orb preview", primitives::preview_orb(), "builtin:preview_orb", None, TEXTURE_PX)?; + let set = session.doc.project.texture_set_mut(SET)?; + set.bake.common.resolution = BakeResolution::from_pixels(TEXTURE_PX).ok_or_else(|| EngineError::Other("invalid bake resolution".into()))?; + set.bake.high_poly.use_low_as_high = true; + set.bake.maps.curvature.parameters.method = CurvatureMethod::Mesh; + set.bake.maps.curvature.parameters.mesh.sampling_radius = CURVATURE_RADIUS; + set.bake.maps.curvature.parameters.mesh.rays = CURVATURE_RAYS; + set.bake.maps.ao.parameters.rays.rays = OCCLUSION_RAYS; + set.bake.maps.thickness.parameters.rays.rays = OCCLUSION_RAYS; + for map in BakedMap::ALL { + set.bake.maps.set_enabled(map, MAPS.contains(&map)); + } + let layer = *set.stack.first().ok_or_else(|| EngineError::Other("the preview has no layer".into()))?; + session.bake_now(SET, false)?; + + let bare = (session.doc.clone(), session.selected.clone()); + Ok(OrbPreview { session, layer, bare, cameras: Vec::new() }) + } + + /// Row-major `size²` pixels of smart mask `id`, with None outside the shape + /// Returns None for unknown masks or sizes outside 1..=[`MAX_PREVIEW_SIZE_PX`] + pub fn mask(&mut self, id: &str, size: usize) -> Option>> { + if !valid_size(size) { + return None; + } + + crate::execute(&mut self.session, "mask.smart.apply", &json!({ "name": id, "layer": self.layer.0 })).ok()?; + // Previews need no undo history; retaining snapshots grows memory across presets + self.session.undo.clear(); + + let camera = camera_for(&mut self.cameras, &self.session, size)?; + let values = self.session.mask_at(self.layer, &camera.texels)?; + + let sub_pixels = (SUPERSAMPLE * SUPERSAMPLE) as f32; + let pixels = (0..size * size) + .map(|pixel| { + let (mut mask_sum, mut normal_sum, mut hits) = (0.0, Vec3::ZERO, 0.0); + for (texel, normal) in pixel_hits(camera, size, pixel) { + mask_sum += values.get(texel).copied().unwrap_or(0.0); + normal_sum += normal; + hits += 1.0; + } + + (hits > 0.0).then(|| MaskPreviewPixel { mask: mask_sum / hits, normal: normal_sum.normalize_or_zero(), coverage: hits / sub_pixels }) + }) + .collect(); + Some(pixels) + } + + /// Row-major `size²` pixels of built-in material `id`, with None outside the shape + /// Returns None for unknown materials or sizes outside 1..=[`MAX_PREVIEW_SIZE_PX`] + pub fn material(&mut self, id: &str, size: usize) -> Option>> { + if !valid_size(size) { + return None; + } + + // Each material goes on the bare shape, not over the previous one + (self.session.doc, self.session.selected) = self.bare.clone(); + let applied = materials::apply(&mut self.session, id); + // Previews need no undo history; retaining snapshots grows memory across materials + self.session.undo.clear(); + applied.ok()?; + + let camera = camera_for(&mut self.cameras, &self.session, size)?; + let values = material_at(&self.session, &camera.texels)?; + + let sub_pixels = (SUPERSAMPLE * SUPERSAMPLE) as f32; + let pixels = (0..size * size) + .map(|pixel| { + let mut sum = Sample { base: [0.0; 3], metallic: 0.0, roughness: 0.0, height: 0.0 }; + let (mut normal_sum, mut hits) = (Vec3::ZERO, 0.0); + for (texel, normal) in pixel_hits(camera, size, pixel) { + let Some(value) = values.get(texel) else { continue }; + + sum.base = [0, 1, 2].map(|component| sum.base[component] + value.base[component]); + sum.metallic += value.metallic; + sum.roughness += value.roughness; + sum.height += value.height; + normal_sum += normal; + hits += 1.0; + } + + (hits > 0.0).then(|| { + let mean = Sample { + base: sum.base.map(|component| component / hits), + metallic: sum.metallic / hits, + roughness: sum.roughness / hits, + height: sum.height / hits, + }; + MaterialPreviewPixel { sample: mean, normal: normal_sum.normalize_or_zero(), coverage: hits / sub_pixels } + }) + }) + .collect(); + Some(pixels) + } +} + +/// Preview sizes the camera may allocate +fn valid_size(size: usize) -> bool { + (1..=MAX_PREVIEW_SIZE_PX).contains(&size) +} + +/// The rays through `pixel` of a `size²` preview that hit the shape, as (texel index, view-space normal) +fn pixel_hits(camera: &OrbCamera, size: usize, pixel: usize) -> impl Iterator + '_ { + let (x, y) = (pixel % size, pixel / size); + (0..SUPERSAMPLE * SUPERSAMPLE).filter_map(move |sub_pixel| { + let (sub_x, sub_y) = (sub_pixel % SUPERSAMPLE, sub_pixel / SUPERSAMPLE); + let ray = (y * SUPERSAMPLE + sub_y) * camera.rays_per_side + x * SUPERSAMPLE + sub_x; + camera.samples.get(ray).copied().flatten() + }) +} + +/// The material values at `texels`, compositing only the tiles that hold them +fn material_at(session: &Session, texels: &[(u32, u32)]) -> Option> { + let tiles: BTreeSet<(u32, u32)> = texels.iter().map(|(x, y)| (x / TILE, y / TILE)).collect(); + let tiles: Vec<(u32, u32)> = tiles.into_iter().collect(); + + session.with_inputs(SET, |inputs| { + let mut composite = texturecraft_compose::Composite::new(&MATERIAL_CHANNELS, TEXTURE_PX); + texturecraft_compose::composite_tiles(inputs, &mut composite, &tiles); + + let samples = texels + .iter() + .map(|&(x, y)| { + let [base, metallic, roughness, height] = MATERIAL_CHANNELS.map(|channel| composite.value(channel, x, y)); + Sample { base, metallic: metallic[0], roughness: roughness[0], height: height[0] } + }) + .collect(); + Some(samples) + }) +} + +/// Cache one camera per preview size, evicting the least recently used view +fn camera_for<'a>(cameras: &'a mut Vec, session: &Session, size: usize) -> Option<&'a OrbCamera> { + let rays_per_side = size * SUPERSAMPLE; + let camera = match cameras.iter().position(|camera| camera.rays_per_side == rays_per_side) { + Some(index) => cameras.remove(index), + None => OrbCamera::new(session, TEXTURE_PX, rays_per_side), + }; + if cameras.len() >= CAMERAS_KEPT { + cameras.remove(0); + } + + cameras.push(camera); + cameras.last() +} + +#[cfg(test)] +mod tests { + use super::*; + + /// Mean absolute difference of the masks of two previews over the pixels both see + fn difference(a: &[Option], b: &[Option]) -> f32 { + let pairs: Vec<(f32, f32)> = a.iter().zip(b).filter_map(|(a, b)| Some((a.as_ref()?.mask, b.as_ref()?.mask))).collect(); + pairs.iter().map(|(a, b)| (a - b).abs()).sum::() / pairs.len().max(1) as f32 + } + + /// Mean mask value over the pixels a preview sees + fn mean_mask(pixels: &[Option]) -> f32 { + pixels.iter().flatten().map(|pixel| pixel.mask).sum::() / pixels.iter().flatten().count().max(1) as f32 + } + + #[test] + fn invalid_preview_sizes_are_rejected_before_changing_the_shape() { + let session = Session::new_project("Orb preview", primitives::cube(2.0), "builtin:cube", None, 128).unwrap(); + let layer = session.doc.project.texture_set(SET).unwrap().stack[0]; + let bare = (session.doc.clone(), session.selected.clone()); + let mut preview = OrbPreview { session, layer, bare, cameras: Vec::new() }; + let stack_size = preview.session.doc.project.texture_set(SET).unwrap().stack.len(); + for size in [0, MAX_PREVIEW_SIZE_PX + 1, usize::MAX / 2 + 1, usize::MAX] { + assert!(preview.mask("edges_sharp", size).is_none(), "size {size} should be rejected before rendering"); + assert!(preview.material("steel_painted_worn", size).is_none(), "size {size} should be rejected before rendering"); + assert!(preview.cameras.is_empty(), "invalid sizes must not allocate a camera"); + assert!(preview.session.doc.project.layer(layer).unwrap().mask.is_none(), "invalid sizes must not apply a mask"); + assert_eq!(preview.session.doc.project.texture_set(SET).unwrap().stack.len(), stack_size, "invalid sizes must not apply a material"); + } + } + + #[test] + fn smart_mask_previews_are_in_range_tell_edges_from_cavities_and_render_at_any_size() { + let size = 24; + let mut preview = OrbPreview::new().unwrap(); + for smart_mask in crate::smart_masks::SMART_MASKS { + let id = smart_mask.id; + let pixels = preview.mask(id, size).unwrap_or_else(|| panic!("{id}")); + assert_eq!(pixels.len(), size * size, "{id}"); + assert!(pixels[0].is_none(), "{id}: the corners are outside the shape"); + + let seen: Vec<&MaskPreviewPixel> = pixels.iter().flatten().collect(); + assert!(seen.len() > size * size / 3, "{id}: the shape fills the frame"); + for pixel in seen { + assert!((0.0..=1.0).contains(&pixel.mask) && (0.0..=1.0).contains(&pixel.coverage) && pixel.coverage > 0.0, "{id}: {pixel:?}"); + assert!(pixel.normal.is_finite(), "{id}: {pixel:?}"); + } + } + + let (edges, cavities) = (preview.mask("edges_sharp", size).unwrap(), preview.mask("dirt_cavities", size).unwrap()); + let shows = |pixels: &[Option]| pixels.iter().flatten().any(|pixel| pixel.mask > 0.5); + assert!(shows(&edges) && shows(&cavities), "both masks find something on the shape"); + assert!(difference(&edges, &cavities) > 0.05, "edges and cavities differ: {}", difference(&edges, &cavities)); + assert!(preview.mask("nope", size).is_none()); + + // The same bake renders other sizes, showing the same mask + let big = preview.mask("edges_sharp", size * 3).unwrap(); + assert_eq!(big.len(), size * size * 9); + assert!((mean_mask(&big) - mean_mask(&edges)).abs() < 0.05, "{} vs {}", mean_mask(&big), mean_mask(&edges)); + + preview.mask("edges_sharp", size * 2).unwrap(); + assert_eq!(preview.cameras.len(), CAMERAS_KEPT, "only the most recent sizes keep their camera"); + } + + #[test] + fn smart_materials_render_on_the_orb_and_show_their_wear() { + let size = 24; + let mut preview = OrbPreview::new().unwrap(); + for material in materials::MATERIALS.iter().filter(|material| material.smart) { + let id = material.id; + let pixels = preview.material(id, size).unwrap_or_else(|| panic!("{id}")); + assert_eq!(pixels.len(), size * size, "{id}"); + assert!(pixels[0].is_none(), "{id}: the corners are outside the shape"); + + for pixel in pixels.iter().flatten() { + let sample = pixel.sample; + let values = sample.base.into_iter().chain([sample.metallic, sample.roughness, sample.height]); + assert!(values.into_iter().all(f32::is_finite), "{id}: {pixel:?}"); + assert!(pixel.normal.is_finite() && pixel.coverage > 0.0, "{id}: {pixel:?}"); + } + } + assert!(preview.material("nope", size).is_none()); + + // Paint chipped at the edges shows the steel under it: the smart material is not its base + let (worn, steel) = (preview.material("steel_painted_worn", size).unwrap(), preview.material("steel", size).unwrap()); + let metallic_pixels = |pixels: &[Option]| pixels.iter().flatten().filter(|pixel| pixel.sample.metallic > 0.5).count(); + let (worn_metallic, steel_metallic) = (metallic_pixels(&worn), metallic_pixels(&steel)); + assert!(worn_metallic > 0 && worn_metallic < steel_metallic / 2, "bare steel only at the worn edges: {worn_metallic} of {steel_metallic}"); + + let base_colors = |pixels: &[Option]| pixels.iter().flatten().map(|pixel| pixel.sample.base).collect::>(); + assert_ne!(base_colors(&worn), base_colors(&steel)); + + // Each material starts from the bare orb: rendering another one in between changes nothing + preview.material("iron_rusted", size).unwrap(); + assert_eq!(preview.material("steel_painted_worn", size).unwrap(), worn); + } +} diff --git a/crates/engine/src/preview.rs b/crates/engine/src/preview.rs index 5b72cea4..ce45b9ff 100644 --- a/crates/engine/src/preview.rs +++ b/crates/engine/src/preview.rs @@ -1,14 +1,8 @@ -//! Shelf previews: built-in materials evaluated on a unit sphere seen from +Z, without a mesh or -//! baked maps (generators that need mesh maps are approximated with world-space noise), and -//! library filters. Cheap enough for lazily rendered thumbnails. Smart masks have their own baked -//! preview ([`crate::mask_preview`]). +//! Cheap shelf previews on a unit sphere: plain materials and library filters (smart ones use [`crate::orb_preview`]) use rayon::prelude::*; -use texturecraft_compose::pattern::{Coords, procedural, world_noise}; -use texturecraft_core::{ - Channel, Effect, EffectKind, Fill, Filter, Generator, GeneratorKind, Layer, LayerKind, Mask, MaskBackground, Procedural, ProceduralKind, Project, - Projection, Source, TextureSet, blend1, -}; +use texturecraft_compose::pattern::{Coords, procedural}; +use texturecraft_core::{Channel, Effect, EffectKind, Fill, Filter, Layer, LayerKind, Procedural, ProceduralKind, Project, Projection, Source, TextureSet}; use texturecraft_geom::glam::{Vec2, Vec3}; use crate::materials::{Builder, build}; @@ -50,54 +44,13 @@ fn source(s: &Source, proj: &Projection, c: &Coords) -> Option<[f32; 3]> { } } -/// Approximate generator: mesh-map signals become world noise (a sphere has no edges or cavities). -fn generator(g: &Generator, c: &Coords) -> f32 { - let dir = Vec3::from(g.direction).try_normalize().unwrap_or(Vec3::Y); - let wear = (world_noise(c.pos, 3.0, 91) - 0.5) * 2.2; - let cavity = (world_noise(c.pos, 3.0, 57) - 0.3).clamp(0.0, 1.0) + (1.0 - c.nrm.y) * 0.1; - let s = match g.kind { - GeneratorKind::Position => c.pos.dot(dir) * 0.5 + 0.5, - GeneratorKind::Direction => c.nrm.dot(dir) * 0.5 + 0.5, - GeneratorKind::EdgeWear => wear, - GeneratorKind::Curvature => 0.5 + wear * 0.5, - GeneratorKind::AmbientOcclusion => 1.0 - cavity, - _ => cavity, - }; - // Same thresholding as the compositor. - let s = if g.noise_amount > 0.0 { s + (world_noise(c.pos, g.noise_scale, g.seed) - 0.5) * g.noise_amount } else { s }; - let soft = g.softness.max(1e-3); - let t = ((s - (1.0 - g.level.clamp(0.0, 1.0) - soft)) / (2.0 * soft)).clamp(0.0, 1.0); - let v = t * t * (3.0 - 2.0 * t); - if g.invert { 1.0 - v } else { v } -} - -fn mask(m: &Mask, c: &Coords) -> f32 { - if !m.enabled { - return 1.0; - } - let mut v = if m.background == MaskBackground::White { 1.0 } else { 0.0 }; - for e in m.effects.iter().filter(|e| e.visible) { - let val = match &e.kind { - EffectKind::Fill { source: s, projection } => source(s, projection, c).map(|x| x[0]), - EffectKind::Generator(g) => Some(generator(g, c)), - EffectKind::Levels(l) => Some(l.apply(v)), - EffectKind::Filter(Filter::Invert) => Some(1.0 - v), - _ => None, - }; - if let Some(val) = val { - let blended = if matches!(e.kind, EffectKind::Levels(_) | EffectKind::Filter(_)) { val } else { blend1(e.blend, v, val) }; - v += (blended - v) * e.opacity.clamp(0.0, 1.0); - } - } - v.clamp(0.0, 1.0) -} - const CHANNELS: [Channel; 4] = [Channel::BaseColor, Channel::Metallic, Channel::Roughness, Channel::Height]; -/// Preview of built-in material `id` (None for an unknown id). +/// Preview of plain material `id` (None for an unknown id or a smart material, whose masks need mesh maps) pub fn material(id: &str, size: usize) -> Option>> { + let plain = crate::materials::find(id).filter(|found| !found.smart)?; let mut project = Project::new("preview", ""); - let layers = build(&mut Builder { p: &mut project, channels: CHANNELS.to_vec() }, id).ok()?; + let layers = build(&mut Builder { p: &mut project, channels: CHANNELS.to_vec() }, plain.id).ok()?; // Pixels evaluate independently and big previews take long on one core let normals: Vec<_> = sphere_normals(size).collect(); @@ -106,23 +59,24 @@ pub fn material(id: &str, size: usize) -> Option>> { .map(|normal| { let at = coords(normal?); let mut values = CHANNELS.map(Channel::default_value); - for layer in layers.iter().filter(|l| l.visible) { + for layer in layers.iter().filter(|layer| layer.visible) { + // Plain materials are unmasked fills let LayerKind::Fill(fill) = &layer.kind else { continue }; - let coverage = layer.mask.as_ref().map_or(1.0, |m| mask(m, &at)); for (value, channel) in values.iter_mut().zip(CHANNELS) { - let layer_value = fill.sources.get(&channel).and_then(|s| source(s, &fill.projection, &at)); + let layer_value = fill.sources.get(&channel).and_then(|channel_source| source(channel_source, &fill.projection, &at)); if let (Some(blend), Some(layer_value)) = (layer.blend(channel), layer_value) { - let weight = coverage * blend.opacity.clamp(0.0, 1.0); - *value = [0, 1, 2].map(|k| value[k] + (layer_value[k] - value[k]) * weight); + let weight = blend.opacity.clamp(0.0, 1.0); + *value = [0, 1, 2].map(|component| value[component] + (layer_value[component] - value[component]) * weight); } } } - let [base, metal, rough, height] = values; - Some(Sample { base, metallic: metal[0], roughness: rough[0], height: height[0] }) + let [base, metallic, roughness, height] = values; + Some(Sample { base, metallic: metallic[0], roughness: roughness[0], height: height[0] }) }) .collect(); + Some(samples) } @@ -196,21 +150,40 @@ pub fn filter(id: &str, size: usize) -> Option>> { mod tests { use super::*; + /// Whether every value of `sample` is finite + fn finite(sample: &Sample) -> bool { + sample.base.into_iter().chain([sample.metallic, sample.roughness, sample.height]).all(f32::is_finite) + } + #[test] fn previews_cover_the_sphere_with_finite_values() { - for m in crate::materials::MATERIALS { - let px = material(m.id, 16).unwrap_or_else(|| panic!("{}", m.id)); - let center = px[8 * 16 + 8].unwrap_or_else(|| panic!("{}", m.id)); - assert!(center.base.iter().chain([¢er.metallic, ¢er.roughness, ¢er.height]).all(|v| v.is_finite()), "{}", m.id); - assert!(px[0].is_none(), "corners are outside the sphere"); + let size = 16; + for built_in in crate::materials::MATERIALS { + let id = built_in.id; + if built_in.smart { + assert!(material(id, size).is_none(), "{id}: smart materials preview on the orb"); + continue; + } + + let mut project = Project::new("preview", ""); + let layers = build(&mut Builder { p: &mut project, channels: CHANNELS.to_vec() }, id).unwrap(); + assert!(layers.iter().all(|layer| layer.mask.is_none()), "{id}: the sphere preview shows no masks"); + + let pixels = material(id, size).unwrap_or_else(|| panic!("{id}")); + let center = pixels[size / 2 * size + size / 2].unwrap_or_else(|| panic!("{id}")); + assert!(finite(¢er), "{id}"); + assert!(pixels[0].is_none(), "corners are outside the sphere"); } - assert!(material("nope", 8).is_none() && filter("nope", 8).is_none()); - for f in crate::filter_lib::FILTERS { - let px = filter(f.id, 24).unwrap_or_else(|| panic!("{}", f.id)); - let center = px[12 * 24 + 12].unwrap_or_else(|| panic!("{}", f.id)); - assert!(center.base.iter().chain([¢er.roughness, ¢er.height]).all(|v| v.is_finite()), "{}", f.id); + assert!(material("nope", size).is_none() && filter("nope", size).is_none()); + + let size = 24; + for library_filter in crate::filter_lib::FILTERS { + let id = library_filter.id; + let pixels = filter(id, size).unwrap_or_else(|| panic!("{id}")); + let center = pixels[size / 2 * size + size / 2].unwrap_or_else(|| panic!("{id}")); + assert!(finite(¢er), "{id}"); } - let (plain, warped) = (filter("levels", 24).unwrap(), filter("warp", 24).unwrap()); + let (plain, warped) = (filter("levels", size).unwrap(), filter("warp", size).unwrap()); assert!(plain != warped, "the warp shows in its preview"); } } diff --git a/crates/geom/src/primitives.rs b/crates/geom/src/primitives.rs index 29bad947..69fab43b 100644 --- a/crates/geom/src/primitives.rs +++ b/crates/geom/src/primitives.rs @@ -201,7 +201,7 @@ const ORB_CUT: f32 = 0.8; /// [`preview_orb`] domed panels: where the valley sits, as a fraction of the face rim radius. const ORB_PANEL_VALLEY: f32 = 0.88; -/// The smart mask preview shape: a sphere cut flat by a cube on six sides, on a thin round base. +/// The preview orb of the smart mask and smart material previews: a sphere cut flat by a cube on six sides, on a thin round base /// Each feature gives one kind of mask something to show: sharp face rims (edges), a softly /// blended left face (soft edges), domed panels inside the front, left and top faces whose valleys /// hold dirt (cavities), a slot around the middle (cavity), the base (thin part, the seam where it diff --git a/crates/ui-egui/src/lib.rs b/crates/ui-egui/src/lib.rs index 375ff1ba..f383c197 100644 --- a/crates/ui-egui/src/lib.rs +++ b/crates/ui-egui/src/lib.rs @@ -17,8 +17,9 @@ pub mod gpu; pub mod i18n; pub mod keymap; mod mask_preview_image; -mod mask_shape; +mod material_preview_image; pub mod menus; +mod orb_shape; pub mod parity; mod preview_image; mod preview_request; @@ -27,6 +28,7 @@ pub mod profile; pub mod render_mode; pub mod shelf; pub mod shelf_preview; +mod soft_box; pub mod state; pub mod theme; pub mod thumbs; diff --git a/crates/ui-egui/src/mask_preview_image.rs b/crates/ui-egui/src/mask_preview_image.rs index 4418d099..de7368df 100644 --- a/crates/ui-egui/src/mask_preview_image.rs +++ b/crates/ui-egui/src/mask_preview_image.rs @@ -2,7 +2,7 @@ use egui::{Color32, ColorImage}; use texturecraft_engine::geom::glam::Vec3; -use texturecraft_engine::mask_preview::MaskPreviewPixel; +use texturecraft_engine::orb_preview::MaskPreviewPixel; use texturecraft_engine::texel::linear_to_srgb; /// View-space lighting uses an upper-left key and a weaker right fill diff --git a/crates/ui-egui/src/mask_shape.rs b/crates/ui-egui/src/mask_shape.rs deleted file mode 100644 index c99a9b1c..00000000 --- a/crates/ui-egui/src/mask_shape.rs +++ /dev/null @@ -1,33 +0,0 @@ -//! The smart mask preview shape, baked on first use - -use texturecraft_engine::mask_preview::MaskPreview; - -/// Whether the smart mask preview shape is baked -#[derive(Default)] -pub enum MaskShape { - #[default] - NotBaked, - /// Box the large session to keep the unbaked worker small - Baked(Box), - /// The bake failed; smart mask previews stay empty - Failed, -} - -impl MaskShape { - /// Bake on first use; retain failure to avoid retrying every frame - pub fn get(&mut self) -> Option<&mut MaskPreview> { - if matches!(self, MaskShape::NotBaked) { - *self = match MaskPreview::new() { - Ok(preview) => MaskShape::Baked(Box::new(preview)), - Err(e) => { - log::warn!("smart mask previews: {e}"); - MaskShape::Failed - } - }; - } - match self { - MaskShape::Baked(preview) => Some(preview), - MaskShape::NotBaked | MaskShape::Failed => None, - } - } -} diff --git a/crates/ui-egui/src/material_preview_image.rs b/crates/ui-egui/src/material_preview_image.rs new file mode 100644 index 00000000..bc232b75 --- /dev/null +++ b/crates/ui-egui/src/material_preview_image.rs @@ -0,0 +1,100 @@ +//! Shading of the smart material previews: a dark studio whose soft boxes show in reflections and light the diffuse color + +use egui::{Color32, ColorImage}; +use texturecraft_engine::geom::glam::Vec3; +use texturecraft_engine::orb_preview::MaterialPreviewPixel; +use texturecraft_engine::texel::linear_to_srgb; + +use crate::preview_image::{aces, bumped_normal, height_slope, preview_radius}; +use crate::soft_box::{SoftBox, smoothstep}; + +/// The studio's soft boxes: a key at the upper right, a fill at the left and a rim light above and behind +const SOFT_BOXES: [SoftBox; 3] = [ + SoftBox { direction: [0.55, 0.75, 0.35], radius_rad: 0.6, intensity: 2.6 }, + SoftBox { direction: [-0.95, 0.2, 0.1], radius_rad: 0.7, intensity: 0.9 }, + SoftBox { direction: [0.1, 0.9, -0.45], radius_rad: 0.35, intensity: 1.6 }, +]; +/// The studio's backdrop brightness straight down and straight up (linear) +const FLOOR: f32 = 0.03; +const CEILING: f32 = 0.16; +/// The lowest roughness shaded (a perfect mirror would show the soft boxes' hard edges) +const MIN_ROUGHNESS: f32 = 0.02; +/// Reflectance of dielectrics at normal incidence +const DIELECTRIC_F0: f32 = 0.04; +/// Exposure before tone mapping +const EXPOSURE: f32 = 1.4; + +/// A smart material preview (sRGB, transparent off the shape) from `size²` preview pixels; height bumps the normals +pub fn material_preview_image(size: usize, pixels: &[Option]) -> ColorImage { + let radius = preview_radius(size); + let height = |index: usize| pixels.get(index).copied().flatten().map(|pixel| pixel.sample.height); + let mut image = ColorImage::filled([size, size], Color32::TRANSPARENT); + + for (index, (out, pixel)) in image.pixels.iter_mut().zip(pixels).enumerate() { + let Some(pixel) = pixel else { continue }; + + let sample = pixel.sample; + let normal = bumped_normal(pixel.normal, height_slope(size, index, sample.height, height), radius); + let roughness = sample.roughness.max(MIN_ROUGHNESS); + let normal_dot_view = normal.z.max(0.0); + // Mirror the direction towards the viewer (+Z) about the normal + let reflected = (2.0 * normal_dot_view * normal - Vec3::Z).normalize_or_zero(); + let specular_light = reflected_light(reflected, roughness); + let diffuse_light = diffuse_light(normal); + // Schlick's Fresnel term, damped on rough surfaces below + let fresnel = (1.0 - normal_dot_view).powi(5); + + let color = [0, 1, 2].map(|component| { + let base = sample.base[component]; + let f0 = DIELECTRIC_F0 + (base - DIELECTRIC_F0) * sample.metallic; + let reflectance = f0 + ((1.0 - roughness).max(f0) - f0) * fresnel; + let linear = reflectance * specular_light + base * (1.0 - sample.metallic) * (1.0 - reflectance) * diffuse_light; + (linear_to_srgb(aces(linear * EXPOSURE)) * 255.0 + 0.5) as u8 + }); + let alpha = (pixel.coverage.clamp(0.0, 1.0) * 255.0 + 0.5) as u8; + *out = Color32::from_rgba_unmultiplied(color[0], color[1], color[2], alpha); + } + image +} + +/// How far unit direction component `y` points up: 0 straight down, 1 straight up +fn upward(y: f32) -> f32 { + y * 0.5 + 0.5 +} + +/// The backdrop's brightness `upward` of the way from the floor (0) to the ceiling (1) +fn backdrop(upward: f32) -> f32 { + FLOOR + (CEILING - FLOOR) * upward +} + +/// The studio seen along unit direction `view` by a surface of `roughness` +fn reflected_light(view: Vec3, roughness: f32) -> f32 { + // A soft horizon: reflections sweep from floor to ceiling smoothly + backdrop(smoothstep(upward(view.y))) + SOFT_BOXES.iter().map(|soft_box| soft_box.reflected(view, roughness)).sum::() +} + +/// The light reaching a diffuse surface with unit normal `normal` +fn diffuse_light(normal: Vec3) -> f32 { + backdrop(upward(normal.y)) + SOFT_BOXES.iter().map(|soft_box| soft_box.diffuse(normal)).sum::() +} + +#[cfg(test)] +mod tests { + use texturecraft_engine::preview::Sample; + + use super::*; + + #[test] + fn the_studio_lights_the_shape_from_the_upper_right() { + let polished_metal = Sample { base: [0.9; 3], metallic: 1.0, roughness: 0.3, height: 0.0 }; + let facing = |normal: Vec3| Some(MaterialPreviewPixel { sample: polished_metal, normal: normal.normalize(), coverage: 1.0 }); + // Halfway between the viewer and the key light, a mirror reflects the key + let towards_the_key = SOFT_BOXES[0].unit_direction() + Vec3::Z; + let pixels = [facing(towards_the_key), facing(Vec3::new(-0.3, -0.9, 0.3)), None, None]; + + let image = material_preview_image(2, &pixels); + let [lit, unlit, outside] = [0, 1, 2].map(|index| image.pixels[index]); + assert!(lit.r() > 200 && unlit.r() < 80, "the key light's reflection shows: {lit:?} vs {unlit:?}"); + assert_eq!((lit.a(), outside.a()), (255, 0), "opaque on the shape, transparent outside"); + } +} diff --git a/crates/ui-egui/src/orb_shape.rs b/crates/ui-egui/src/orb_shape.rs new file mode 100644 index 00000000..3d220a5c --- /dev/null +++ b/crates/ui-egui/src/orb_shape.rs @@ -0,0 +1,33 @@ +//! The preview orb of the smart mask and smart material previews, baked on first use + +use texturecraft_engine::orb_preview::OrbPreview; + +/// Whether the preview orb is baked +#[derive(Default)] +pub enum OrbShape { + #[default] + NotBaked, + /// Box the large session to keep the unbaked worker small + Baked(Box), + /// The bake failed; previews on the orb stay empty + Failed, +} + +impl OrbShape { + /// Bake on first use; retain failure to avoid retrying every frame + pub fn get(&mut self) -> Option<&mut OrbPreview> { + if matches!(self, OrbShape::NotBaked) { + *self = match OrbPreview::new() { + Ok(preview) => OrbShape::Baked(Box::new(preview)), + Err(e) => { + log::warn!("preview orb: {e}"); + OrbShape::Failed + } + }; + } + match self { + OrbShape::Baked(preview) => Some(preview), + OrbShape::NotBaked | OrbShape::Failed => None, + } + } +} diff --git a/crates/ui-egui/src/preview_image.rs b/crates/ui-egui/src/preview_image.rs index f689c85d..9b753b74 100644 --- a/crates/ui-egui/src/preview_image.rs +++ b/crates/ui-egui/src/preview_image.rs @@ -3,6 +3,7 @@ use egui::{Color32, ColorImage}; use texturecraft_engine::compose::ImageRes; use texturecraft_engine::core::ProceduralKind; +use texturecraft_engine::geom::glam::Vec3; use texturecraft_engine::paint::alphas::{self, LibraryAlpha}; use texturecraft_engine::paint::{BrushSettings, Shape}; use texturecraft_engine::preview::{self, Sample}; @@ -12,6 +13,14 @@ use texturecraft_engine::texel::linear_to_srgb; const PROCEDURAL_SCALE: f32 = 3.0; /// Samples per pixel along each axis of the alpha swatches const ALPHA_SUPERSAMPLE: usize = 2; +/// Normal tilt per height step, relative to the shape's radius in pixels +const BUMP_PER_RADIUS: f32 = 0.75; +/// Exposure of the shaded previews before tone mapping +const EXPOSURE: f32 = 1.4; +/// Gap between a preview's shape and the image edge in pixels +const SHAPE_MARGIN_PX: f32 = 1.0; +/// Guards the normal division against a zero vector +const MIN_NORMAL_LENGTH: f32 = 1e-6; /// Linear shading for view-space normal `n`, viewed along +Z pub fn shade(n: [f32; 3], base: [f32; 3], metal: f32, rough: f32) -> [f32; 3] { @@ -52,28 +61,52 @@ pub fn aces(x: f32) -> f32 { /// Shade row-major `size²` samples with height bumps and a transparent background pub fn sphere_image(size: usize, samples: &[Option]) -> ColorImage { - let mut img = ColorImage::filled([size, size], Color32::TRANSPARENT); - let r = (size as f32 * 0.5 - 1.0).max(0.5); - let h = |x: Option, y: Option| { - let (x, y) = (x.filter(|x| *x < size)?, y?); - samples.get(y.checked_mul(size)?.checked_add(x)?).copied().flatten().map(|s| s.height) - }; - for (i, n) in preview::sphere_normals(size).enumerate() { - let (Some(n), Some(Some(s))) = (n, samples.get(i)) else { continue }; + let mut image = ColorImage::filled([size, size], Color32::TRANSPARENT); + let radius = preview_radius(size); + let height = |index: usize| samples.get(index).copied().flatten().map(|sample| sample.height); - let (x, y) = (i % size, i / size); - let c = s.height; - // Image Y points down; the shading normal uses Y up - let dx = h(Some(x + 1), Some(y)).unwrap_or(c) - h(x.checked_sub(1), Some(y)).unwrap_or(c); - let dy = h(Some(x), y.checked_sub(1)).unwrap_or(c) - h(Some(x), Some(y + 1)).unwrap_or(c); - let k = r * 0.5 * 1.5; - let b = [n.x - dx * k, n.y - dy * k, n.z]; - let len = (b[0] * b[0] + b[1] * b[1] + b[2] * b[2]).sqrt().max(1e-6); - let col = shade(b.map(|v| v / len), s.base, s.metallic, s.roughness).map(|v| (linear_to_srgb(aces(v * 1.4)) * 255.0 + 0.5) as u8); - let edge = ((1.0 - (n.x * n.x + n.y * n.y).sqrt()) * r).clamp(0.0, 1.0); - img.pixels[i] = Color32::from_rgba_unmultiplied(col[0], col[1], col[2], (edge * 255.0) as u8); + for (index, normal) in preview::sphere_normals(size).enumerate() { + let (Some(normal), Some(Some(sample))) = (normal, samples.get(index)) else { continue }; + + // Anti-aliased outline: opaque from one pixel inside the rim + let coverage = ((1.0 - (normal.x * normal.x + normal.y * normal.y).sqrt()) * radius).clamp(0.0, 1.0); + image.pixels[index] = lit_pixel(normal, height_slope(size, index, sample.height, height), radius, sample, coverage); } - img + image +} + +/// Radius in pixels of the shape filling a `size²` preview +pub(crate) fn preview_radius(size: usize) -> f32 { + (size as f32 * 0.5 - SHAPE_MARGIN_PX).max(0.5) +} + +/// Height change per pixel rightwards and upwards at `pixel`; None heights count as `center` +pub(crate) fn height_slope(size: usize, pixel: usize, center: f32, height: impl Fn(usize) -> Option) -> [f32; 2] { + let (x, y) = (pixel % size, pixel / size); + let at = |x: Option, y: Option| { + let (x, y) = (x.filter(|x| *x < size)?, y?); + height(y.checked_mul(size)?.checked_add(x)?) + }; + + // Image Y points down; the shading normal uses Y up + let right = at(Some(x + 1), Some(y)).unwrap_or(center) - at(x.checked_sub(1), Some(y)).unwrap_or(center); + let up = at(Some(x), y.checked_sub(1)).unwrap_or(center) - at(Some(x), Some(y + 1)).unwrap_or(center); + [right, up] +} + +/// Tilt a view-space normal by the height `slope` on a shape of `radius` pixels +pub(crate) fn bumped_normal(normal: Vec3, slope: [f32; 2], radius: f32) -> Vec3 { + let bump = radius * BUMP_PER_RADIUS; + let bumped = [normal.x - slope[0] * bump, normal.y - slope[1] * bump, normal.z]; + let length = (bumped[0] * bumped[0] + bumped[1] * bumped[1] + bumped[2] * bumped[2]).sqrt().max(MIN_NORMAL_LENGTH); + Vec3::from(bumped.map(|component| component / length)) +} + +/// One sphere pixel of `sample`, bumped by `slope` and `coverage` opaque +fn lit_pixel(normal: Vec3, slope: [f32; 2], radius: f32, sample: &Sample, coverage: f32) -> Color32 { + let linear = shade(bumped_normal(normal, slope, radius).to_array(), sample.base, sample.metallic, sample.roughness); + let color = linear.map(|component| (linear_to_srgb(aces(component * EXPOSURE)) * 255.0 + 0.5) as u8); + Color32::from_rgba_unmultiplied(color[0], color[1], color[2], (coverage * 255.0) as u8) } /// Grayscale `size²` swatch of procedural `kind` diff --git a/crates/ui-egui/src/preview_request.rs b/crates/ui-egui/src/preview_request.rs index 71c7870b..7797a7e3 100644 --- a/crates/ui-egui/src/preview_request.rs +++ b/crates/ui-egui/src/preview_request.rs @@ -3,7 +3,8 @@ use egui::ColorImage; use crate::mask_preview_image::mask_preview_image; -use crate::mask_shape::MaskShape; +use crate::material_preview_image::material_preview_image; +use crate::orb_shape::OrbShape; use crate::shelf_preview::ShelfPreview; /// Render `preview` at `size_px²`; the answer comes back under `key` @@ -18,11 +19,12 @@ pub struct PreviewRequest { } impl PreviewRequest { - /// Render the asset, baking the mask shape on first use + /// Render the asset, baking the orb on first use for smart masks and smart materials /// Unknown assets and failed bakes return None - pub fn render(&self, shape: &mut MaskShape) -> Option { + pub fn render(&self, shape: &mut OrbShape) -> Option { match &self.preview { - ShelfPreview::SmartMask(id) => Some(mask_preview_image(self.size_px, &shape.get()?.render(id, self.size_px)?)), + ShelfPreview::SmartMask(id) => Some(mask_preview_image(self.size_px, &shape.get()?.mask(id, self.size_px)?)), + ShelfPreview::SmartMaterial(id) => Some(material_preview_image(self.size_px, &shape.get()?.material(id, self.size_px)?)), preview => preview.image(self.size_px), } } diff --git a/crates/ui-egui/src/preview_worker.rs b/crates/ui-egui/src/preview_worker.rs index a3d2cc8f..1fe89353 100644 --- a/crates/ui-egui/src/preview_worker.rs +++ b/crates/ui-egui/src/preview_worker.rs @@ -2,7 +2,7 @@ //! Web requests render synchronously on the UI thread #[cfg(target_arch = "wasm32")] -use crate::mask_shape::MaskShape; +use crate::orb_shape::OrbShape; use crate::preview_request::PreviewRequest; /// Request key and rendered image; None on failure @@ -18,7 +18,7 @@ pub enum PreviewWorker { Running { requests: std::sync::mpsc::Sender, results: std::sync::mpsc::Receiver }, /// The web: requests render as they are made #[cfg(target_arch = "wasm32")] - Inline { shape: MaskShape, results: Vec }, + Inline { shape: OrbShape, results: Vec }, /// The worker could not start or stopped; requests are refused // The web has no thread to stop #[cfg_attr(target_arch = "wasm32", allow(dead_code))] @@ -89,7 +89,7 @@ impl PreviewWorker { use std::collections::VecDeque; use std::sync::mpsc::channel; - use crate::mask_shape::MaskShape; + use crate::orb_shape::OrbShape; let (requests, request_rx) = channel::(); let (result_tx, results) = channel(); @@ -101,7 +101,7 @@ impl PreviewWorker { if let Err(e) = &pool { log::warn!("shelf previews share the global thread pool: {e}"); } - let mut shape = MaskShape::default(); + let mut shape = OrbShape::default(); let mut queue = VecDeque::new(); loop { if queue.is_empty() { @@ -136,7 +136,7 @@ impl PreviewWorker { /// Render inline (no threads on the web) #[cfg(target_arch = "wasm32")] fn start(_ctx: &egui::Context) -> PreviewWorker { - PreviewWorker::Inline { shape: MaskShape::default(), results: Vec::new() } + PreviewWorker::Inline { shape: OrbShape::default(), results: Vec::new() } } } @@ -170,23 +170,26 @@ mod tests { ("unknown material", ShelfPreview::Material("nope")), ("mask", ShelfPreview::SmartMask(SMART_MASKS[0].id)), ("unknown mask", ShelfPreview::SmartMask("nope")), + ("smart material", ShelfPreview::SmartMaterial("steel_painted_worn")), + ("unknown smart material", ShelfPreview::SmartMaterial("nope")), ]; + let requests_sent = requests.len(); for (key, preview) in requests { assert!(worker.request(&ctx, PreviewRequest { key: key.into(), preview, size_px, hover: false }), "{key}"); } let mut answers = HashMap::new(); let start = Instant::now(); - while answers.len() < 4 && start.elapsed() < Duration::from_secs(120) { + while answers.len() < requests_sent && start.elapsed() < Duration::from_secs(120) { answers.extend(worker.poll()); std::thread::sleep(Duration::from_millis(10)); } - for key in ["material", "mask"] { + for key in ["material", "mask", "smart material"] { let image = answers.get(key).and_then(Option::as_ref).unwrap_or_else(|| panic!("{key}: {answers:?}")); assert_eq!(image.size, [size_px, size_px], "{key}"); } - for key in ["unknown material", "unknown mask"] { + for key in ["unknown material", "unknown mask", "unknown smart material"] { assert!(matches!(answers.get(key), Some(None)), "{key}: {answers:?}"); } assert!(!worker.is_stopped()); diff --git a/crates/ui-egui/src/shelf.rs b/crates/ui-egui/src/shelf.rs index 46ced908..5d876249 100644 --- a/crates/ui-egui/src/shelf.rs +++ b/crates/ui-egui/src/shelf.rs @@ -12,8 +12,8 @@ use texturecraft_engine::filter_lib::FILTERS; #[cfg(not(target_arch = "wasm32"))] use texturecraft_engine::formats::mcmat::MCMAT_EXT; use texturecraft_engine::geom::glam::Vec2; -use texturecraft_engine::mask_preview::MAX_PREVIEW_SIZE_PX; use texturecraft_engine::materials::MATERIALS; +use texturecraft_engine::orb_preview::MAX_PREVIEW_SIZE_PX; use texturecraft_engine::paint::alphas; use texturecraft_engine::paint::presets::{BrushPreset, PRESETS}; use texturecraft_engine::smart_masks::SMART_MASKS; @@ -34,8 +34,9 @@ const TILE_ROUNDING: f32 = 3.0; /// The thumbnail's size in a tile and its center below the tile's top, in points const THUMBNAIL_SIZE: f32 = 56.0; const THUMBNAIL_CENTER_Y: f32 = 32.0; -/// A placeholder disc's radius relative to the thumbnail's width -const PLACEHOLDER_RADIUS: f32 = 0.45; +/// Loading icon size relative to the thumbnail width, and its opacity over the dim text color +const LOADING_ICON_SCALE: f32 = 0.9; +const LOADING_ICON_OPACITY: f32 = 0.5; /// A tile label's font size, its gap below the thumbnail and its total side margin, in points const LABEL_FONT_SIZE: f32 = 9.5; const LABEL_GAP: f32 = 3.0; @@ -300,20 +301,22 @@ fn categories(items: &[T], category: impl Fn(&T) -> &'static str) -> Vec<&'st out } -/// Built-in materials (or smart materials), grouped by category. +/// Built-in materials or smart materials, grouped by category fn materials(app: &mut TextureCraftApp, ui: &mut Ui, ctx: &egui::Context, filter: &str, smart: bool, name: &str) { - let shown: Vec<_> = MATERIALS.iter().filter(|m| m.smart == smart && matches(filter, &[m.label, m.category, m.id])).collect(); + let shown: Vec<_> = + MATERIALS.iter().filter(|material| material.smart == smart && matches(filter, &[material.label, material.category, material.id])).collect(); if shown.is_empty() { return; } + title(ui, name); - for cat in categories(&shown, |m| m.category) { - header(ui, cat); + for category in categories(&shown, |material| material.category) { + header(ui, category); tiles(ui, |ui| { - for m in shown.iter().filter(|m| m.category == cat) { - let tex = app.thumbs.material(ctx, m.id); - let asset = Asset::Material(m.id); - if tile(ui, &mut app.thumbs, tex.as_ref(), || ShelfPreview::Material(m.id), m.label, Some(&asset)).clicked() { + for material in shown.iter().filter(|material| material.category == category) { + let texture = app.thumbs.material(ctx, material.id); + let asset = Asset::Material(material.id); + if tile(ui, &mut app.thumbs, texture.as_ref(), || ShelfPreview::material(material.id), material.label, Some(&asset)).clicked() { apply(app, &asset); } } @@ -623,8 +626,9 @@ fn big_preview(ui: &Ui, thumbs: &mut Thumbs, preview: impl FnOnce() -> ShelfPrev let preview = preview(); let requested_size_px = (BIG_PREVIEW_SIZE * ctx.pixels_per_point()).round() as usize; - // High display scales must respect the mask camera's allocation limit - let size_px = if matches!(&preview, ShelfPreview::SmartMask(_)) { requested_size_px.clamp(1, MAX_PREVIEW_SIZE_PX) } else { requested_size_px }; + // High display scales must respect the orb camera's allocation limit + let on_the_orb = matches!(&preview, ShelfPreview::SmartMask(_) | ShelfPreview::SmartMaterial(_)); + let size_px = if on_the_orb { requested_size_px.clamp(1, MAX_PREVIEW_SIZE_PX) } else { requested_size_px }; // Scrolling moves tiles beneath a stationary pointer let idle_seconds = ui.input(|input| if input.is_scrolling() { 0.0 } else { input.pointer.time_since_last_movement().min(input.time_since_last_scroll()) }); @@ -636,14 +640,21 @@ fn big_preview(ui: &Ui, thumbs: &mut Thumbs, preview: impl FnOnce() -> ShelfPrev thumbs.rendered_big(ctx, &preview, size_px) } -/// `tex` drawn into `rect`, or a placeholder disc while it renders -fn thumbnail(painter: &egui::Painter, tex: Option<&egui::TextureHandle>, rect: egui::Rect, tk: &Tokens) { - match tex { - Some(t) => { - painter.image(t.id(), rect, egui::Rect::from_min_max(egui::pos2(0.0, 0.0), egui::pos2(1.0, 1.0)), Color32::WHITE); +/// `texture` drawn into `rect`, or a dim loading icon while it renders +fn thumbnail(painter: &egui::Painter, texture: Option<&egui::TextureHandle>, rect: egui::Rect, tk: &Tokens) { + match texture { + Some(texture) => { + painter.image(texture.id(), rect, egui::Rect::from_min_max(egui::pos2(0.0, 0.0), egui::pos2(1.0, 1.0)), Color32::WHITE); } None => { - painter.circle_filled(rect.center(), rect.width() * PLACEHOLDER_RADIUS, tk.row_hover); + let font = egui::FontId::proportional(rect.width() * LOADING_ICON_SCALE); + painter.text( + rect.center(), + egui::Align2::CENTER_CENTER, + egui_phosphor::regular::ARROWS_CLOCKWISE, + font, + tk.text_dim.gamma_multiply(LOADING_ICON_OPACITY), + ); } } } diff --git a/crates/ui-egui/src/shelf_preview.rs b/crates/ui-egui/src/shelf_preview.rs index a23ffb32..b512f250 100644 --- a/crates/ui-egui/src/shelf_preview.rs +++ b/crates/ui-egui/src/shelf_preview.rs @@ -5,6 +5,7 @@ use std::sync::Arc; use egui::ColorImage; use texturecraft_engine::compose::ImageRes; use texturecraft_engine::core::ProceduralKind; +use texturecraft_engine::materials; use texturecraft_engine::paint::BrushSettings; use texturecraft_engine::paint::alphas::LibraryAlpha; use texturecraft_engine::paint::presets::BrushPreset; @@ -14,9 +15,11 @@ use crate::preview_image::{alpha_image, image_preview, procedural_image, sphere_ /// The asset a shelf tile previews pub enum ShelfPreview { - /// A built-in material or smart material on a sphere + /// A built-in plain material on a sphere Material(&'static str), - /// Smart mask rendering requires the worker's baked shape + /// Smart material rendering requires the worker's baked orb + SmartMaterial(&'static str), + /// Smart mask rendering requires the worker's baked orb SmartMask(&'static str), /// A library filter on a sample material on a sphere Filter(&'static str), @@ -31,10 +34,19 @@ pub enum ShelfPreview { } impl ShelfPreview { + /// Smart materials preview on the orb, plain materials on a sphere + pub fn material(id: &'static str) -> ShelfPreview { + match materials::find(id) { + Some(found) if found.smart => ShelfPreview::SmartMaterial(id), + Some(_) | None => ShelfPreview::Material(id), + } + } + /// The cache key of the preview (one per asset) pub fn key(&self) -> String { match self { ShelfPreview::Material(id) => format!("mat:{id}"), + ShelfPreview::SmartMaterial(id) => format!("smart-mat:{id}"), ShelfPreview::SmartMask(id) => format!("mask:{id}"), ShelfPreview::Filter(id) => format!("filter:{id}"), ShelfPreview::Procedural(kind) => format!("proc:{kind:?}"), @@ -45,11 +57,11 @@ impl ShelfPreview { } /// Render a `size²` image; unknown assets return None - /// Smart masks return None here because their bake belongs to the worker + /// Smart masks and smart materials return None here because their bake belongs to the worker pub fn image(&self, size: usize) -> Option { match self { ShelfPreview::Material(id) => Some(sphere_image(size, &preview::material(id, size)?)), - ShelfPreview::SmartMask(_) => None, + ShelfPreview::SmartMask(_) | ShelfPreview::SmartMaterial(_) => None, ShelfPreview::Filter(id) => Some(sphere_image(size, &preview::filter(id, size)?)), ShelfPreview::Procedural(kind) => Some(procedural_image(*kind, size)), ShelfPreview::Alpha(alpha) => Some(alpha_image(alpha, size)), @@ -86,14 +98,23 @@ mod tests { let key = preview.key(); let image = preview.image(BIG_PX).unwrap_or_else(|| panic!("{key}")); assert_eq!(image.size, [BIG_PX, BIG_PX], "{key}"); - assert!(image.pixels.iter().any(|c| c.a() > 0 && c.r().max(c.g()).max(c.b()) > 0), "{key}: something shows"); + assert!(image.pixels.iter().any(|color| color.a() > 0 && color.r().max(color.g()).max(color.b()) > 0), "{key}: something shows"); } let finite = |samples: Vec>| { - samples.iter().flatten().all(|s| s.base.iter().chain([&s.metallic, &s.roughness, &s.height]).all(|v| v.is_finite())) + samples.iter().flatten().all(|sample| sample.base.into_iter().chain([sample.metallic, sample.roughness, sample.height]).all(f32::is_finite)) }; assert!(finite(preview::material(MATERIALS[0].id, BIG_PX).unwrap_or_default())); assert!(finite(preview::filter(FILTERS[0].id, BIG_PX).unwrap_or_default())); - assert!(ShelfPreview::SmartMask("edges_sharp").image(BIG_PX).is_none(), "smart masks need the baked shape"); + assert!(ShelfPreview::SmartMask("edges_sharp").image(BIG_PX).is_none(), "smart masks need the baked orb"); + assert!(ShelfPreview::SmartMaterial("steel_painted_worn").image(BIG_PX).is_none(), "smart materials need the baked orb"); + } + + #[test] + fn smart_materials_and_only_they_preview_on_the_orb() { + for material in MATERIALS { + let on_the_orb = matches!(ShelfPreview::material(material.id), ShelfPreview::SmartMaterial(_)); + assert_eq!(on_the_orb, material.smart, "{}", material.id); + } } } diff --git a/crates/ui-egui/src/soft_box.rs b/crates/ui-egui/src/soft_box.rs new file mode 100644 index 00000000..9c2c8391 --- /dev/null +++ b/crates/ui-egui/src/soft_box.rs @@ -0,0 +1,48 @@ +//! A soft box of the smart material preview studio (see [`crate::material_preview_image`]) + +use texturecraft_engine::geom::glam::Vec3; + +/// How much roughness widens a soft box's reflection, in radians per unit of roughness +const BLUR_RAD_PER_ROUGHNESS: f32 = 1.1; +/// A reflected disc's soft edge: this share of its reflected radius plus a minimum in radians +const EDGE_SOFTNESS: f32 = 0.25; +const EDGE_SOFTNESS_MIN_RAD: f32 = 0.02; +/// The share of a soft box's light that reaches a diffuse surface facing it +const DIFFUSE_SHARE: f32 = 0.9; + +/// A round area light far away, seen as a disc in reflections +pub struct SoftBox { + /// Direction towards the light in view space (+X right, +Y up, +Z towards the viewer), not normalized + pub direction: [f32; 3], + /// Angular radius of the disc in radians + pub radius_rad: f32, + /// Brightness of the disc (linear) + pub intensity: f32, +} + +impl SoftBox { + /// The unit direction towards the light + pub fn unit_direction(&self) -> Vec3 { + Vec3::from(self.direction).normalize_or_zero() + } + + /// The light seen along unit direction `view` by a surface of `roughness`: rougher surfaces see the disc wider and dimmer (the same light spread out) + pub fn reflected(&self, view: Vec3, roughness: f32) -> f32 { + let reflected_radius_rad = self.radius_rad.hypot(roughness * BLUR_RAD_PER_ROUGHNESS); + let angle_rad = view.dot(self.unit_direction()).clamp(-1.0, 1.0).acos(); + let edge_width_rad = EDGE_SOFTNESS * reflected_radius_rad + EDGE_SOFTNESS_MIN_RAD; + let inside = smoothstep((reflected_radius_rad - angle_rad) / edge_width_rad); + self.intensity * (self.radius_rad / reflected_radius_rad).powi(2) * inside + } + + /// The light reaching a diffuse surface with unit normal `normal` + pub fn diffuse(&self, normal: Vec3) -> f32 { + self.intensity * self.radius_rad * self.radius_rad * DIFFUSE_SHARE * normal.dot(self.unit_direction()).max(0.0) + } +} + +/// Smooth 0..=1 ramp of `t` (clamped), flat at both ends +pub fn smoothstep(t: f32) -> f32 { + let t = t.clamp(0.0, 1.0); + t * t * (3.0 - 2.0 * t) +} diff --git a/crates/ui-egui/src/thumbs.rs b/crates/ui-egui/src/thumbs.rs index 9ed4f73b..d0067411 100644 --- a/crates/ui-egui/src/thumbs.rs +++ b/crates/ui-egui/src/thumbs.rs @@ -1,6 +1,6 @@ //! Shelf and brush preview caches //! Small synchronous renders are limited per frame -//! Smart masks and hover previews use [`PreviewWorker`] +//! Smart masks, smart materials and hover previews use [`PreviewWorker`] use std::collections::{HashMap, VecDeque}; @@ -16,7 +16,7 @@ use crate::preview_worker::PreviewWorker; use crate::shelf_preview::ShelfPreview; use crate::worker_preview::WorkerPreview; -/// Shelf thumbnails rendered per frame at most (the rest follow on the next frames) +/// UI-thread renders per frame at most; a web worker request uses the whole budget const PER_FRAME: usize = 2; /// Shelf sphere and smart mask thumbnail size in pixels const SPHERE_PX: usize = 72; @@ -37,7 +37,7 @@ pub struct Thumbs { images: HashMap, /// (frame, thumbnails rendered in it) budget: (u64, usize), - /// Renders the smart mask thumbnails and the big previews + /// Renders the orb thumbnails and the big previews worker: PreviewWorker, /// Worker-rendered previews by [`worker_key`] rendered: HashMap, @@ -82,25 +82,34 @@ impl Thumbs { /// Render within the frame budget; deferred thumbnails request a repaint fn shelf(&mut self, ctx: &egui::Context, preview: ShelfPreview, size_px: usize) -> Option { let key = preview.key(); - if let Some(t) = self.shelf.get(&key) { - return Some(t.clone()); + if let Some(texture) = self.shelf.get(&key) { + return Some(texture.clone()); } + if !self.spend_budget(ctx, 1) { + return None; + } + + // An unknown asset shows as an empty thumbnail + let image = preview.image(size_px).unwrap_or_else(|| ColorImage::filled([size_px, size_px], Color32::TRANSPARENT)); + let texture = ctx.load_texture(format!("thumb_{key}"), image, TextureOptions::LINEAR); + self.shelf.insert(key, texture.clone()); + Some(texture) + } + + /// Spend `renders` of this frame's UI-thread budget; when it is spent, request a repaint + fn spend_budget(&mut self, ctx: &egui::Context, renders: usize) -> bool { let frame = ctx.cumulative_pass_nr(); if self.budget.0 != frame { self.budget = (frame, 0); } - if self.budget.1 >= PER_FRAME { + if self.budget.1 + renders > PER_FRAME { ctx.request_repaint(); - return None; + return false; } - self.budget.1 += 1; - // An unknown asset shows as an empty thumbnail - let image = preview.image(size_px).unwrap_or_else(|| ColorImage::filled([size_px, size_px], Color32::TRANSPARENT)); - let t = ctx.load_texture(format!("thumb_{key}"), image, TextureOptions::LINEAR); - self.shelf.insert(key, t.clone()); - Some(t) + self.budget.1 += renders; + true } /// Request once per asset and size; return None while pending or after failure @@ -109,13 +118,19 @@ impl Thumbs { self.receive(ctx); let key = worker_key(&preview, size_px); - if !self.rendered.contains_key(&key) { + if !self.rendered.contains_key(&key) && self.may_request(ctx) { let queued = self.worker.request(ctx, PreviewRequest { key: key.clone(), preview, size_px, hover }); self.rendered.insert(key.clone(), if queued { WorkerPreview::Rendering } else { WorkerPreview::Failed }); } + self.ready(&key) } + /// Native workers take every request; the web renders inline, so it takes one per frame + fn may_request(&mut self, ctx: &egui::Context) -> bool { + !cfg!(target_arch = "wasm32") || self.spend_budget(ctx, PER_FRAME) + } + /// The worker-rendered preview under `key` if it arrived fn ready(&self, key: &str) -> Option { match self.rendered.get(key) { @@ -169,9 +184,12 @@ impl Thumbs { self.ready(&worker_key(preview, size_px)) } - /// Sphere thumbnail of built-in material `id` + /// Material thumbnail: smart materials come from the worker's orb, plain ones are spheres pub fn material(&mut self, ctx: &egui::Context, id: &'static str) -> Option { - self.shelf(ctx, ShelfPreview::Material(id), SPHERE_PX) + match ShelfPreview::material(id) { + preview @ ShelfPreview::SmartMaterial(_) => self.worker_rendered(ctx, preview, SPHERE_PX, false), + preview => self.shelf(ctx, preview, SPHERE_PX), + } } /// Smart mask thumbnail; None until the worker returns it diff --git a/crates/ui-egui/src/worker_preview.rs b/crates/ui-egui/src/worker_preview.rs index 53767276..27c3525b 100644 --- a/crates/ui-egui/src/worker_preview.rs +++ b/crates/ui-egui/src/worker_preview.rs @@ -7,6 +7,6 @@ pub enum WorkerPreview { /// Requested; the worker has not answered yet Rendering, Ready(TextureHandle), - /// The asset is unknown or the worker could not render it (the tile keeps its placeholder) + /// The asset is unknown or the worker could not render it (the tile keeps its loading icon) Failed, } diff --git a/crates/ui-egui/tests/shelf_hover_preview.rs b/crates/ui-egui/tests/shelf_hover_preview.rs index 460ed7c8..2ad76a68 100644 --- a/crates/ui-egui/tests/shelf_hover_preview.rs +++ b/crates/ui-egui/tests/shelf_hover_preview.rs @@ -145,7 +145,7 @@ fn scrolling_with_a_stationary_pointer_defers_the_big_preview() { #[test] fn high_dpi_smart_mask_hover_stays_within_the_renderer_limit() { - use texturecraft_engine::mask_preview::MAX_PREVIEW_SIZE_PX; + use texturecraft_engine::orb_preview::MAX_PREVIEW_SIZE_PX; use texturecraft_engine::smart_masks::SMART_MASKS; let (mut harness, _) = materials_shelf(1.0 / 4.0, 3.0);