diff --git a/ROADMAP.md b/ROADMAP.md index f68a5f80..645044d1 100644 --- a/ROADMAP.md +++ b/ROADMAP.md @@ -12,7 +12,7 @@ end to end today (engine + UI + automation + tests), not what is planned. | Area | Weight | Done | What works | Main gaps | |---|---:|---:|---|---| | Project and files | 8 | 95% | New project from glTF/GLB, FBX (binary and ASCII, 6.x and 7.x), COLLADA, **USD (usda, usdc, usdz)**, **Alembic (Ogawa)**, OBJ, PLY, STL or built-in meshes (auto-unwrap when UVs are missing; a `.gltf`'s buffers and images and a loose USD layer's textures are read from its folder and kept in the project), **project templates** (built-in and saved from a project), `.tcraft` open/save/save as/save a copy, autosave, **asks to save unsaved changes** before quitting or replacing the project (in the browser too, and before the tab closes), recent files, drag and drop, reimport mesh **with strokes preserved on the surface**, **MaterialX import** (`file.importMaterialX`: a `.mtlx` material with `open_pbr_surface`, `standard_surface` or `gltf_pbr` becomes one fill layer with its textures and values), image resources, remove unused resources, textured OBJ (MTL), GLB and **USD** mesh export, browser open/save/download | HDF5 Alembic; Alembic animation (first sample only) | -| Texture sets | 6 | 95% | One set per material, **UDIM / UV tiles** (auto-detected or switched on later with resampling, **a resolution per tile**, one texture per tile at its own size, `$udim` export), list with visibility (show or hide all, invert, **focus** on one set), sizes 128–8192 with resampling, add/remove channels (19 channel types incl. coat, sheen, anisotropy and scattering), height strength, normal format | Filter radii and height slopes of a tile smaller than its atlas block follow the block | +| Texture sets | 6 | 100% | One set per material, **UDIM / UV tiles** (auto-detected or switched on later with resampling, **a resolution per tile** whose filters and height slopes keep their size in UV space, one texture per tile at its own size, `$udim` export), list with visibility (show or hide all, invert, **focus** on one set), sizes 128–8192 with resampling, add/remove channels (19 channel types incl. coat, sheen, anisotropy and scattering), height strength, normal format | — | | Layer stack | 16 | 98% | Paint, fill, folder and **instance** layers; 32 per-channel blend modes and opacities; white/black/painted masks with **mask with height**; generator, fill, levels (with a histogram of its input), invert/threshold, color selection, compare, blur, sharpen and HSL effects on masks and layer content; anchor points; effects **dragged to reorder**, duplicated, and **copied, cut and pasted** across layers, masks and sets (Ctrl+C, Ctrl+X, Ctrl+V, Ctrl+D and Delete act on a selected effect); smart masks; mask view (Alt+click); Alt+click a material channel to keep it alone; duplicate, group, drag to reorder, rename, color tags, copy/cut/paste (also as instance) across sets, flatten, instantiate across sets, save layers as smart materials; **30 library filters** (adjustments incl. histogram scan, range and shift, blur/sharpen/high pass, bevel, glow, edge detect, warps, mosaic, baked lighting, material finishes); **geometry masks** (a layer on chosen mesh parts) | A few niche filters of the reference app's catalog | | Painting tools | 14 | 91% | Paint, eraser, projection with image stencils, polygon fill, **path** and **lasso fill**, smudge, clone, color picker, quick mask, Shift+click lines with preview, 2D view painting; size, flow, stroke opacity, spacing, hardness, angle, follow path, jitters, alignment, angle fade, backface culling, lazy mouse, **Ctrl+drag in a view for size, hardness, flow and angle**, X/Y/Z mirror and **radial symmetry**, pen pressure, procedural and image alphas, **text** in any installed font (as an alpha or a decal), **particle brush** | Pen tilt (not exposed by the windowing layer) | | Materials and assets | 8 | 92% | **MaterialCraft materials** (`.mcmat`, sent to the shelf from MaterialCraft) as fill layers whose graph inputs and presets stay editable, re-cooked at the set's resolution with its baked mesh maps; 63 procedural materials (incl. car paint, velvet, brushed steel, skin, wax, ice, snow, bark), 21 smart materials, 18 smart masks, **67 procedural brush alphas**, **18 brush presets** plus user presets, 23 procedurals, 6 environments plus imported HDR/EXR panoramas, image resources, a user smart material library, a tabbed shelf with search and **drag and drop** onto layers and the viewport | A smaller bundled library than the reference app's | diff --git a/crates/compose/src/display.rs b/crates/compose/src/display.rs index 96294c4a..56a4d4e1 100644 --- a/crates/compose/src/display.rs +++ b/crates/compose/src/display.rs @@ -11,10 +11,12 @@ //! | Emissive | sRGB8 | emissive | | | scattering weight | //! | Lobes | RGBA8 | coat weight | coat roughness | anisotropy level | anisotropy angle | //! | Sheen | sRGB8 | sheen color | | | sheen weight | -//! | Extra | RGBA8 | coat normal x | coat normal y | transmission | | +//! | Extra | RGBA8 | coat normal x | coat normal y | transmission | tile scale | //! //! Extra packs the coat normal's x and y as `128 + 127 × n` (the default normal is exactly 0; -//! z is rebuilt in the shader). +//! z is rebuilt in the shader). Its alpha is the [`Composite::block_scales`] of the texel's UV +//! tile as `32 × log2(1 / scale)` (0 for a tile filling its block): the shader turns height +//! slopes down by it. //! //! Alpha of sRGB formats is linear. Channels a set lacks pack their default values, which switch //! the extra lobes off, so the renderer can keep Lobes and Sheen as 1×1 placeholders until a @@ -44,7 +46,7 @@ pub enum DisplayKind { Lobes, /// sRGB8: sheen color, alpha = sheen weight. Sheen, - /// RGBA8 linear: coat normal x and y, transmission. + /// RGBA8 linear: coat normal x and y, transmission, tile scale. Extra, } @@ -139,12 +141,14 @@ pub fn tile_bytes(comp: &Composite, baked: &BakedMaps, kind: DisplayKind, tx: u3 let (n, transmission) = (get(Channel::CoatNormal), scalar8(Channel::Transmission)); // Signed 8-bit around 128 so the flat normal packs exactly. let snorm = |v: u16| (128.0 + 127.0 * (v as f32 / 65535.0 * 2.0 - 1.0)).round().clamp(0.0, 255.0) as u8; + // A TILE never straddles two atlas blocks. + let scale = (-32.0 * comp.block_scales.at(tx * TILE, ty * TILE).log2()).round().clamp(0.0, 255.0) as u8; for (i, px) in out.chunks_exact_mut(4).enumerate() { for (k, d) in px.iter_mut().take(2).enumerate() { *d = n.and_then(|t| t.get(i * 3 + k)).map_or(128, |v| snorm(*v)); } px[2] = transmission(i); - px[3] = 0; + px[3] = scale; } } DisplayKind::Orm => { @@ -222,6 +226,17 @@ mod tests { assert!((b[3] as i32 - 127).abs() <= 1); } + #[test] + fn extra_alpha_holds_the_tile_scale() { + let mut set = texturecraft_core::TextureSet::new("s", 0, 256); + set.uv_tiles = vec![1001, 1002]; + set.tile_resolutions.insert(1002, 64); + let comp = Composite { block_scales: set.block_scales(), ..Composite::new(&[], 512) }; + let alpha = |tx: u32| tile_bytes(&comp, &BakedMaps::default(), DisplayKind::Extra, tx, 0)[3]; + // Tile 1001 fills its block; 1002 (from texel 256) a quarter of it: 32 × log2(4). + assert_eq!((alpha(0), alpha(3), alpha(4), alpha(7)), (0, 0, 64, 64)); + } + #[test] fn missing_channels_fall_back_to_defaults() { let comp = Composite::new(&[], 64); diff --git a/crates/compose/src/eval.rs b/crates/compose/src/eval.rs index b225e4c3..de26d5bd 100644 --- a/crates/compose/src/eval.rs +++ b/crates/compose/src/eval.rs @@ -7,8 +7,8 @@ use std::collections::{BTreeMap, HashMap}; use rayon::prelude::*; use texturecraft_core::{ - BakedMap, BlendMode, Channel, ChannelKind, CompareOp, Effect, EffectKind, Fill, Filter, Generator, GeneratorKind, HeightMask, Layer, LayerId, LayerKind, - Mask, MaskBackground, NormalFormat, Project, Projection, Source, TextureSet, TileGrid, blend1, blend3, lum, mix3, per_unit, + BakedMap, BlendMode, BlockScales, Channel, ChannelKind, CompareOp, Effect, EffectKind, Fill, Filter, Generator, GeneratorKind, HeightMask, Layer, LayerId, + LayerKind, Mask, MaskBackground, NormalFormat, Project, Projection, Source, TextureSet, TileGrid, blend1, blend3, lum, mix3, per_unit, }; use texturecraft_geom::glam::{Vec2, Vec3}; use texturecraft_geom::{Mesh, NO_TRI, UvGBuffer}; @@ -106,9 +106,8 @@ impl Inputs<'_> { self.project.texture_set(self.ts).ok().and_then(TextureSet::tile_grid) } - /// Texels per UV tile across (the whole width for a classic set): filter radii scale with it. - /// shortcut: a tile smaller than its atlas block (per-tile resolution) uses the block's - /// radii; scale them by `TextureSet::tile_scale` if filters must match across tile sizes. + /// Texels per atlas block across (the whole width for a classic set): filter radii scale + /// with it, and with the tile's share of its block. fn tile_res(&self) -> u32 { self.gbuf.width / self.tile_grid().map_or(1, |g| g.cols.max(1)) } @@ -121,6 +120,8 @@ pub struct Composite { pub resolution: u32, pub height: u32, pub channels: BTreeMap, + /// The set's [`TextureSet::block_scales`]: height slopes on the display follow each tile. + pub block_scales: BlockScales, } impl Composite { @@ -130,7 +131,12 @@ impl Composite { } pub fn with_size(channels: &[Channel], width: u32, height: u32) -> Composite { - Composite { resolution: width, height, channels: channels.iter().map(|c| (*c, TileImage::new(width, height, c.components()))).collect() } + Composite { + resolution: width, + height, + channels: channels.iter().map(|c| (*c, TileImage::new(width, height, c.components()))).collect(), + block_scales: BlockScales::default(), + } } /// Channel value at a texel (the channel default when absent). @@ -612,36 +618,60 @@ fn field(inp: &Inputs, channels: &[Channel], below: &Fields, id: LayerId, job: J Job::Content(ch) if ch.kind() == ChannelKind::Signed => 0.0, _ => 0.5, }; - if !blurs { - let mut data = gather(op, &orig, &cover, comps, (rx0, ry0, w, h), r as f32, inp.tile_res(), opacity); - unpremultiply(&mut data, comps); - return Some(Field { x0: rx0, y0: ry0, w, h, comps, data }); - } - // Weighted so uncovered texels don't bleed in. - let (wu, hu, ru) = (w as usize, h as usize, r as usize); - let mut weights = cover; - blur(&mut weights, wu, hu, ru); - let mut data = orig.clone(); - for p in 0..comps { - let mut vals: Vec = orig.par_chunks(comps).map(|px| px.get(p).copied().unwrap_or(0.0)).collect(); - blur(&mut vals, wu, hu, ru); - data.par_chunks_mut(comps).zip(vals.par_iter()).zip(weights.par_iter()).for_each(|((px, v), wt)| { - // Content is premultiplied, so the mid value is too (coverage itself is kept). - let cov = if comps == 4 { px.get(3).copied().unwrap_or(0.0) } else { 1.0 }; - if *wt > 1e-6 - && let Some(slot) = px.get_mut(p) - { - let (o, blurred) = (*slot, v / wt); - let filtered = match op { - Op::Blur(Some(amount)) => o + amount * (o - blurred), - Op::HighPass if p < 3 => o - blurred + mid * cov, - // Away from 0 by at most the value itself: 0 at the edge, full inside. - Op::Bevel if p < 3 => o.signum() * o.abs().min((2.0 * blurred * o.signum() - o.abs()).max(0.0)), - Op::Glow(amount) if p < 3 => o + amount * blurred, - Op::HighPass | Op::Bevel | Op::Glow(_) => o, - _ => blurred, - }; - *slot = o + (filtered - o) * opacity; + // The filter at the radius of a tile filling `scale` of its atlas block (a smaller tile has + // fewer texels per UV unit, so its filters reach fewer texels). + let filtered = |scale: f32| -> Vec { + let res = ((inp.tile_res() as f32 * scale).round() as u32).max(1); + let r = neighbourhood(effects, res).map_or(r, |(_, radius, _)| radius.round().clamp(1.0, r as f32) as u32); + if !blurs { + return gather(op, &orig, &cover, comps, (rx0, ry0, w, h), r as f32, res, opacity); + } + // Weighted so uncovered texels don't bleed in. + let (wu, hu, ru) = (w as usize, h as usize, r as usize); + let mut weights = cover.clone(); + blur(&mut weights, wu, hu, ru); + let mut data = orig.clone(); + for p in 0..comps { + let mut vals: Vec = orig.par_chunks(comps).map(|px| px.get(p).copied().unwrap_or(0.0)).collect(); + blur(&mut vals, wu, hu, ru); + data.par_chunks_mut(comps).zip(vals.par_iter()).zip(weights.par_iter()).for_each(|((px, v), wt)| { + // Content is premultiplied, so the mid value is too (coverage itself is kept). + let cov = if comps == 4 { px.get(3).copied().unwrap_or(0.0) } else { 1.0 }; + if *wt > 1e-6 + && let Some(slot) = px.get_mut(p) + { + let (o, blurred) = (*slot, v / wt); + let filtered = match op { + Op::Blur(Some(amount)) => o + amount * (o - blurred), + Op::HighPass if p < 3 => o - blurred + mid * cov, + // Away from 0 by at most the value itself: 0 at the edge, full inside. + Op::Bevel if p < 3 => o.signum() * o.abs().min((2.0 * blurred * o.signum() - o.abs()).max(0.0)), + Op::Glow(amount) if p < 3 => o + amount * blurred, + Op::HighPass | Op::Bevel | Op::Glow(_) => o, + _ => blurred, + }; + *slot = o + (filtered - o) * opacity; + } + }); + } + data + }; + // Each block keeps the result at its tile's scale (blocks are TILE aligned). + let scales = inp.project.texture_set(inp.ts).map(TextureSet::block_scales).unwrap_or_default(); + let mut levels: Vec = + (ry0..ry1).step_by(TILE as usize).flat_map(|y| (rx0..rx1).step_by(TILE as usize).map(move |x| (x, y))).map(|(x, y)| scales.at(x, y)).collect(); + levels.sort_by(f32::total_cmp); + levels.dedup(); + let (first, rest) = levels.split_first().map_or((1.0, &[][..]), |(f, r)| (*f, r)); + let mut data = filtered(first); + for &scale in rest { + let other = filtered(scale); + let row = w as usize * comps; + data.par_chunks_mut(row).zip(other.par_chunks(row)).enumerate().for_each(|(y, (dst, src))| { + for (x, (d, s)) in dst.chunks_mut(comps).zip(src.chunks(comps)).enumerate() { + if scales.at(rx0 + x as u32, ry0 + y as u32) == scale { + d.copy_from_slice(s); + } } }); } diff --git a/crates/core/src/lib.rs b/crates/core/src/lib.rs index f5608dff..80f1cafe 100644 --- a/crates/core/src/lib.rs +++ b/crates/core/src/lib.rs @@ -19,8 +19,9 @@ pub use layer::{ LinkPreset, Mask, MaskBackground, MaterialLink, PathShape, Procedural, ProceduralKind, Projection, Source, gradient, hsl_adjust, per_unit, }; pub use project::{ - AoMixing, BakeMatch, BakeSettings, BakedMap, Camera, DepthOfField, DirectionMode, DisplaySettings, FORMAT_VERSION, MAX_RESOLUTION, MIN_RESOLUTION, - NormalFormat, NormalMixing, PositionMode, Project, RayDistribution, RaySettings, SelfOcclusion, TextureSet, TileGrid, ToneMapping, UDIM_RANGE, udim_at, + AoMixing, BakeMatch, BakeSettings, BakedMap, BlockScales, Camera, DepthOfField, DirectionMode, DisplaySettings, FORMAT_VERSION, MAX_RESOLUTION, + MIN_RESOLUTION, NormalFormat, NormalMixing, PositionMode, Project, RayDistribution, RaySettings, SelfOcclusion, TextureSet, TileGrid, ToneMapping, + UDIM_RANGE, udim_at, }; #[derive(Debug, thiserror::Error, Clone, PartialEq)] diff --git a/crates/core/src/project.rs b/crates/core/src/project.rs index 2a8dbf58..c144ec98 100644 --- a/crates/core/src/project.rs +++ b/crates/core/src/project.rs @@ -399,6 +399,27 @@ impl TileGrid { } } +/// The fraction of its atlas block the UV tile of each block fills ([`TextureSet::tile_scale`]): +/// such a tile has fewer texels per UV unit, so filter radii and height slopes shrink with it. +/// Empty (every scale 1) unless a tile is smaller than its block. +#[derive(Clone, Debug, Default, PartialEq)] +pub struct BlockScales { + block: u32, + cols: u32, + scales: Vec, +} + +impl BlockScales { + /// The scale at atlas texel (x, y). + pub fn at(&self, x: u32, y: u32) -> f32 { + let (bx, by) = (x / self.block.max(1), y / self.block.max(1)); + if bx >= self.cols { + return 1.0; + } + self.scales.get(by as usize * self.cols as usize + bx as usize).copied().unwrap_or(1.0) + } +} + fn one() -> f32 { 1.0 } @@ -467,6 +488,13 @@ impl TextureSet { (self.tile_resolution(udim) as f32 / self.block_resolution().max(1) as f32).clamp(1e-3, 1.0) } + /// [`TextureSet::tile_scale`] of every atlas block, to look up by atlas texel. + pub fn block_scales(&self) -> BlockScales { + let Some(g) = self.tile_grid().filter(|_| !self.tile_resolutions.is_empty()) else { return BlockScales::default() }; + let scales = (0..g.rows).flat_map(|by| (0..g.cols).map(move |bx| g.udim(bx, by))).map(|u| self.tile_scale(u)).collect(); + BlockScales { block: self.block_resolution(), cols: g.cols, scales } + } + /// Scale of the tile holding mesh UV `uv` (v down) and that tile's origin corner. fn tile_at(&self, uv: [f32; 2]) -> (f32, [f32; 2]) { (udim_at(uv).map_or(1.0, |u| self.tile_scale(u)), [uv[0].floor(), uv[1].floor()]) diff --git a/crates/engine/src/session.rs b/crates/engine/src/session.rs index e9909635..10a90287 100644 --- a/crates/engine/src/session.rs +++ b/crates/engine/src/session.rs @@ -64,7 +64,7 @@ impl SetCache { gbuf: Arc::new(gbuf), dilation: Arc::new(dilation), covered_tiles: Arc::new(covered), - composite: Composite::with_size(&ts.channel_list(), w, h), + composite: Composite { block_scales: ts.block_scales(), ..Composite::with_size(&ts.channel_list(), w, h) }, dirty: all.clone(), settle: BTreeSet::new(), upload: all, @@ -583,9 +583,9 @@ impl Session { for (i, ts) in sets.iter().enumerate() { match self.caches.get_mut(i) { Some(c) if c.size == ts.size() => { - let want = ts.channel_list(); - if c.composite.channels.keys().copied().collect::>() != want { - c.composite = Composite::with_size(&want, c.size.0, c.size.1); + let (want, scales) = (ts.channel_list(), ts.block_scales()); + if c.composite.channels.keys().copied().collect::>() != want || c.composite.block_scales != scales { + c.composite = Composite { block_scales: scales, ..Composite::with_size(&want, c.size.0, c.size.1) }; c.upload.extend(texturecraft_compose::all_tiles(c.size.0, c.size.1)); c.invalidate_all(); } diff --git a/crates/engine/src/uv_tile_cmds.rs b/crates/engine/src/uv_tile_cmds.rs index acda78db..c6b49a7c 100644 --- a/crates/engine/src/uv_tile_cmds.rs +++ b/crates/engine/src/uv_tile_cmds.rs @@ -305,6 +305,72 @@ mod tests { } } + /// Paint channel `c` of the first layer over every covered texel as `f(u)`, `u` the texel's + /// position across its own UV tile (0..1), so every tile shows the same pattern in UV space. + fn paint_across_tiles(s: &mut Session, c: Channel, f: impl Fn(f32) -> Vec) { + let set = s.doc.project.texture_sets[0].clone(); + let (grid, (w, h)) = (set.tile_grid().unwrap(), set.size()); + let gbuf = s.caches[0].gbuf.clone(); + let img = s.doc.pixels.layer_mut(set.stack[0], c, (w, h)); + for y in 0..h { + for x in 0..w { + if gbuf.covered((y * w + x) as usize) { + let m = set.from_atlas(&grid, [(x as f32 + 0.5) / w as f32, (y as f32 + 0.5) / h as f32]); + img.set(x, y, &f(m[0].rem_euclid(1.0))); + } + } + } + s.touched(); + while s.update() {} + } + + /// A tile at half its block's resolution: (session, its block's left texel, its side). + fn half_res_tile() -> (Session, u32, u32) { + let mut s = udim_session(); + execute(&mut s, "textureSet.tile.resolution", &json!({"tile": 1002, "resolution": 128})).unwrap(); + (s, 256, 128) + } + + #[test] + fn filter_radii_follow_each_tiles_resolution() { + let (mut s, x2, side) = half_res_tile(); + let id = s.doc.project.texture_sets[0].stack[0]; + execute(&mut s, "effect.add.filter", &json!({"layer": id.0, "target": "content", "filter": "blur", "radius": 60})).unwrap(); + // Black on the left half of each tile, white on the right: a blurred edge in the middle. + paint_across_tiles(&mut s, Channel::BaseColor, |u| { + let v = if u < 0.5 { 0 } else { 65535 }; + vec![v, v, v, 65535] + }); + // Texels of the soft edge along a row through the middle of a tile (away from its borders). + let comp = &s.caches[0].composite; + let edge = |x0: u32, side: u32| { + (x0 + side / 8..x0 + side * 7 / 8).filter(|x| (0.05..0.95).contains(&comp.value(Channel::BaseColor, *x, side / 2)[0])).count() as i64 + }; + let (wide, narrow) = (edge(0, 256), edge(x2, side)); + assert!(wide > 8, "the blur softens the edge: {wide}"); + // The same width in UV space: half the texels in the half-resolution tile. + assert!((2 * narrow - wide).abs() <= 4, "{narrow} texels at 128 vs {wide} at 256"); + } + + #[test] + fn height_slopes_follow_each_tiles_resolution() { + let (mut s, _, _) = half_res_tile(); + s.doc.project.texture_sets[0].height_strength = 8.0; + // The same height ramp across each tile. + paint_across_tiles(&mut s, Channel::Height, |u| vec![texturecraft_texel::to_u16_signed(0.5 * u), 65535]); + let opts = crate::file_cmds::export_options(&s, &json!({"preset": "Document channels + Normal + AO", "format": "png"}), "t").unwrap(); + let files = s.export_files(&[0], &opts).unwrap(); + // The red (x) of the exported normal at the middle of a tile. + let tilt = |tile: &str| { + let f = files.iter().find(|f| f.name.ends_with(&format!("_normal.{tile}.png"))).expect("a normal map per tile"); + let img = image::load_from_memory(&f.bytes).unwrap().to_rgb8(); + img.get_pixel(img.width() / 2, img.height() / 2)[0] as i32 + }; + let (full, half) = (tilt("1001"), tilt("1002")); + assert!(full < 110, "the ramp tilts the normal: {full}"); + assert!((full - half).abs() <= 2, "the same slope in UV space: {half} at 128 vs {full} at 256"); + } + #[test] fn convert_to_uv_tiles_and_back() { let mut s = Session::new_project("u", primitives::builtin("udim_plane").unwrap(), "builtin:udim_plane", None, 256).unwrap(); diff --git a/crates/formats/src/export/mod.rs b/crates/formats/src/export/mod.rs index a59fab62..6b1767e4 100644 --- a/crates/formats/src/export/mod.rs +++ b/crates/formats/src/export/mod.rs @@ -18,7 +18,7 @@ use std::io::Cursor; use rayon::prelude::*; use serde::{Deserialize, Serialize}; use texturecraft_compose::{BakedMaps, Composite}; -use texturecraft_core::{AoMixing, BakedMap, Channel, ChannelKind, NormalFormat, NormalMixing, Project, TextureSet}; +use texturecraft_core::{AoMixing, BakedMap, BlockScales, Channel, ChannelKind, NormalFormat, NormalMixing, Project, TextureSet}; use texturecraft_geom::glam::Vec3; use texturecraft_texel::{ColorSpace, DilationMap, linear_to_srgb}; @@ -565,9 +565,11 @@ struct Sampler<'a> { coverage: &'a [bool], /// Composite width. res: u32, - /// Texels per UV tile (`res` for a classic set): the height slope and the Sobel window - /// follow the tile. + /// Texels per atlas block (`res` for a classic set): the height slope and the Sobel window + /// follow the block. tile_res: u32, + /// The share of its block each tile fills: a smaller tile's height slope shrinks with it. + scales: BlockScales, /// Normal convention overriding every normal output. normal_override: Option, project_normal: NormalFormat, @@ -615,7 +617,7 @@ impl Sampler<'_> { }; let gx = (h(1, -1) + 2.0 * h(1, 0) + h(1, 1) - h(-1, -1) - 2.0 * h(-1, 0) - h(-1, 1)) / 8.0; let gy = (h(-1, 1) + 2.0 * h(0, 1) + h(1, 1) - h(-1, -1) - 2.0 * h(0, -1) - h(1, -1)) / 8.0; - let s = self.set.height_strength * self.tile_res as f32 / HEIGHT_SPAN; + let s = self.set.height_strength * self.tile_res as f32 * self.scales.at(x, y) / HEIGHT_SPAN; // Image y points down; OpenGL normals have +Y up the image. Vec3::new(-gx * s, gy * s, 1.0).try_normalize().unwrap_or(Vec3::Z) } @@ -707,6 +709,7 @@ pub fn render_maps(input: &ExportInput, opts: &ExportOptions) -> Result) -> f32 { const PARALLAX_STEPS: i32 = 16; +// The share of its atlas block a UV tile fills (Extra alpha, packed in compose/src/display.rs): +// a smaller tile has fewer texels per UV unit, so its height slopes per texel shrink with it. +fn tile_scale(extra: vec4) -> f32 { + return exp2(-extra.a * 255.0 / 32.0); +} + // Parallax occlusion mapping: march the view ray down through the signed height field (the mesh // surface at height 0; height 1 lies strength/16 UV units above it, the same scale as // height-to-normal) and return the UV where it first goes below the heights. `v_ts`: tangent-space @@ -292,7 +298,7 @@ fn parallax_uv(uv: vec2, v_ts: vec3) -> vec2 { let dx = dpdx(uv); let dy = dpdy(uv); // UV shift per unit of height along the ray (grazing angles capped). - let shift = vec2(v_ts.x, -v_ts.y) / max(v_ts.z, 0.15) * (g.mode.z / 16.0); + let shift = vec2(v_ts.x, -v_ts.y) / max(v_ts.z, 0.15) * (g.mode.z / 16.0) * tile_scale(textureSampleGrad(t_extra, samp, uv, dx, dy)); var prev_z = 1.0; var prev_d = 1.0 - textureSampleGrad(t_height, samp, uv + shift, dx, dy).r; // Heights at the top of the range already hide the ray at entry. @@ -394,7 +400,7 @@ fn shade_mesh(i: VOut, front: bool) -> Shaded { // Tangent-space normal: height gradient (+Y = up the image) combined with the normal channel. // Same slope rule as texture export: strength 1 tilts 45° for a height change of 1 over 1/16 of the width. - let k = g.mode.z * dims.x / 16.0; + let k = g.mode.z * dims.x / 16.0 * tile_scale(extra); let n_height = normalize(vec3(-(hr - hl) * 0.5 * k, (hd - hu) * 0.5 * k, 1.0)); var n_detail = snorm8(nrm_s); n_detail.y *= g.mode.w; diff --git a/crates/render/src/shaders/trace.wgsl b/crates/render/src/shaders/trace.wgsl index d957d722..10fe6853 100644 --- a/crates/render/src/shaders/trace.wgsl +++ b/crates/render/src/shaders/trace.wgsl @@ -291,7 +291,8 @@ fn surface(hit: Hit, o: vec3, d: vec3) -> Surface { let extra = textureLoad(t_extra, texel(layer, 7u, uv, 0, 0), layer, 0); let info = P.sets[layer]; - let k = info.w * info.x / 16.0; + // A UV tile smaller than its atlas block: Extra alpha holds 32 × log2(1 / its share), as in mesh.wgsl. + let k = info.w * info.x / 16.0 * exp2(-extra.a * 255.0 / 32.0); var n_height = vec3(0.0, 0.0, 1.0); if (k != 0.0) { let hx = textureLoad(t_height, texel(layer, 3u, uv, 1, 0), layer, 0).r - textureLoad(t_height, texel(layer, 3u, uv, -1, 0), layer, 0).r; diff --git a/crates/render/src/trace.rs b/crates/render/src/trace.rs index 1a592a49..a823a031 100644 --- a/crates/render/src/trace.rs +++ b/crates/render/src/trace.rs @@ -536,15 +536,22 @@ fn surface(scene: &TraceScene, tri: u32, u: f32, v: f32, o: Vec3, d: Vec3, t: f3 let sign = if tan[0].w < 0.0 { -1.0 } else { 1.0 }; let set = scene.tri_set.get(tri as usize).and_then(|s| scene.sets.get(*s)); + // The composite texel at offset (dx, dy) from the hit. + let texel = |s: &TraceSet, dx: i32, dy: i32| { + let (w, h) = (s.composite.resolution.max(1) as i32, s.composite.height.max(1) as i32); + (((uv.x * w as f32).floor() as i32 + dx).rem_euclid(w) as u32, ((uv.y * h as f32).floor() as i32 + dy).rem_euclid(h) as u32) + }; let ch = |c: Channel, dx: i32, dy: i32| -> [f32; 3] { let Some(s) = set else { return c.default_value() }; - let (w, h) = (s.composite.resolution.max(1) as i32, s.composite.height.max(1) as i32); - let x = ((uv.x * w as f32).floor() as i32 + dx).rem_euclid(w) as u32; - let y = ((uv.y * h as f32).floor() as i32 + dy).rem_euclid(h) as u32; + let (x, y) = texel(s, dx, dy); s.composite.value(c, x, y) }; let base = Vec3::from(ch(Channel::BaseColor, 0, 0)); - let k = set.map_or(0.0, |s| s.height_strength * s.composite.resolution as f32 / 16.0); + // A UV tile smaller than its atlas block has fewer texels per UV unit: slopes per texel shrink. + let k = set.map_or(0.0, |s| { + let (x, y) = texel(s, 0, 0); + s.height_strength * s.composite.resolution as f32 / 16.0 * s.composite.block_scales.at(x, y) + }); let n_height = if k != 0.0 { let h = |dx, dy| ch(Channel::Height, dx, dy)[0]; Vec3::new(-(h(1, 0) - h(-1, 0)) * 0.5 * k, (h(0, 1) - h(0, -1)) * 0.5 * k, 1.0).normalize_or(Vec3::Z) diff --git a/docs/features.md b/docs/features.md index 116a0622..464bda72 100644 --- a/docs/features.md +++ b/docs/features.md @@ -79,8 +79,9 @@ Everything TextureCraft does today, by area. What's still missing is in [`ROADMA OBJ, PLY and STL, or a built-in mesh; UVs are generated when a mesh has none. A `.gltf`'s buffers and images and a loose USD layer's textures are read from its folder and kept in the project. Reimport a changed mesh and your painted strokes stay on the surface. -- **UDIM / UV tiles:** detected on import or switched on later, with a resolution per tile and one - texture per tile on export (`$udim`). +- **UDIM / UV tiles:** detected on import or switched on later, with a resolution per tile (blurs, + other filters and height-to-normal slopes keep their size in UV space at any tile resolution) + and one texture per tile on export (`$udim`). - **Texture sets** from 128 to 8192 px per material, resampled when you change them, with 21 channel types to add or remove. Show, hide or invert them all at once, or **focus** on the active one. The project's **normal map format** (OpenGL or DirectX, in Texture Set Settings)