diff --git a/ATTRIBUTION.md b/ATTRIBUTION.md index 500328aa..bdd983f6 100644 --- a/ATTRIBUTION.md +++ b/ATTRIBUTION.md @@ -23,6 +23,7 @@ licensed and keep their license file next to them. | `docs/images/texturecraft-light.png` | README screenshot: the light brightness level with the blue accent | TextureCraft contributors | original screenshot of TextureCraft | MIT OR Apache-2.0 | | `docs/images/texturecraft-lantern.png` | README render: a storm lantern (original procedural mesh of lathes and swept wires, eight texture sets) in chipped red enamel, rust, soot, tarnished brass and glass with an emissive flame (`texturecraft-cli render --camera Hero --samples 2048`, 1200×900) | TextureCraft contributors | original model and render by TextureCraft | MIT OR Apache-2.0 | | `docs/images/texturecraft-camera.png` | README render: a rangefinder camera (original procedural mesh) in black enamel worn to brass, leatherette, chrome and coated glass; the lens distance scale is an original image drawn in code (`texturecraft-cli render --camera Hero --samples 2048`, 1200×900) | TextureCraft contributors | original model and render by TextureCraft | MIT OR Apache-2.0 | +| `assets/environments/studio_small_09_512.hdr` | Studio Small 09: a small photo studio with octaboxes on a white infinity cyc, equirect HDR reduced to 512×256 (2×2 box filter, Radiance RLE); lights the Properties panel's material orbs | Sergej Majboroda (Poly Haven) | https://polyhaven.com/a/studio_small_09 (1K .hdr) | CC0-1.0 | | `docs/brand/artcraft-*.svg`, `docs/brand/artcraft-*.png` | ArtCraft logo and mark | ArtCraft Team | storytold/craftrules `assets/brand/` | ArtCraft brand terms, not open source ([`docs/brand/LICENSE-brand.txt`](docs/brand/LICENSE-brand.txt)) | | `crates/formats/src/mesh_import/usd/fixtures/crafted-references.usdc` | Synthetic USDC class/reference/time-sample acceptance fixture | ArtCraft Team and craft-libs contributors | [Pinned generator and provenance](crates/formats/src/mesh_import/usd/fixtures/README.md) | MIT (`crates/formats/src/mesh_import/usd/fixtures/LICENSE-MIT`) | diff --git a/assets/hdr/studio_small_09_512.hdr b/assets/hdr/studio_small_09_512.hdr new file mode 100644 index 00000000..3a3f4f35 Binary files /dev/null and b/assets/hdr/studio_small_09_512.hdr differ diff --git a/crates/ui-egui/src/material_orb.rs b/crates/ui-egui/src/material_orb.rs new file mode 100644 index 00000000..704959cc --- /dev/null +++ b/crates/ui-egui/src/material_orb.rs @@ -0,0 +1,356 @@ +//! The material orbs of the Properties panel: a sphere showing the whole material (every channel, height and normal relief +//! included) lit by a photographed studio, or one channel unlit as the viewport's channel view shows it, rendered at its +//! on-screen size in physical pixels, off the UI thread, cached by look + +use egui::{Color32, ColorImage, Painter, Rect, pos2}; +use rayon::prelude::*; +use texturecraft_engine::geom::glam::Vec3; +use texturecraft_engine::texel::linear_to_srgb; + +use crate::orb_environment::OrbEnvironment; +use crate::orb_material::{OrbMaterial, OrbSample, orb_coords}; +use crate::orb_previews::{OrbJob, OrbPreviews}; +use crate::preview_image::aces; +use crate::theme::Tokens; + + +/// Largest orb rendered, in physical pixels +const MAX_SIDE_PX: usize = 512; + +/// The sphere's radius in halves of the square +const SPHERE_RADIUS: f32 = 0.84; + +/// The lowest roughness shaded (a perfect mirror aliases at orb sizes) +const MIN_ROUGHNESS: f32 = 0.03; + +/// How deep the height channel's full range carves the surface, in orb radii +const HEIGHT_DEPTH: f32 = 0.05; + +/// Exposure before tone mapping +const EXPOSURE: f32 = 0.55; + +/// The least facing a normal turned past the outline keeps, so the reflection and the BRDF fit never see a grazing zero +const MIN_NORMAL_DOT_VIEW: f32 = 1e-4; + +/// Draws `material`'s orb into `rect` on the panel's darkest backdrop; each `place` keeps its last picture while a new one renders +pub(crate) fn material_orb(painter: &Painter, rect: Rect, material: &OrbMaterial, tokens: &Tokens, place: impl std::hash::Hash + std::fmt::Debug) { + let ctx = painter.ctx(); + let side = ((rect.width() * ctx.pixels_per_point()).round() as usize).clamp(1, MAX_SIDE_PX); + let key = OrbJob::key_of(material, side, tokens.chrome); + let job = || OrbJob::new(material.clone(), side, tokens.chrome); + if let Some(texture) = OrbPreviews::texture(ctx, egui::Id::unique(("material_orb", place)), key, job) { + painter.image(texture.id(), rect, Rect::from_min_max(pos2(0.0, 0.0), pos2(1.0, 1.0)), Color32::WHITE); + } +} + +/// The orb `side` pixels square, on `backdrop` +pub(crate) fn render(material: &OrbMaterial, side: usize, backdrop: Color32) -> ColorImage { + let side = side.clamp(1, MAX_SIDE_PX); + let env = OrbEnvironment::get(); + let back = [backdrop.r(), backdrop.g(), backdrop.b()].map(|component| f32::from(component) / 255.0); + + // One pixel in orb radii: the step for the height slope and the reach of the anti-aliased outline + let pixel = 2.0 / (side as f32 * SPHERE_RADIUS); + let uniform = (!material.varies()).then(|| material.sample(&orb_coords(Vec3::Y), 1.0)); + let mut pixels = vec![Color32::TRANSPARENT; side * side]; + pixels.par_chunks_mut(side).enumerate().for_each(|(y, row)| { + for (x, out) in row.iter_mut().enumerate() { + let u = ((x as f32 + 0.5) / side as f32 * 2.0 - 1.0) / SPHERE_RADIUS; + let v = (1.0 - (y as f32 + 0.5) / side as f32 * 2.0) / SPHERE_RADIUS; + let distance = (u * u + v * v).sqrt(); + let coverage = ((1.0 - distance) / pixel + 0.5).clamp(0.0, 1.0); + if coverage <= 0.0 { + *out = backdrop; + continue; + } + + // Pixels on the outline shade the sphere's rim + let (u, v) = if distance > 1.0 { (u / distance, v / distance) } else { (u, v) }; + let normal = Vec3::new(u, v, (1.0 - u * u - v * v).max(0.0).sqrt()); + let (shown, alpha) = match material.alone() { + Some(channel) => { + let footprint = pixel * std::f32::consts::FRAC_1_PI; + (channel_view(channel, material.value(channel, &orb_coords(normal), footprint)), coverage) + } + None => { + let (linear, opacity) = shade(material, env, normal, pixel, uniform); + (linear.map(|component| linear_to_srgb(aces(component * EXPOSURE))), coverage * opacity) + } + }; + let [r, g, b] = [0, 1, 2].map(|channel| ((back[channel] + (shown[channel] - back[channel]) * alpha) * 255.0).round().clamp(0.0, 255.0) as u8); + *out = Color32::from_rgb(r, g, b); + } + }); + ColorImage::new([side, side], pixels) +} + +/// The linear light leaving the orb at view-space unit `direction` from its centre, and the material's opacity there +fn shade(material: &OrbMaterial, env: &OrbEnvironment, direction: Vec3, pixel: f32, uniform: Option) -> ([f32; 3], f32) { + // Facing the viewer, the orb's poles sit on its outline, where their UV pinch does not show + let coords = orb_coords(direction); + let footprint = pixel * std::f32::consts::FRAC_1_PI; + let sample = uniform.unwrap_or_else(|| material.sample(&coords, footprint)); + + // Tangent frame on the material: east along the UVs, then north + let east = Vec3::new(-direction.z, 0.0, direction.x).try_normalize().unwrap_or(Vec3::X); + let north = direction.cross(east).try_normalize().unwrap_or(Vec3::Y); + let mapped = Vec3::from(sample.normal.map(|component| component * 2.0 - 1.0)); + let mut surface = (east * mapped.x + north * mapped.y + direction * mapped.z).try_normalize().unwrap_or(direction); + if material.has_relief() { + let height = material.height(&coords, footprint); + let slope = |toward: Vec3| (material.height(&orb_coords((direction + toward * pixel).normalize()), footprint) - height) / pixel; + surface = (surface - (east * slope(east) + north * slope(north)) * HEIGHT_DEPTH).try_normalize().unwrap_or(surface); + } + + let normal = surface; + let roughness = sample.roughness.clamp(MIN_ROUGHNESS, 1.0); + let metallic = sample.metallic.clamp(0.0, 1.0); + let normal_dot_view = normal.z.max(MIN_NORMAL_DOT_VIEW); + + // 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 = env.reflected(reflected, roughness); + let diffuse_light = env.diffuse(normal); + let (scale, bias) = environment_brdf(roughness, normal_dot_view); + let mut out = [0.0; 3]; + for (channel, value) in out.iter_mut().enumerate() { + let base = sample.base[channel].clamp(0.0, 1.0); + let f0 = DIELECTRIC_REFLECTANCE + (base - DIELECTRIC_REFLECTANCE) * metallic; + let specular = f0 * scale + bias; + *value = diffuse_light[channel] * base * (1.0 - metallic) * (1.0 - specular) + specular_light[channel] * specular + sample.emissive[channel].max(0.0); + } + (out, sample.opacity.clamp(0.0, 1.0)) +} + +/// `channel`'s `value` on screen (0..1) as the viewport's channel view shows it: colours sRGB-encoded, height around mid gray +fn channel_view(channel: Channel, value: [f32; 3]) -> [f32; 3] { + let value = value.map(|c| if c.is_finite() { c } else { 0.0 }); + let shown = match channel { + Channel::BaseColor | Channel::Emissive | Channel::Specular | Channel::SheenColor => value.map(|c| linear_to_srgb(c.clamp(0.0, 1.0))), + // The viewport encodes these as it does colours (they share its colour output) + Channel::Metallic | Channel::Roughness | Channel::Glossiness => [linear_to_srgb(value[0].clamp(0.0, 1.0)); 3], + Channel::Normal | Channel::CoatNormal => value, + Channel::Height => [value[0] * 0.5 + 0.5; 3], + _ => [value[0]; 3], + }; + shown.map(|c| c.clamp(0.0, 1.0)) +} + +/// The split-sum environment BRDF as scale and bias on F0, from Karis' analytic fit for mobile (no lookup table) +fn environment_brdf(roughness: f32, normal_dot_view: f32) -> (f32, f32) { + let [gloss, gloss_offset, scale_base, bias_base] = [1.0 - roughness, roughness * -0.0275 + 0.0425, roughness * -0.572 + 1.04, roughness * 0.022 - 0.04]; + let shared = (gloss * gloss).min((-9.28 * normal_dot_view).exp2()) * gloss + gloss_offset; + (shared * -1.04 + scale_base, shared * 1.04 + bias_base) +} + +#[cfg(test)] +mod tests { + use texturecraft_engine::core::{Channel, Fill, Procedural, ProceduralKind, Source}; + + use super::*; + + const BACKDROP: Color32 = Color32::from_rgb(27, 31, 39); + + fn copper() -> OrbMaterial { + OrbMaterial::uniform([0.8, 0.35, 0.18], 1.0, 0.35) + } + + fn at(image: &ColorImage, x: usize, y: usize) -> Color32 { + image.pixels.get(y * image.size[0] + x).copied().unwrap_or_default() + } + + /// Mean of how far each pixel's channels spread apart (0 = gray) + fn saturation(image: &ColorImage) -> f32 { + let spread = |pixel: &Color32| f32::from(pixel.r().max(pixel.g()).max(pixel.b()) - pixel.r().min(pixel.g()).min(pixel.b())); + let shown: Vec = image.pixels.iter().filter(|pixel| **pixel != BACKDROP).map(spread).collect(); + shown.iter().sum::() / shown.len().max(1) as f32 + } + + #[test] + fn the_orb_sits_on_its_backdrop_and_shows_its_colour() { + let image = render(&copper(), 64, BACKDROP); + assert_eq!(image.pixels[0], BACKDROP, "the corner is off the sphere"); + let middle = at(&image, 32, 32); + assert!(middle.r() > middle.b(), "copper is warm: {middle:?}"); + } + + #[test] + fn rougher_materials_spread_their_highlight() { + let peak = |roughness: f32| { + let image = render(&OrbMaterial::uniform([0.8, 0.35, 0.18], 1.0, roughness), 64, Color32::BLACK); + image.pixels.iter().map(|pixel| pixel.r()).max().unwrap_or(0) + }; + assert!(peak(0.1) > peak(0.9), "a polished orb has a brighter hot spot"); + } + + #[test] + fn a_metal_reflects_the_studio_in_its_own_colour() { + // The studio's soft boxes and dark walls show as bright and dark bands across a polished metal, tinted by its colour + let image = render(&OrbMaterial::uniform([0.95, 0.64, 0.54], 1.0, 0.15), 96, BACKDROP); + let lightness: Vec = image.pixels.iter().filter(|pixel| **pixel != BACKDROP).map(|pixel| pixel.r()).collect(); + let (darkest, brightest) = (lightness.iter().min().copied().unwrap_or(0), lightness.iter().max().copied().unwrap_or(0)); + assert!(brightest - darkest > 120, "reflections show light and dark: {darkest}..{brightest}"); + assert!(saturation(&image) > 25.0, "copper stays coloured, not gray: {}", saturation(&image)); + } + + fn fill_with(channel: Channel, source: Source) -> Fill { + let mut fill = Fill::default(); + fill.sources.insert(channel, source); + fill + } + + #[test] + fn a_colour_procedurals_gradient_map_colours_the_orb() { + let source = |ramp: Vec<[f32; 3]>| Source::Procedural { pattern: Procedural::new(ProceduralKind::Cells), low: [0.0; 3], high: [1.0; 3], ramp }; + let on = [Channel::BaseColor]; + let gray = render(&OrbMaterial::of_fill(&fill_with(Channel::BaseColor, source(Vec::new())), &on, &Default::default()), 64, BACKDROP); + let red = render(&OrbMaterial::of_fill(&fill_with(Channel::BaseColor, source(vec![[1.0, 0.0, 0.0]; 2])), &on, &Default::default()), 64, BACKDROP); + let reddened = + red.pixels.iter().zip(&gray.pixels).filter(|(r, g)| i32::from(r.r()) - i32::from(r.g()) > i32::from(g.r()) - i32::from(g.g()) + 16).count(); + assert!(reddened > 64 * 64 / 4, "the ramp's red shows on the orb: {reddened} pixels"); + } + + #[test] + fn every_channel_shows_on_the_orb_relief_included() { + let flat = render(&OrbMaterial::of_fill(&Fill::default(), &[Channel::BaseColor, Channel::Height, Channel::Normal], &Default::default()), 64, BACKDROP); + let pattern = Procedural::new(ProceduralKind::Cells); + for channel in [Channel::BaseColor, Channel::Roughness, Channel::Height, Channel::Normal] { + let (low, high) = match channel { + Channel::Normal => ([0.2, 0.5, 0.9], [0.8, 0.5, 0.9]), + Channel::Height => ([-1.0; 3], [1.0; 3]), + _ => ([0.0; 3], [1.0; 3]), + }; + let fill = fill_with(channel, Source::Procedural { pattern: pattern.clone(), low, high, ramp: Vec::new() }); + let on = [Channel::BaseColor, Channel::Roughness, Channel::Height, Channel::Normal]; + let shown = render(&OrbMaterial::of_fill(&fill, &on, &Default::default()), 64, BACKDROP); + let changed = shown.pixels.iter().zip(&flat.pixels).filter(|(a, b)| a != b).count(); + assert!(changed > 64 * 64 / 4, "{channel:?} changes the orb: {changed} pixels"); + let off = render(&OrbMaterial::of_fill(&fill, &[], &Default::default()), 64, BACKDROP); + let flat_off = render(&OrbMaterial::of_fill(&Fill::default(), &[], &Default::default()), 64, BACKDROP); + assert_eq!(off.pixels, flat_off.pixels, "{channel:?} switched off shows its default"); + } + } + + #[test] + fn an_image_source_shows_on_the_orb() { + use std::sync::Arc; + use texturecraft_engine::compose::ImageRes; + + // Left half black, right half white + let rgba = (0..64 * 64).map(|i| if i % 64 < 32 { [0.0, 0.0, 0.0, 1.0] } else { [1.0; 4] }).collect(); + let images = std::collections::HashMap::from([("stripes".to_owned(), Arc::new(ImageRes::new(64, 64, rgba, false)))]); + let fill = fill_with(Channel::BaseColor, Source::Image { name: "stripes".into(), normal_format: Default::default() }); + let image = render(&OrbMaterial::of_fill(&fill, &[Channel::BaseColor], &images), 64, BACKDROP); + let lightness: Vec = image.pixels.iter().filter(|pixel| **pixel != BACKDROP).map(|pixel| pixel.g()).collect(); + let (darkest, brightest) = (lightness.iter().min().copied().unwrap_or(0), lightness.iter().max().copied().unwrap_or(0)); + assert!(brightest - darkest > 100, "the black and white halves both show: {darkest}..{brightest}"); + let missing = render(&OrbMaterial::of_fill(&fill, &[Channel::BaseColor], &Default::default()), 64, BACKDROP); + assert_ne!(missing.pixels, image.pixels, "a missing image reads the default"); + } + + #[test] + fn hostile_sizes_and_values_render_without_panicking() { + for side in [0, 1, 2, 100_000] { + let image = render(&OrbMaterial::uniform([f32::NAN, f32::INFINITY, -1.0], f32::NAN, f32::NEG_INFINITY), side, BACKDROP); + assert!(image.size[0] >= 1 && image.size[0] <= MAX_SIDE_PX); + } + } + + #[test] + fn the_orb_renders_at_its_size_on_screen_times_the_screen_scale() { + use std::time::{Duration, Instant}; + + use crate::orb_previews::OrbPreviews; + + // 160 points: wider than the old 256-pixel cap once doubled + for scale in [1.0_f32, 2.0] { + let ctx = egui::Context::default(); + ctx.set_pixels_per_point(scale); + let material = copper(); + let expected = (160.0 * scale) as usize; + let start = Instant::now(); + while OrbPreviews::shown_size(&ctx, "hidpi") != Some([expected, expected]) && start.elapsed() < Duration::from_secs(20) { + let mut output = ctx.run_pass(Default::default(), |ctx| { + let painter = ctx.layer_painter(egui::LayerId::background()); + let rect = Rect::from_min_size(pos2(10.0, 10.0), egui::vec2(160.0, 160.0)); + material_orb(&painter, rect, &material, &Tokens::get(ctx), "hidpi"); + }); + + // Nothing draws these textures here + output.textures_delta.clear(); + std::thread::sleep(Duration::from_millis(5)); + } + assert_eq!(OrbPreviews::shown_size(&ctx, "hidpi"), Some([expected, expected]), "at {scale}x"); + } + } + + /// Milliseconds per orb, written by `cargo test --release -p texturecraft-ui-egui --lib -- orb_render_timing --ignored --nocapture` + #[test] + #[ignore = "a timing, not a check"] + fn orb_render_timing() { + use std::time::Instant; + + use texturecraft_engine::compose::ImageRes; + + let started = Instant::now(); + crate::orb_environment::OrbEnvironment::get(); + eprintln!("studio prefilter (once): {:.1} ms", started.elapsed().as_secs_f64() * 1000.0); + let rgba = (0..512 * 512).map(|i| [(i % 512) as f32 / 512.0, 0.5, (i / 512) as f32 / 512.0, 1.0]).collect(); + let images = std::collections::HashMap::from([("photo".to_owned(), std::sync::Arc::new(ImageRes::new(512, 512, rgba, true)))]); + let mut complex = Fill::default(); + complex.sources.insert(Channel::BaseColor, Source::Image { name: "photo".into(), normal_format: Default::default() }); + complex.sources.insert( + Channel::Roughness, + Source::Procedural { pattern: Procedural::new(ProceduralKind::Clouds), low: [0.2; 3], high: [0.8; 3], ramp: Vec::new() }, + ); + complex + .sources + .insert(Channel::Height, Source::Procedural { pattern: Procedural::new(ProceduralKind::Cells), low: [-1.0; 3], high: [1.0; 3], ramp: Vec::new() }); + complex.sources.insert( + Channel::Normal, + Source::Procedural { pattern: Procedural::new(ProceduralKind::Perlin), low: [0.3, 0.5, 0.9], high: [0.7, 0.5, 0.9], ramp: Vec::new() }, + ); + let on = [Channel::BaseColor, Channel::Roughness, Channel::Height, Channel::Normal]; + let looks = [("uniform", copper()), ("image+procedurals+height+normal", OrbMaterial::of_fill(&complex, &on, &images))]; + for (name, look) in looks { + for side in [25, 100, 200, 400] { + let runs = 10; + let started = Instant::now(); + for _ in 0..runs { + std::hint::black_box(render(&look, side, BACKDROP)); + } + eprintln!("{name} {side}px: {:.2} ms", started.elapsed().as_secs_f64() * 1000.0 / f64::from(runs)); + } + } + } + + #[test] + fn a_channel_alone_shows_unlit_as_the_viewports_channel_view_draws_it() { + let mut fill = fill_with(Channel::BaseColor, Source::Uniform([0.8, 0.35, 0.18])); + fill.sources.insert(Channel::Roughness, Source::Uniform([0.3; 3])); + fill.sources.insert(Channel::Height, Source::Uniform([0.5; 3])); + let on = [Channel::BaseColor, Channel::Roughness, Channel::Height]; + let byte = |value: f32| (value * 255.0).round() as u8; + let encoded = |value: f32| byte(linear_to_srgb(value)); + + for (channel, expected) in [ + (Channel::BaseColor, Color32::from_rgb(encoded(0.8), encoded(0.35), encoded(0.18))), + (Channel::Roughness, Color32::from_gray(encoded(0.3))), + (Channel::Height, Color32::from_gray(byte(0.75))), + (Channel::Metallic, Color32::from_gray(0)), + ] { + let image = render(&OrbMaterial::of_channel(&fill, channel, &on, &Default::default()), 64, BACKDROP); + + assert_eq!(at(&image, 32, 32), expected, "{channel:?} at the centre"); + assert_eq!(at(&image, 12, 32), expected, "{channel:?} unlit: the same off the centre"); + assert_eq!(image.pixels[0], BACKDROP, "{channel:?} sits on the backdrop"); + } + } + + #[test] + fn the_key_changes_with_the_look_and_only_with_it() { + let a = OrbMaterial::uniform([0.8, 0.35, 0.18], 1.0, 0.35); + assert_eq!(a.key(), copper().key()); + assert_ne!(a.key(), OrbMaterial::uniform([0.8, 0.35, 0.18], 1.0, 0.36).key()); + } +} diff --git a/crates/ui-egui/src/orb_environment.rs b/crates/ui-egui/src/orb_environment.rs new file mode 100644 index 00000000..c7d50c8e --- /dev/null +++ b/crates/ui-egui/src/orb_environment.rs @@ -0,0 +1,78 @@ +//! The studio that lights every material orb: a bundled photographed environment (CC0, see ATTRIBUTION.md), prefiltered once for +//! glossy reflections and reduced to spherical harmonics for diffuse light + +use std::sync::OnceLock; + +use texturecraft_engine::geom::glam::Vec3; +use texturecraft_render::ibl::{self, EnvImage}; + +/// The bundled environment: a small photo studio with soft boxes, 512 x 256 equirect Radiance HDR +const STUDIO_HDR: &[u8] = include_bytes!("../../../assets/environments/studio_small_09_512.hdr"); + +/// Prefiltered levels from mirror (0) to fully rough (last) +const LEVELS: u32 = 6; + +/// How far the studio is turned about the vertical axis (radians) so its key soft box lights the orb from the upper left +const TURN: f32 = 4.4; + +/// The prefiltered studio +pub(crate) struct OrbEnvironment { + /// Level `l` holds reflections for roughness `l / (LEVELS - 1)` + levels: Vec, + /// Diffuse light as 9 spherical-harmonics coefficients + irradiance: [[f32; 3]; 9], +} + +impl OrbEnvironment { + /// The studio, decoded and prefiltered by the first caller (about a tenth of a second in release) + pub(crate) fn get() -> &'static OrbEnvironment { + static STUDIO: OnceLock = OnceLock::new(); + STUDIO.get_or_init(|| OrbEnvironment::from_hdr(STUDIO_HDR).unwrap_or_else(OrbEnvironment::fallback)) + } + + fn from_hdr(bytes: &[u8]) -> Option { + let decoded = + image::load_from_memory_with_format(bytes, image::ImageFormat::Hdr).inspect_err(|e| log::warn!("the orb studio did not load: {e}")).ok()?; + + let rgb = decoded.into_rgb32f(); + let (pixels, _) = rgb.as_raw().as_chunks::<3>(); + drop(rgb); + + Some(OrbEnvironment::of(&env)) + } + + /// The built-in procedural studio, should the bundled one ever fail to decode + fn fallback() -> OrbEnvironment { + OrbEnvironment::of(&ibl::environment("Studio Soft", 256)) + } + + fn of(env: &EnvImage) -> OrbEnvironment { + OrbEnvironment { levels: ibl::prefilter(env, LEVELS), irradiance: ibl::sh9(env) } + } + + /// Light reflected towards unit direction `direction` (view space: +X right, +Y up, +Z towards the viewer) by a surface of `roughness` + pub(crate) fn reflected(&self, direction: Vec3, roughness: f32) -> Vec3 { + let turned = turn(direction); + let level = roughness.clamp(0.0, 1.0) * (self.levels.len().saturating_sub(1)) as f32; + let below = level.floor() as usize; + let sample = |index: usize| self.levels.get(index).or(self.levels.last()).map_or(Vec3::ZERO, |env| env.sample(turned)); + let fraction = level - level.floor(); + if fraction <= 0.0 { sample(below) } else { sample(below).lerp(sample(below + 1), fraction) } + } + + /// Diffuse light reaching a surface with unit normal `normal` (view space) + pub(crate) fn diffuse(&self, normal: Vec3) -> Vec3 { + let basis = ibl::sh_basis(turn(normal)); + let mut light = Vec3::ZERO; + for (coefficient, weight) in self.irradiance.iter().zip(basis) { + light += Vec3::from(*coefficient) * weight; + } + light.max(Vec3::ZERO) + } +} + +/// `direction` in the studio's frame +fn turn(direction: Vec3) -> Vec3 { + let (sin, cos) = TURN.sin_cos(); + Vec3::new(direction.x * cos + direction.z * sin, direction.y, direction.z * cos - direction.x * sin) +} diff --git a/crates/ui-egui/src/orb_material.rs b/crates/ui-egui/src/orb_material.rs new file mode 100644 index 00000000..5a1a7da6 --- /dev/null +++ b/crates/ui-egui/src/orb_material.rs @@ -0,0 +1,185 @@ +//! What a material orb shows: every channel the orb lights with, read from the fill's own sources through its own projection + +use std::collections::BTreeMap; +use std::fmt::Write as _; +use std::hash::{DefaultHasher, Hash, Hasher}; +use std::sync::{Arc, Weak}; + +use texturecraft_engine::compose::ImageRes; +use texturecraft_engine::compose::pattern::{Coords, image_samples, procedural}; +use texturecraft_engine::core::blend::lum; +use texturecraft_engine::core::{Channel, ChannelKind, Fill, NormalFormat, Projection, Sampling, Source}; +use texturecraft_engine::geom::glam::{Vec2, Vec3}; +use texturecraft_engine::texel::srgb_to_linear; + +mod hash_writer; +mod orb_sample; + +use hash_writer::HashWriter; +pub(crate) use orb_sample::OrbSample; + +/// The channels the orb reads; the others do not change how it looks +pub(crate) const ORB_CHANNELS: [Channel; 7] = + [Channel::BaseColor, Channel::Metallic, Channel::Roughness, Channel::Normal, Channel::Height, Channel::Emissive, Channel::Opacity]; + +/// Fewest and most image repeats the orb's filtering assumes, so a tiny or huge projection scale neither blurs nor aliases without bound +const MIN_IMAGE_SCALE: f32 = 0.01; +const MAX_IMAGE_SCALE: f32 = 64.0; + +/// A material as the orb shows it +#[derive(Clone, Debug)] +pub(crate) struct OrbMaterial { + sources: BTreeMap, + projection: Projection, + sampling: Sampling, + /// The images the sources read, shared with the session + images: BTreeMap>, + /// The one channel shown on its own, unlit, as the viewport's channel view draws it; `None` = the whole material, lit + alone: Option, +} + +impl OrbMaterial { + /// One value per channel: a plain material's base colour, metallic and roughness + #[cfg(test)] + pub(crate) fn uniform(base: [f32; 3], metallic: f32, roughness: f32) -> OrbMaterial { + let sources = BTreeMap::from([ + (Channel::BaseColor, Source::Uniform(base)), + (Channel::Metallic, Source::Uniform([metallic; 3])), + (Channel::Roughness, Source::Uniform([roughness; 3])), + ]); + OrbMaterial { sources, projection: Projection::default(), sampling: Sampling::default(), images: BTreeMap::new(), alone: None } + } + + /// `fill` with the channels in `on`; channels that are off show their defaults, images come from `images` + pub(crate) fn of_fill(fill: &Fill, on: &[Channel], images: &std::collections::HashMap>) -> OrbMaterial { + OrbMaterial::with_channels(fill, ORB_CHANNELS.into_iter().filter(|channel| on.contains(channel)), images, None) + } + + /// `fill`'s `channel` alone (its default when the fill does not write it, `on` being the channels it writes) + pub(crate) fn of_channel(fill: &Fill, channel: Channel, on: &[Channel], images: &std::collections::HashMap>) -> OrbMaterial { + OrbMaterial::with_channels(fill, on.contains(&channel).then_some(channel), images, Some(channel)) + } + + fn with_channels( + fill: &Fill, + channels: impl IntoIterator, + images: &std::collections::HashMap>, + alone: Option, + ) -> OrbMaterial { + let sources: BTreeMap = channels.into_iter().map(|channel| (channel, fill.source(channel))).collect(); + let images = sources + .values() + .filter_map(|source| match source { + Source::Image { name, .. } => images.get(name).map(|image| (name.clone(), image.clone())), + _ => None, + }) + .collect(); + OrbMaterial { sources, projection: fill.projection.clone(), sampling: fill.sampling, images, alone } + } + + /// The channel the orb shows on its own, if any + pub(crate) fn alone(&self) -> Option { + self.alone + } + + /// The images it reads, held weakly: while a cached picture holds them, a new image can't take a freed one's address, which [`OrbMaterial::key`] hashes + pub(crate) fn image_handles(&self) -> Vec> { + self.images.values().map(Arc::downgrade).collect() + } + + /// A key that changes whenever the orb would look different + pub(crate) fn key(&self) -> u64 { + let mut hasher = DefaultHasher::new(); + + // Writing to a hasher cannot fail + let _ = write!(HashWriter(&mut hasher), "{:?}{:?}{:?}{:?}", self.sources, self.projection, self.sampling, self.alone); + for (name, image) in &self.images { + // The same name re-imported is a new image + (name, Arc::as_ptr(image) as usize, image.width, image.height).hash(&mut hasher); + } + hasher.finish() + } + + /// Whether any channel varies over the surface (a uniform material needs no per-pixel reads) + pub(crate) fn varies(&self) -> bool { + self.sources.values().any(|source| !matches!(source, Source::Uniform(_))) + } + + /// The material at `coords`; `footprint` = how far one orb pixel reaches in UVs + pub(crate) fn sample(&self, coords: &Coords, footprint: f32) -> OrbSample { + let value = |channel: Channel| self.value(channel, coords, footprint); + let [metallic, roughness, opacity] = [Channel::Metallic, Channel::Roughness, Channel::Opacity].map(|channel| value(channel)[0]); + OrbSample { base: value(Channel::BaseColor), metallic, roughness, normal: value(Channel::Normal), emissive: value(Channel::Emissive), opacity } + } + + /// The height at `coords` (0 without a height channel) + pub(crate) fn height(&self, coords: &Coords, footprint: f32) -> f32 { + self.value(Channel::Height, coords, footprint)[0] + } + + /// Whether the height channel varies (only then does it bump the surface) + pub(crate) fn has_relief(&self) -> bool { + self.sources.get(&Channel::Height).is_some_and(|source| !matches!(source, Source::Uniform(_))) + } + + /// `channel`'s value at `coords` (linear; normals 0..1 per component, height -1..1) + pub(crate) fn value(&self, channel: Channel, coords: &Coords, footprint: f32) -> [f32; 3] { + let Some(source) = self.sources.get(&channel) else { return channel.default_value() }; + match source { + Source::Uniform(value) => *value, + Source::Procedural { pattern, low, high, ramp } => { + let amount = procedural(pattern, &self.projection, coords); + + // A colour channel's gradient map colours the pattern as the layer stack does + if channel.kind() == ChannelKind::Color && !ramp.is_empty() { + texturecraft_engine::core::gradient(ramp, amount).unwrap_or_default() + } else { + [0, 1, 2].map(|k| low[k] + (high[k] - low[k]) * amount) + } + } + Source::Image { name, normal_format } => { + let Some(image) = self.images.get(name) else { return channel.default_value() }; + self.image_value(image, channel.kind(), *normal_format, coords, footprint) + } + + // An anchor reads another layer's result, which only the layer stack knows + Source::Anchor { .. } => channel.default_value(), + } + } + + fn image_value(&self, image: &ImageRes, kind: ChannelKind, normal_format: NormalFormat, coords: &Coords, footprint: f32) -> [f32; 3] { + let mut sum = [0.0f32; 3]; + for (uv, weight) in image_samples(&self.projection, coords).into_iter().filter(|(_, weight)| *weight > 0.0) { + let texel = image.sample_filtered(uv.x, uv.y, self.sampling, footprint * image.width as f32 * image_scale(&self.projection)); + for (total, value) in sum.iter_mut().zip(texel) { + *total += value * weight; + } + } + match kind { + ChannelKind::Color if image.srgb => sum.map(srgb_to_linear), + // Normal channels are OpenGL (+Y up the image): a DirectX image's green flips + ChannelKind::NormalMap if normal_format == NormalFormat::DirectX => [sum[0], 1.0 - sum[1], sum[2]], + ChannelKind::Color | ChannelKind::NormalMap => sum, + ChannelKind::Scalar => [lum(sum); 3], + ChannelKind::Signed => [lum(sum) * 2.0 - 1.0; 3], + } + } +} + +/// How many image repeats the projection lays across the orb's width, roughly (sharper filtering for fewer) +fn image_scale(projection: &Projection) -> f32 { + let scale = match projection { + Projection::Triplanar { scale, .. } | Projection::Planar { scale, .. } => *scale, + Projection::Spherical { scale, .. } | Projection::Cylindrical { scale, .. } => scale.max(1.0), + Projection::Uv { scale, .. } => scale[0].abs().max(scale[1].abs()), + Projection::UvTile | Projection::Warp { .. } => 1.0, + }; + if scale.is_finite() { scale.abs().clamp(MIN_IMAGE_SCALE, MAX_IMAGE_SCALE) } else { 1.0 } +} + +/// Where a point of the unit orb lies for a fill's projection: its position and normal (both the unit direction `direction`), and UVs wrapping once around the equator (two across) and once from pole to pole +pub(crate) fn orb_coords(direction: Vec3) -> Coords { + let u = direction.z.atan2(direction.x) / std::f32::consts::TAU + 0.5; + let v = direction.y.clamp(-1.0, 1.0).acos() / std::f32::consts::PI; + Coords { uv: Vec2::new(u * 2.0, v), pos: direction, nrm: direction } +} diff --git a/crates/ui-egui/src/orb_material/hash_writer.rs b/crates/ui-egui/src/orb_material/hash_writer.rs new file mode 100644 index 00000000..4c0c6140 --- /dev/null +++ b/crates/ui-egui/src/orb_material/hash_writer.rs @@ -0,0 +1,12 @@ +use std::fmt; +use std::hash::Hasher; + +/// Feeds formatted text straight into a hasher, so a `Debug` key needs no string +pub(super) struct HashWriter<'h, H: Hasher>(pub(super) &'h mut H); + +impl fmt::Write for HashWriter<'_, H> { + fn write_str(&mut self, text: &str) -> fmt::Result { + self.0.write(text.as_bytes()); + Ok(()) + } +} diff --git a/crates/ui-egui/src/orb_material/orb_sample.rs b/crates/ui-egui/src/orb_material/orb_sample.rs new file mode 100644 index 00000000..606b07fe --- /dev/null +++ b/crates/ui-egui/src/orb_material/orb_sample.rs @@ -0,0 +1,11 @@ +/// The orb's values at one point of its surface (linear) +#[derive(Clone, Copy, Debug, PartialEq)] +pub(crate) struct OrbSample { + pub(crate) base: [f32; 3], + pub(crate) metallic: f32, + pub(crate) roughness: f32, + /// Tangent-space normal, OpenGL (+Y up), 0..1 per component + pub(crate) normal: [f32; 3], + pub(crate) emissive: [f32; 3], + pub(crate) opacity: f32, +} diff --git a/crates/ui-egui/src/orb_previews.rs b/crates/ui-egui/src/orb_previews.rs new file mode 100644 index 00000000..ffc478d4 --- /dev/null +++ b/crates/ui-egui/src/orb_previews.rs @@ -0,0 +1,352 @@ +//! Material orb pictures, cached by look and rendered off the UI thread: a quick low-resolution picture first, then the full one +//! (the web, which has no threads, renders the full picture at once) + +use std::collections::HashMap; +use std::collections::hash_map::Entry; +use std::sync::{Arc, Mutex}; + +use egui::{ColorImage, Context, Id, TextureHandle, TextureOptions}; + +mod orb_job; +#[cfg(not(target_arch = "wasm32"))] +mod orb_result; +mod picture; +#[cfg(not(target_arch = "wasm32"))] +mod worker; + +pub(crate) use orb_job::OrbJob; +#[cfg(not(target_arch = "wasm32"))] +use orb_result::OrbResult; +use picture::Picture; +#[cfg(not(target_arch = "wasm32"))] +use worker::Worker; + +/// Pictures kept; the least recently drawn go first (a list of every plain material holds about fifty) +const MAX_PICTURES: usize = 160; + +/// Most places that keep their last drawn picture (an orb place outlives its look, so places can outnumber pictures) +const MAX_SHOWN_PLACES: usize = MAX_PICTURES * 2; + +/// The quick first picture is this many times smaller than the full one, and pictures this small skip it +const QUICK_DIVISOR: usize = 4; +const QUICK_BELOW_PX: usize = 48; + +/// Every orb picture of one egui context +#[derive(Default)] +pub struct OrbPreviews { + pictures: HashMap, + /// The picture last drawn at each place and the pass it was drawn in, shown while that place's new one renders + shown: HashMap, + #[cfg(not(target_arch = "wasm32"))] + worker: Option, +} + +type Shared = Arc>; + +impl OrbPreviews { + /// The picture to draw at `place` for the look `key` (see [`OrbJob::key_of`]): its own once rendered, else the last one drawn there (None before the first); `job` builds the render only when the look is new + pub(crate) fn texture(ctx: &Context, place: Id, key: u64, job: impl FnOnce() -> OrbJob) -> Option { + let shared = ctx.data_mut(|data| data.get_temp_mut_or_default::(Id::unique("orb_previews")).clone()); + let mut previews = shared.lock().ok()?; + previews.take_results(ctx); + let pass = ctx.cumulative_pass_nr(); + if let Entry::Vacant(slot) = previews.pictures.entry(key) { + let job = job(); + slot.insert(Picture { texture: None, full: false, drawn: pass, _images: job.material.image_handles() }); + #[cfg(not(target_arch = "wasm32"))] + let job = OrbJob { place, ..job }; + previews.start(ctx, job); + } + let ready = previews.pictures.get_mut(&key).and_then(|picture| { + picture.drawn = pass; + picture.texture.clone() + }); + let on_screen = match ready { + Some(texture) => { + previews.shown.insert(place, (texture.clone(), pass)); + Some(texture) + } + None => previews.shown.get_mut(&place).map(|(texture, drawn)| { + *drawn = pass; + texture.clone() + }), + }; + + // A new look or a new place may pass the cap + previews.forget_old(); + on_screen + } + + /// Whether every orb asked for has its full picture (tests and captures wait for this) + pub fn settled(ctx: &Context) -> bool { + let shared = ctx.data_mut(|data| data.get_temp_mut_or_default::(Id::unique("orb_previews")).clone()); + let Ok(mut previews) = shared.lock() else { return true }; + previews.take_results(ctx); + previews.pictures.values().all(|picture| picture.full) + } + + /// The size in pixels of the picture last drawn at `place` (tests) + #[cfg(test)] + pub(crate) fn shown_size(ctx: &Context, place: &str) -> Option<[usize; 2]> { + let shared = ctx.data_mut(|data| data.get_temp_mut_or_default::(Id::unique("orb_previews")).clone()); + let previews = shared.lock().ok()?; + previews.shown.get(&Id::unique(("material_orb", place))).map(|(texture, _)| texture.size()) + } + + fn store(&mut self, ctx: &Context, key: u64, full: bool, image: ColorImage) { + if let Some(picture) = self.pictures.get_mut(&key) + && !picture.full + { + picture.texture = Some(ctx.load_texture("material-orb", image, TextureOptions::LINEAR)); + picture.full = full; + } + } + + /// Drop the least recently drawn pictures past [`MAX_PICTURES`] and places' last shown pictures past [`MAX_SHOWN_PLACES`] + fn forget_old(&mut self) { + while self.pictures.len() > MAX_PICTURES { + let Some(oldest) = self.pictures.iter().min_by_key(|(_, picture)| picture.drawn).map(|(key, _)| *key) else { break }; + self.pictures.remove(&oldest); + } + + // A place no longer drawn (a deleted layer) must not keep its texture alive + while self.shown.len() > MAX_SHOWN_PLACES { + let Some(oldest) = self.shown.iter().min_by_key(|(_, (_, drawn))| *drawn).map(|(place, _)| *place) else { break }; + self.shown.remove(&oldest); + } + } + + /// The web renders the full picture at once + #[cfg(target_arch = "wasm32")] + fn start(&mut self, ctx: &Context, job: OrbJob) { + let job = OrbJob { quick: false, ..job }; + self.store(ctx, job.key, true, job.picture()); + } + + #[cfg(target_arch = "wasm32")] + fn take_results(&mut self, _ctx: &Context) {} + + #[cfg(not(target_arch = "wasm32"))] + fn start(&mut self, ctx: &Context, job: OrbJob) { + let key = job.key; + let worker = match self.worker.take() { + Some(worker) => worker, + None => match Worker::start() { + Some(worker) => worker, + None => { + // No thread: render here rather than show nothing + let job = OrbJob { quick: false, ..job }; + self.store(ctx, key, true, job.picture()); + return; + } + }, + }; + match worker.jobs.send((job, ctx.clone())) { + Ok(()) => self.worker = Some(worker), + Err(std::sync::mpsc::SendError((job, _))) => { + let job = OrbJob { quick: false, ..job }; + self.store(ctx, key, true, job.picture()); + } + } + } + + #[cfg(not(target_arch = "wasm32"))] + fn take_results(&mut self, ctx: &Context) { + let Some(worker) = &self.worker else { return }; + let results: Vec = worker.results.try_iter().collect(); + for result in results { + match result { + OrbResult::Picture { key, full, image } => self.store(ctx, key, full, image), + OrbResult::Dropped { key } => { + // Asked for again the next time it is drawn (its place keeps showing what it last showed) + self.pictures.remove(&key); + } + } + } + } +} + +/// Keep only the newest job per place (others than [`Id::NULL`]); returns the keys of the jobs dropped +#[cfg(not(target_arch = "wasm32"))] +fn newest_per_place(waiting: &mut Vec) -> Vec { + let mut seen = std::collections::HashSet::new(); + let mut dropped = Vec::new(); + let mut kept: Vec = Vec::with_capacity(waiting.len()); + for job in waiting.drain(..).rev() { + if job.place == Id::NULL || seen.insert(job.place) { + kept.push(job); + } else { + dropped.push(job.key); + } + } + kept.reverse(); + *waiting = kept; + dropped +} + +#[cfg(test)] +mod tests { + use std::collections::BTreeMap; + use std::time::{Duration, Instant}; + + use egui::Color32; + use texturecraft_engine::compose::ImageRes; + use texturecraft_engine::core::{Channel, Fill, Source}; + + use super::*; + use crate::orb_material::OrbMaterial; + + fn copper(roughness: f32) -> OrbMaterial { + OrbMaterial::uniform([0.8, 0.35, 0.18], 1.0, roughness) + } + + /// One UI pass; nothing draws the textures it makes, so their updates are dropped + fn run(ctx: &Context, ui: impl FnMut(&Context)) { + let mut output = ctx.run_pass(Default::default(), ui); + output.textures_delta.clear(); + } + + /// Draw `job` at `place` every pass until it is full or 20 s pass; returns the sizes shown on the way + fn draw_until_settled(ctx: &Context, place: Id, job: &OrbJob) -> Vec<[usize; 2]> { + let start = Instant::now(); + let mut sizes = Vec::new(); + while start.elapsed() < Duration::from_secs(20) { + let mut size = None; + run(ctx, |ctx| size = OrbPreviews::texture(ctx, place, job.key, || job.clone()).map(|texture| texture.size())); + if let Some(size) = size + && sizes.last() != Some(&size) + { + sizes.push(size); + } + if OrbPreviews::settled(ctx) { + run(ctx, |ctx| size = OrbPreviews::texture(ctx, place, job.key, || job.clone()).map(|texture| texture.size())); + if let Some(size) = size + && sizes.last() != Some(&size) + { + sizes.push(size); + } + break; + } + std::thread::sleep(Duration::from_millis(5)); + } + sizes + } + + #[test] + fn an_orb_renders_off_the_ui_thread_quick_first_then_full_and_is_cached_by_its_look() { + let ctx = Context::default(); + let place = Id::unique("orb"); + let job = OrbJob::new(copper(0.3), 200, Color32::BLACK); + let mut first = None; + run(&ctx, |ctx| first = OrbPreviews::texture(ctx, place, job.key, || job.clone())); + assert!(first.is_none(), "the first pass does not wait for the render"); + let sizes = draw_until_settled(&ctx, place, &job); + + // A fast render can bring both pictures between two frames, so only the full one is sure to show; the quick one never comes after it + let quick_then_full: &[[usize; 2]] = &[[50, 50], [200, 200]]; + assert!(sizes == quick_then_full || sizes == quick_then_full[1..], "the quick picture, if shown, then the full one: {sizes:?}"); + assert!(OrbPreviews::settled(&ctx)); + + // The same look again: drawn at once from the cache, nothing new to render + let mut again = None; + run(&ctx, |ctx| again = OrbPreviews::texture(ctx, place, job.key, || job.clone())); + assert_eq!(again.map(|texture| texture.size()), Some([200, 200])); + assert!(OrbPreviews::settled(&ctx), "a cached look renders nothing"); + + // A new look keeps the old picture on screen until its own arrives + let rougher = OrbJob::new(copper(0.8), 200, Color32::BLACK); + let mut meanwhile = None; + run(&ctx, |ctx| meanwhile = OrbPreviews::texture(ctx, place, rougher.key, || rougher.clone())); + assert!(meanwhile.is_some(), "the last picture stays while the new one renders"); + assert!(!OrbPreviews::settled(&ctx), "the new look is rendering"); + draw_until_settled(&ctx, place, &rougher); + assert!(OrbPreviews::settled(&ctx)); + } + + /// A dropped context lets go of its orb pictures and closes its worker's job channel: the idle worker holds no context + #[test] + fn a_dropped_context_frees_its_previews_while_the_worker_idles() { + // Long enough for the worker to finish its last job on a busy machine + const ATTEMPTS: usize = 2000; + const WAIT: Duration = Duration::from_millis(5); + let ctx = Context::default(); + let job = OrbJob::new(copper(0.3), 64, Color32::BLACK); + draw_until_settled(&ctx, Id::unique("orb"), &job); + let shared = ctx.data(|data| data.get_temp::(Id::unique("orb_previews"))).unwrap(); + let previews = Arc::downgrade(&shared); + drop(shared); + + drop(ctx); + + let freed = (0..ATTEMPTS).any(|_| { + let freed = previews.upgrade().is_none(); + if !freed { + std::thread::sleep(WAIT); + } + freed + }); + assert!(freed, "the worker kept the dropped context and its previews alive"); + } + + #[test] + fn a_newer_look_for_the_same_place_replaces_one_still_waiting() { + let job = |roughness: f32| OrbJob { place: Id::unique("orb"), ..OrbJob::new(copper(roughness), 64, Color32::BLACK) }; + let other = OrbJob { place: Id::unique("other"), ..OrbJob::new(copper(0.5), 64, Color32::BLACK) }; + let mut waiting = vec![job(0.1), other.clone(), job(0.2), job(0.3)]; + let dropped = newest_per_place(&mut waiting); + assert_eq!(dropped.len(), 2); + assert_eq!(waiting.iter().map(|job| job.key).collect::>(), vec![other.key, job(0.3).key]); + } + + #[test] + fn places_no_longer_drawn_let_go_of_their_last_picture_past_the_cap() { + let ctx = Context::default(); + let texture = ctx.load_texture("orb", ColorImage::filled([1, 1], Color32::BLACK), TextureOptions::LINEAR); + let mut previews = OrbPreviews::default(); + let places = MAX_SHOWN_PLACES as u64 + 10; + for pass in 0..places { + previews.shown.insert(Id::unique(("orb", pass)), (texture.clone(), pass)); + } + + previews.forget_old(); + + assert_eq!(previews.shown.len(), MAX_SHOWN_PLACES, "the cap holds for places too"); + assert!(!previews.shown.contains_key(&Id::unique(("orb", 0_u64))), "the least recently drawn place goes first"); + assert!(previews.shown.contains_key(&Id::unique(("orb", places - 1))), "the latest drawn place stays"); + } + + /// An orb of a fill whose base colour reads `image` under one name, the name a re-import keeps + fn image_orb(image: Arc) -> OrbJob { + let fill = Fill { sources: BTreeMap::from([(Channel::BaseColor, Source::image(REIMPORTED))]), ..Fill::default() }; + let images = HashMap::from([(REIMPORTED.to_owned(), image)]); + OrbJob::new(OrbMaterial::of_fill(&fill, &[Channel::BaseColor], &images), 64, Color32::BLACK) + } + + /// An image name imported twice + const REIMPORTED: &str = "grain"; + + #[test] + fn a_new_image_under_a_cached_ones_name_and_size_gets_its_own_picture() { + let ctx = Context::default(); + let place = Id::unique("orb"); + let image = Arc::new(ImageRes::new(2, 2, vec![[0.1; 4]; 4], false)); + let first = image_orb(Arc::clone(&image)); + draw_until_settled(&ctx, place, &first); + let first_key = first.key; + drop(first); + + // The cached picture holds the image weakly, so its address stays taken however the allocator reuses blocks + assert!(Arc::weak_count(&image) >= 1, "the cached picture keeps the image's address"); + drop(image); + + // Same name and size: the freed image's address must not come back to the cached picture's key + let second = image_orb(Arc::new(ImageRes::new(2, 2, vec![[0.9; 4]; 4], false))); + assert_ne!(second.key, first_key, "the new image's orb is drawn anew"); + } + + #[test] + fn small_orbs_skip_the_quick_picture() { + assert!(!OrbJob::new(copper(0.3), 24, Color32::BLACK).quick); + assert!(OrbJob::new(copper(0.3), 96, Color32::BLACK).quick); + } +} diff --git a/crates/ui-egui/src/orb_previews/orb_job.rs b/crates/ui-egui/src/orb_previews/orb_job.rs new file mode 100644 index 00000000..f14316cd --- /dev/null +++ b/crates/ui-egui/src/orb_previews/orb_job.rs @@ -0,0 +1,49 @@ +use std::hash::{DefaultHasher, Hash, Hasher}; + +#[cfg(not(target_arch = "wasm32"))] +use egui::Id; +use egui::{Color32, ColorImage}; + +use super::{QUICK_BELOW_PX, QUICK_DIVISOR}; +use crate::material_orb::render; +use crate::orb_material::OrbMaterial; + +/// One orb to render +#[derive(Clone, Debug)] +pub(crate) struct OrbJob { + pub(super) key: u64, + pub(super) material: OrbMaterial, + pub(super) side: usize, + pub(super) backdrop: Color32, + /// Where it is drawn: a newer job for the same place replaces an older one still waiting (the web renders each job at once) + #[cfg(not(target_arch = "wasm32"))] + pub(super) place: Id, + /// The quick picture is still to come + pub(super) quick: bool, +} + +impl OrbJob { + pub(crate) fn new(material: OrbMaterial, side: usize, backdrop: Color32) -> OrbJob { + OrbJob { + key: OrbJob::key_of(&material, side, backdrop), + material, + side, + backdrop, + #[cfg(not(target_arch = "wasm32"))] + place: Id::NULL, + quick: side >= QUICK_BELOW_PX, + } + } + + /// The cache key of `material`'s orb `side` pixels square on `backdrop`, without building the job + pub(crate) fn key_of(material: &OrbMaterial, side: usize, backdrop: Color32) -> u64 { + let mut hasher = DefaultHasher::new(); + (material.key(), side, backdrop.to_array()).hash(&mut hasher); + hasher.finish() + } + + pub(super) fn picture(&self) -> ColorImage { + let side = if self.quick { self.side / QUICK_DIVISOR } else { self.side }; + render(&self.material, side, self.backdrop) + } +} diff --git a/crates/ui-egui/src/orb_previews/orb_result.rs b/crates/ui-egui/src/orb_previews/orb_result.rs new file mode 100644 index 00000000..54666899 --- /dev/null +++ b/crates/ui-egui/src/orb_previews/orb_result.rs @@ -0,0 +1,14 @@ +use egui::ColorImage; + +/// What the worker answers +pub(super) enum OrbResult { + Picture { + key: u64, + full: bool, + image: ColorImage, + }, + /// A newer job for its place replaced it before it was finished + Dropped { + key: u64, + }, +} diff --git a/crates/ui-egui/src/orb_previews/picture.rs b/crates/ui-egui/src/orb_previews/picture.rs new file mode 100644 index 00000000..06a6d813 --- /dev/null +++ b/crates/ui-egui/src/orb_previews/picture.rs @@ -0,0 +1,14 @@ +use std::sync::Weak; + +use egui::TextureHandle; +use texturecraft_engine::compose::ImageRes; + +/// A cached picture +pub(super) struct Picture { + pub(super) texture: Option, + pub(super) full: bool, + /// The pass it was last drawn in + pub(super) drawn: u64, + /// The images it shows, so no new image reuses their addresses (and so their key) while it is cached + pub(super) _images: Vec>, +} diff --git a/crates/ui-egui/src/orb_previews/worker.rs b/crates/ui-egui/src/orb_previews/worker.rs new file mode 100644 index 00000000..ad7d8260 --- /dev/null +++ b/crates/ui-egui/src/orb_previews/worker.rs @@ -0,0 +1,73 @@ +use egui::Context; + +use super::{OrbJob, OrbResult, newest_per_place}; + +/// The thread that renders orbs +pub(super) struct Worker { + /// Each job comes with the context to repaint when its picture is ready + pub(super) jobs: std::sync::mpsc::Sender<(OrbJob, Context)>, + pub(super) results: std::sync::mpsc::Receiver, +} + +impl Worker { + pub(super) fn start() -> Option { + let (jobs, job_rx) = std::sync::mpsc::channel::<(OrbJob, Context)>(); + let (result_tx, results) = std::sync::mpsc::channel(); + let spawned = std::thread::Builder::new().name("texturecraft-material-orbs".into()).spawn(move || { + // Its own pool keeps orbs from queuing ahead of painting and compositing + let threads = std::thread::available_parallelism().map_or(1, |n| n.get().saturating_sub(1).max(1)); + let pool = rayon::ThreadPoolBuilder::new().num_threads(threads).thread_name(|i| format!("texturecraft-orb-{i}")).build(); + let mut waiting: Vec = Vec::new(); + let mut repaint: Option = None; + loop { + if waiting.is_empty() { + // Idle, the thread holds no context: the context owns the job sender, so a held one would keep both alive + drop(repaint.take()); + let Ok((job, ctx)) = job_rx.recv() else { break }; + waiting.push(job); + repaint = Some(ctx); + } + for (job, ctx) in job_rx.try_iter() { + waiting.push(job); + repaint = Some(ctx); + } + for key in newest_per_place(&mut waiting) { + if result_tx.send(OrbResult::Dropped { key }).is_err() { + return; + } + } + + // Every quick picture before any full one, so a list fills in at once + let next = waiting.iter().position(|job| job.quick).unwrap_or(0); + if next >= waiting.len() { + continue; + } + + let mut job = waiting.remove(next); + let image = match &pool { + Ok(pool) => pool.install(|| job.picture()), + Err(_) => job.picture(), + }; + let full = !job.quick; + if result_tx.send(OrbResult::Picture { key: job.key, full, image }).is_err() { + return; + } + + if let Some(ctx) = &repaint { + ctx.request_repaint(); + } + if !full { + job.quick = false; + waiting.push(job); + } + } + }); + match spawned { + Ok(_) => Some(Worker { jobs, results }), + Err(e) => { + log::warn!("could not start the material orb worker: {e}"); + None + } + } + } +}