Merge authoritative bake settings and UV tile controls

This commit is contained in:
chasse20 committed 2026-11-06 00:17:28 -05:00
commit a13e96d8b5
57 files changed
+1767 -323

No files matched your search

+1 -1
View File
@@ -72,7 +72,7 @@ fn join(dir: &str, name: &str) -> String {
impl Headless {
pub fn new(session: Session, fs: Filesystem) -> Headless {
// Bakes run here (CLI, MCP) cast their rays on the GPU when there is one.
texturecraft_engine::bake_cmds::install_gpu_tracer(std::sync::Arc::new(texturecraft_render::gpu_bake::GpuBaker::new()));
texturecraft_engine::bake::install_gpu_tracer(std::sync::Arc::new(texturecraft_render::gpu_bake::GpuBaker::new()));
Headless { session, fs, gpu: None }
}
+1 -1
View File
@@ -72,7 +72,7 @@ impl Gpu {
// The aux texture behind the mesh-map and mask views (rebuilt every render).
let res = texturecraft_render::aux_size(cache.size);
let aux = match s.view {
ViewMode::MeshMap(m) => Some(texturecraft_render::mesh_maps::mesh_map_rgba(s.doc.baked.get(&ts), m, res)),
ViewMode::MeshMap(m) => Some(texturecraft_render::mesh_maps::mesh_map_rgba(s.doc.baked.get(&ts), m, res, cache.size, &comp.block_scales)),
ViewMode::Mask(id) if s.doc.project.locate(id).is_some_and(|(t, _, _)| t == ts) => s.mask_view_rgba(id, res),
_ => None,
};
+31 -5
View File
@@ -143,14 +143,20 @@ fn alloc<T: Clone>(count: usize, value: T) -> Result<Vec<T>, BakeError> {
}
pub fn bake(request: &BakeRequest, progress: &Progress) -> Result<BakeOutput, BakeError> {
bake_in_strips(request, progress, STRIP_TEXELS, &CpuTracer)
bake_in_strips(request, progress, STRIP_TEXELS, &CpuTracer, &[])
}
/// Retry on the CPU if the supplied tracer fails
pub fn bake_on(request: &BakeRequest, progress: &Progress, tracer: &dyn Tracer) -> Result<BakeOutput, BakeError> {
match bake_in_strips(request, progress, STRIP_TEXELS, tracer) {
bake_tiles(request, progress, &[], Some(tracer))
}
/// Excluded atlas blocks produce no samples; their geometry still participates in ray tracing
pub fn bake_tiles(request: &BakeRequest, progress: &Progress, excluded_tiles: &[(u32, u32)], tracer: Option<&dyn Tracer>) -> Result<BakeOutput, BakeError> {
let tracer = tracer.unwrap_or(&CpuTracer);
match bake_in_strips(request, progress, STRIP_TEXELS, tracer, excluded_tiles) {
Err(BakeError::Tracer(error)) => {
let mut output = bake(request, progress)?;
let mut output = bake_in_strips(request, progress, STRIP_TEXELS, &CpuTracer, excluded_tiles)?;
output.tracer = format!("CPU ({} unavailable: {error})", tracer.name());
Ok(output)
}
@@ -160,8 +166,18 @@ pub fn bake_on(request: &BakeRequest, progress: &Progress, tracer: &dyn Tracer)
type OutRow<'a> = Vec<&'a mut [f32]>;
fn bake_in_strips(request: &BakeRequest, progress: &Progress, strip_texels: usize, tracer: &dyn Tracer) -> Result<BakeOutput, BakeError> {
fn bake_in_strips(
request: &BakeRequest,
progress: &Progress,
strip_texels: usize,
tracer: &dyn Tracer,
excluded_tiles: &[(u32, u32)],
) -> Result<BakeOutput, BakeError> {
validate(request)?;
if excluded_tiles.iter().any(|(column, row)| *column >= request.tiles.0 || *row >= request.tiles.1) {
return Err(BakeError::Invalid("excluded UV tile lies outside the bake atlas".into()));
}
let settings = request.settings;
let (tile_width, tile_height) = settings.common.output_size();
let tile_size = (tile_width as usize, tile_height as usize);
@@ -196,7 +212,17 @@ fn bake_in_strips(request: &BakeRequest, progress: &Progress, strip_texels: usiz
let (sample_start_y, strip_sample_height) = (strip_start * samples_per_axis, rows * samples_per_axis);
strip_mesh.uvs =
request.mesh.uvs.iter().map(|uv| Vec2::new(uv.x, (uv.y * sample_height as f32 - sample_start_y as f32) / strip_sample_height as f32)).collect();
let gbuffer = UvGBuffer::new(&strip_mesh, request.material, sample_width as u32, strip_sample_height as u32);
let mut gbuffer = UvGBuffer::new(&strip_mesh, request.material, sample_width as u32, strip_sample_height as u32);
for &(column, row) in excluded_tiles {
let start_x = column as usize * tile_size.0 * samples_per_axis;
let start_y = row as usize * tile_size.1 * samples_per_axis;
let end_y = (start_y + tile_size.1 * samples_per_axis).min(sample_start_y + strip_sample_height);
for sample_y in start_y.max(sample_start_y)..end_y {
let first = (sample_y - sample_start_y) * sample_width + start_x;
gbuffer.tri.get_mut(first..first + tile_size.0 * samples_per_axis).ok_or_else(strip_error)?.fill(NO_TRI);
}
}
let coverage_rows = covered.get_mut(strip_start * width..(strip_start + rows) * width).ok_or_else(strip_error)?;
coverage_rows.par_chunks_mut(width).enumerate().for_each(|(row_index, row)| {
for (x, covered_pixel) in row.iter_mut().enumerate() {
+54
View File
@@ -0,0 +1,54 @@
use super::{Broken, settings};
use crate::tracing::CpuTracer;
use crate::{BakeRequest, Progress, bake, bake_in_strips, bake_tiles};
use texturecraft_core::{BakeAntialiasing, BakedMap, TileGrid};
use texturecraft_geom::glam::Vec2;
use texturecraft_geom::{Bvh, primitives};
#[test]
fn excluded_tiles_match_across_strips_antialiasing_and_cpu_fallback() {
let mut mesh = primitives::udim_plane();
let grid = TileGrid::of(&[1001, 1002]).unwrap();
mesh.map_material_uvs(0, |uv| Vec2::from(grid.to_atlas(uv.to_array())));
let bvh = Bvh::new(&mesh);
let mut settings = settings(32, &[BakedMap::Position, BakedMap::AmbientOcclusion]);
settings.maps.ao.parameters.rays.rays = 4;
settings.common.antialiasing = BakeAntialiasing::Subsampling2x2;
settings.common.dilation = 4;
settings.common.apply_diffusion = true;
let request = BakeRequest {
mesh: &mesh,
bvh: &bvh,
material: 0,
low_base_color: &[],
settings: &settings,
high: None,
cage: None,
skew: None,
cage_paint: None,
tiles: (2, 1),
};
let full = bake(&request, &Progress::new()).unwrap();
for excluded in [[(0, 0)], [(1, 0)]] {
let partial = bake_tiles(&request, &Progress::new(), &excluded, None).unwrap();
let strips = bake_in_strips(&request, &Progress::new(), 512, &CpuTracer, &excluded).unwrap();
let fallback = bake_tiles(&request, &Progress::new(), &excluded, Some(&Broken)).unwrap();
assert_eq!(strips.maps, partial.maps);
assert_eq!(fallback.maps, partial.maps);
assert!(fallback.tracer.contains("Broken unavailable"));
for map in [BakedMap::Position, BakedMap::AmbientOcclusion] {
let components = map.components();
for (index, pixel) in partial.maps[&map].chunks_exact(components).enumerate() {
if index % 64 / 32 == excluded[0].0 as usize {
assert_eq!(pixel, &map.neutral()[..components]);
} else {
assert_eq!(pixel, &full.maps[&map][index * components..(index + 1) * components]);
}
}
}
}
assert!(bake_tiles(&request, &Progress::new(), &[(2, 0)], None).is_err());
assert!(bake_tiles(&request, &Progress::new(), &[(0, u32::MAX)], None).is_err());
}
+4 -1
View File
@@ -17,6 +17,9 @@ use super::*;
#[path = "test/setting.rs"]
mod setting;
#[path = "test/tile_selection.rs"]
mod tile_selection;
fn settings(resolution: u32, maps: &[BakedMap]) -> BakeSettings {
with_rays(
{
@@ -307,7 +310,7 @@ fn strips_match_a_single_pass() {
tiles: (1, 1),
};
let whole = bake(&req, &Progress::new()).unwrap();
let strips = bake_in_strips(&req, &Progress::new(), 128 * 2, &CpuTracer).unwrap();
let strips = bake_in_strips(&req, &Progress::new(), 128 * 2, &CpuTracer, &[]).unwrap();
for (map, a) in &whole.maps {
let b = &strips.maps[map];
let off = a.iter().zip(b).filter(|(a, b)| (*a - *b).abs() > 1e-3).count();
+53
View File
@@ -0,0 +1,53 @@
use std::collections::BTreeMap;
use texturecraft_core::{BakedMap, BlockScales};
/// Dense mesh maps with `components()` floats per texel in row-major order
/// Each UV tile fills its block independently of the working resolution
/// The width is `resolution`; height follows the output size and UV tile grid
#[derive(Clone, Debug, Default, PartialEq)]
pub struct BakedMaps {
/// Width in texels
pub resolution: u32,
pub maps: BTreeMap<BakedMap, std::sync::Arc<Vec<f32>>>,
}
impl BakedMaps {
/// Sample a working atlas texel without resampling the stored bake
pub fn sample_working(&self, map: BakedMap, x: u32, y: u32, size: (u32, u32), scales: &BlockScales) -> Option<[f32; 3]> {
let uv = [(x as f32 + 0.5) / size.0.max(1) as f32, (y as f32 + 0.5) / size.1.max(1) as f32];
self.sample_uv(map, scales.bake_uv(uv, size)?)
}
/// Nearest sample in the uniform bake atlas
pub fn sample_uv(&self, map: BakedMap, uv: [f32; 2]) -> Option<[f32; 3]> {
if uv.iter().any(|value| !value.is_finite()) {
return None;
}
let size = (self.resolution, self.height(map));
self.sample(map, (uv[0] * size.0 as f32) as u32, (uv[1] * size.1 as f32) as u32, size)
}
/// Height in texels of map `m`, from its length
pub fn height(&self, m: BakedMap) -> u32 {
self.maps.get(&m).map_or(0, |d| (d.len() / (self.resolution.max(1) as usize * m.components())) as u32)
}
/// Sample the corresponding texel of an image with the supplied output size
pub fn sample(&self, map: BakedMap, x: u32, y: u32, output_size: (u32, u32)) -> Option<[f32; 3]> {
let data = self.maps.get(&map)?;
let width = u64::from(self.resolution.max(1));
let height = u64::from(self.height(map).max(1));
let sample_x = (u64::from(x) * width / u64::from(output_size.0.max(1))).min(width - 1);
let sample_y = (u64::from(y) * height / u64::from(output_size.1.max(1))).min(height - 1);
let component_count = map.components();
let offset = ((sample_y * width + sample_x) as usize).checked_mul(component_count)?;
let texel = data.get(offset..offset.checked_add(component_count)?)?;
Some(if component_count == 3 { [texel[0], texel[1], texel[2]] } else { [texel[0]; 3] })
}
pub fn scalar(&self, m: BakedMap, x: u32, y: u32, size: (u32, u32)) -> Option<f32> {
self.sample(m, x, y, size).map(|v| v[0])
}
}
+2 -2
View File
@@ -159,7 +159,7 @@ pub fn tile_bytes(comp: &Composite, baked: &BakedMaps, kind: DisplayKind, tx: u3
if gloss { (get(Channel::Glossiness), default16(Channel::Glossiness)) } else { (get(Channel::Roughness), default16(Channel::Roughness)) };
for i in 0..TILE_AREA {
let (x, y) = (tx * TILE + (i as u32 % TILE), ty * TILE + (i as u32 / TILE));
let baked_ao = baked.scalar(BakedMap::AmbientOcclusion, x, y, (res, comp.height)).unwrap_or(1.0);
let baked_ao = baked.sample_working(BakedMap::AmbientOcclusion, x, y, (res, comp.height), &comp.block_scales).map_or(1.0, |value| value[0]);
let ch_ao = ao.and_then(|a| a.get(i)).map(|v| *v as f32 / 65535.0).unwrap_or(1.0);
let px = &mut out[i * 4..i * 4 + 4];
px[0] = ((baked_ao * ch_ao).clamp(0.0, 1.0) * 255.0 + 0.5) as u8;
@@ -175,7 +175,7 @@ pub fn tile_bytes(comp: &Composite, baked: &BakedMaps, kind: DisplayKind, tx: u3
let px = &mut out[i * 4..i * 4 + 4];
// The baked normal is the base the painted normal details sit on (as in export).
let (x, y) = (tx * TILE + (i as u32 % TILE), ty * TILE + (i as u32 / TILE));
let base = baked.sample(BakedMap::Normal, x, y, (res, comp.height));
let base = baked.sample_working(BakedMap::Normal, x, y, (res, comp.height), &comp.block_scales);
match (n, base) {
(Some(t), None) => {
for (k, d) in px.iter_mut().take(3).enumerate() {
+13 -4
View File
@@ -93,6 +93,7 @@ pub struct Inputs<'a> {
pub gbuf: &'a UvGBuffer,
pub pixels: &'a PixelStore,
pub baked: &'a BakedMaps,
pub block_scales: BlockScales,
pub preview: Option<&'a StrokePreview>,
/// Imported image resources (fill sources).
pub images: &'a ImageStore,
@@ -1043,7 +1044,11 @@ impl<'a, 'b> Texel<'a, 'b> {
}
fn baked(&self, m: BakedMap) -> Option<f32> {
self.inp.baked.scalar(m, self.x, self.y, (self.res, self.inp.gbuf.height))
self.baked_color(m).map(|value| value[0])
}
fn baked_color(&self, map: BakedMap) -> Option<[f32; 3]> {
self.inp.baked.sample_working(map, self.x, self.y, (self.res, self.inp.gbuf.height), &self.inp.block_scales)
}
/// Where projection `proj` samples this texel: the texel's coordinates, or for a decal its
@@ -1179,7 +1184,7 @@ impl<'a, 'b> Texel<'a, 'b> {
v += (val - v) * o;
}
EffectKind::ColorSelection { colors, tolerance } => {
let id = self.inp.baked.sample(BakedMap::Id, self.x, self.y, (self.res, self.inp.gbuf.height));
let id = self.baked_color(BakedMap::Id);
let hit = id.is_some_and(|c| colors.iter().any(|k| (k[0] - c[0]).abs().max((k[1] - c[1]).abs()).max((k[2] - c[2]).abs()) <= *tolerance));
let val = if hit { 1.0 } else { 0.0 };
v += (blend1(e.blend, v, val) - v) * o;
@@ -1981,7 +1986,7 @@ pub fn effect_histogram(inp: &Inputs, effect: LayerId, channel: Channel, bins: u
false
}
};
let cut_inp = Inputs { project: &cut, preview: None, ..*inp };
let cut_inp = Inputs { project: &cut, preview: None, block_scales: inp.block_scales.clone(), ..*inp };
let channels = cut.texture_set(inp.ts).map(|t| t.channel_list()).unwrap_or_default();
let tiles = histogram_tiles(inp.gbuf.width, inp.gbuf.height);
// A field covers the bounding box of the tiles it is built for, which for a scattered sample
@@ -2058,7 +2063,7 @@ pub fn flatten_layer(inp: &Inputs, id: LayerId, tiles: &[(u32, u32)]) -> Option<
if let Some(l) = solo.layers.get_mut(&id) {
l.visible = true;
}
let solo_inp = Inputs { project: &solo, preview: None, ..*inp };
let solo_inp = Inputs { project: &solo, preview: None, block_scales: inp.block_scales.clone(), ..*inp };
let fields = neighbourhood_fields(&solo_inp, &channels, tiles);
let out: Vec<Vec<FlatTile>> = tiles
.par_iter()
@@ -2135,6 +2140,7 @@ mod tests {
gbuf: &f.gbuf,
pixels: &f.pixels,
baked: &f.baked,
block_scales: f.project.texture_sets[0].block_scales(),
preview,
images: &images,
bounds: f.mesh.bounds(),
@@ -2252,6 +2258,7 @@ mod tests {
gbuf: &fixture.gbuf,
pixels: &fixture.pixels,
baked: &fixture.baked,
block_scales: fixture.project.texture_sets[0].block_scales(),
preview: None,
images: &images,
bounds: fixture.mesh.bounds(),
@@ -2606,6 +2613,7 @@ soft {soft:?}"
gbuf: &f.gbuf,
pixels: &f.pixels,
baked: &f.baked,
block_scales: f.project.texture_sets[0].block_scales(),
preview: None,
images: &images,
bounds: f.mesh.bounds(),
@@ -2667,6 +2675,7 @@ soft {soft:?}"
gbuf: &f.gbuf,
pixels: &f.pixels,
baked: &f.baked,
block_scales: f.project.texture_sets[0].block_scales(),
preview: None,
images: &images,
bounds: f.mesh.bounds(),
+1
View File
@@ -7,6 +7,7 @@
#![forbid(unsafe_code)]
#![deny(clippy::unwrap_used, clippy::expect_used, clippy::panic, clippy::unimplemented, clippy::todo, clippy::unreachable)]
mod baked_maps;
pub mod below;
pub mod display;
pub mod eval;
+3 -34
View File
@@ -1,9 +1,9 @@
//! Pixel data owned by a document: painted layer channels, painted mask effects and baked mesh
//! maps. Everything is copy-on-write, so cloning the store for undo is cheap.
use std::collections::{BTreeMap, HashMap};
use std::collections::HashMap;
use texturecraft_core::{BakedMap, Channel, ChannelKind, LayerId};
use texturecraft_core::{Channel, ChannelKind, LayerId};
use texturecraft_texel::{TileImage, from_u16, from_u16_signed};
/// Painted data of one paint layer channel: premultiplied value(s) plus coverage, u16 per
@@ -56,38 +56,7 @@ pub fn decode(kind: ChannelKind, v: u16) -> f32 {
if kind == ChannelKind::Signed { from_u16_signed(v) } else { from_u16(v) }
}
/// Baked mesh maps of one texture set (dense, row-major, `components()` floats per texel). The
/// width is `resolution`; height follows the output size and UV tile grid
#[derive(Clone, Debug, Default, PartialEq)]
pub struct BakedMaps {
/// Width in texels.
pub resolution: u32,
pub maps: BTreeMap<BakedMap, std::sync::Arc<Vec<f32>>>,
}
impl BakedMaps {
/// Height in texels of map `m` (from its length).
pub fn height(&self, m: BakedMap) -> u32 {
self.maps.get(&m).map_or(0, |d| (d.len() / (self.resolution.max(1) as usize * m.components())) as u32)
}
/// Sample the corresponding texel of an image with the supplied output size
pub fn sample(&self, map: BakedMap, x: u32, y: u32, output_size: (u32, u32)) -> Option<[f32; 3]> {
let data = self.maps.get(&map)?;
let width = u64::from(self.resolution.max(1));
let height = u64::from(self.height(map).max(1));
let sample_x = (u64::from(x) * width / u64::from(output_size.0.max(1))).min(width - 1);
let sample_y = (u64::from(y) * height / u64::from(output_size.1.max(1))).min(height - 1);
let component_count = map.components();
let offset = ((sample_y * width + sample_x) as usize).checked_mul(component_count)?;
let texel = data.get(offset..offset.checked_add(component_count)?)?;
Some(if component_count == 3 { [texel[0], texel[1], texel[2]] } else { [texel[0]; 3] })
}
pub fn scalar(&self, m: BakedMap, x: u32, y: u32, size: (u32, u32)) -> Option<f32> {
self.sample(m, x, y, size).map(|v| v[0])
}
}
pub use crate::baked_maps::BakedMaps;
/// A decoded image resource sampled by fills (values in the file's encoding; see `srgb`).
#[derive(Clone, Debug, PartialEq)]
+12 -1
View File
@@ -90,7 +90,18 @@ fn heavy_stack(f: &mut Fixture) -> LayerId {
}
fn inputs<'a>(f: &'a Fixture, ts: usize, images: &'a texturecraft_compose::ImageStore, baked: &'a texturecraft_compose::BakedMaps) -> Inputs<'a> {
Inputs { project: &f.project, ts, mesh: &f.mesh, gbuf: &f.gbuf, pixels: &f.pixels, baked, preview: None, images, bounds: f.mesh.bounds() }
Inputs {
project: &f.project,
ts,
mesh: &f.mesh,
gbuf: &f.gbuf,
pixels: &f.pixels,
baked,
block_scales: f.project.texture_sets[ts].block_scales(),
preview: None,
images,
bounds: f.mesh.bounds(),
}
}
fn run(f: &Fixture, ts: usize, tiles: &[(u32, u32)], below: Option<&mut BelowCache>) -> Composite {
+43
View File
@@ -0,0 +1,43 @@
/// Per-block UV tile scale for working-to-bake coordinates, filter radii, and height slopes
/// Empty when every tile fills its block; see [`crate::TextureSet::tile_scale`]
#[derive(Clone, Debug, Default, PartialEq)]
pub struct BlockScales {
pub(crate) block: u32,
pub(crate) cols: u32,
pub(crate) scales: Vec<f32>,
}
impl BlockScales {
/// Working atlas UV → uniform bake atlas UV, excluding unused portions of tile blocks
pub fn bake_uv(&self, uv: [f32; 2], working_size: (u32, u32)) -> Option<[f32; 2]> {
if working_size.0 == 0 || working_size.1 == 0 || uv.iter().any(|value| !value.is_finite() || !(0.0..1.0).contains(value)) {
return None;
}
if self.scales.is_empty() {
return Some(uv);
}
let block = self.block.max(1) as f32;
let position = [uv[0] * working_size.0 as f32 / block, uv[1] * working_size.1 as f32 / block];
let origin = position.map(f32::floor);
let scale = self.at((origin[0] * block) as u32, (origin[1] * block) as u32);
let local = [(position[0] - origin[0]) / scale, (position[1] - origin[1]) / scale];
if local.iter().any(|value| !value.is_finite() || !(0.0..1.0).contains(value)) {
return None;
}
Some([(origin[0] + local[0]) * block / working_size.0.max(1) as f32, (origin[1] + local[1]) * block / working_size.1.max(1) as f32])
}
/// 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;
}
let index = (by as usize).checked_mul(self.cols as usize).and_then(|index| index.checked_add(bx as usize));
index.and_then(|index| self.scales.get(index)).copied().unwrap_or(1.0)
}
}
+1
View File
@@ -9,6 +9,7 @@
pub mod bake;
pub mod blend;
mod block_scales;
pub mod channel;
pub mod layer;
pub mod project;
+10 -21
View File
@@ -6,7 +6,7 @@ use serde::{Deserialize, Serialize};
use crate::{BakeSettings, BakedMap, Channel, ChannelFormat, CoreError, Effect, Layer, LayerId, LayerKind, Result};
pub const FORMAT_VERSION: u32 = 1;
pub const FORMAT_VERSION: u32 = 2;
/// Maximum group nesting (also bounds recursion over hostile project files)
pub const MAX_DEPTH: usize = 16;
@@ -63,6 +63,9 @@ pub struct TextureSet {
/// [`TileGrid`], [`TextureSet::block_resolution`] texels square.
#[serde(default, skip_serializing_if = "Vec::is_empty")]
pub uv_tiles: Vec<u32>,
/// UV tiles excluded from baking; missing entries stay included
#[serde(default, skip_serializing_if = "BTreeSet::is_empty")]
pub bake_excluded_tiles: BTreeSet<u32>,
/// Per-tile resolutions overriding `resolution` (UDIM → texels per side). A tile smaller
/// than the atlas block fills the block's top-left corner (see [`TextureSet::to_atlas`]).
#[serde(default, skip_serializing_if = "BTreeMap::is_empty")]
@@ -132,26 +135,7 @@ 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<f32>,
}
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)
}
}
pub use crate::block_scales::BlockScales;
fn one() -> f32 {
1.0
@@ -176,6 +160,7 @@ impl TextureSet {
baked: BTreeSet::new(),
visible: true,
uv_tiles: Vec::new(),
bake_excluded_tiles: BTreeSet::new(),
tile_resolutions: BTreeMap::new(),
}
}
@@ -185,6 +170,10 @@ impl TextureSet {
TileGrid::of(&self.uv_tiles)
}
pub fn has_enabled_bake_tiles(&self) -> bool {
self.uv_tiles.is_empty() || self.uv_tiles.iter().any(|tile| !self.bake_excluded_tiles.contains(tile))
}
/// Height strength for slopes measured over the whole texture width (the viewport shader,
/// the path tracer): a UV tile atlas is one tile per column wide.
pub fn atlas_height_strength(&self) -> f32 {
+9 -6
View File
@@ -1,7 +1,8 @@
use super::MergedHigh;
use crate::{EngineError, Result};
use std::sync::Arc;
use texturecraft_bake::{BakeOutput, BakePaintMap, BakeRequest, HighPoly, Progress, bake, bake_on, tracing::Tracer};
use texturecraft_bake::{BakeOutput, BakePaintMap, BakeRequest, HighPoly, Progress, bake_tiles, tracing::Tracer};
use texturecraft_compose::BakedMaps;
use texturecraft_core::BakeSettings;
use texturecraft_geom::{Bvh, Mesh};
@@ -20,6 +21,9 @@ pub struct BakeTask {
pub cage_paint: Option<Arc<BakePaintMap>>,
/// UV tile grid (columns, rows) of the set; (1, 1) without UV tiles.
pub tiles: (u32, u32),
/// Snapshot of tile selection and pixels to retain while the worker runs
pub excluded_tiles: Vec<(u32, u32)>,
pub previous_maps: BakedMaps,
/// The GPU ray tracer, if installed and not turned off (`bake.run {cpu: true}`).
pub tracer: Option<Arc<dyn Tracer>>,
}
@@ -40,10 +44,9 @@ impl BakeTask {
cage_paint: self.cage_paint.as_deref(),
tiles: self.tiles,
};
match &self.tracer {
Some(tracer) => bake_on(&request, progress, tracer.as_ref()),
None => bake(&request, progress),
}
.map_err(|e| EngineError::Other(format!("bake failed: {e}")))
let mut output = bake_tiles(&request, progress, &self.excluded_tiles, self.tracer.as_deref())
.map_err(|error| EngineError::Other(format!("bake failed: {error}")))?;
super::preserve_tiles::restore(&mut output, &self.previous_maps, &self.excluded_tiles, self.tiles)?;
Ok(output)
}
}
+46
View File
@@ -0,0 +1,46 @@
use std::sync::Arc;
use rayon::prelude::*;
use texturecraft_bake::BakePaintMap;
use texturecraft_core::TextureSet;
use texturecraft_geom::glam::Vec2;
use crate::{EngineError, Result};
/// Correction paint stays in working coordinates; the worker reads a uniform bake atlas
pub(super) fn paint_for_bake(painted: &Arc<BakePaintMap>, set: &TextureSet) -> Result<Arc<BakePaintMap>> {
let Some(grid) = set.tile_grid().filter(|_| !set.tile_resolutions.is_empty()) else {
return Ok(painted.clone());
};
painted.validate().map_err(|error| EngineError::Other(error.to_string()))?;
let (width, height) = (painted.width, painted.height);
let mut values = vec![0.0; painted.values.len()];
values.par_chunks_mut(width as usize).enumerate().for_each(|(y, row)| {
for (x, value) in row.iter_mut().enumerate() {
let uv = grid.from_atlas([(x as f32 + 0.5) / width as f32, (y as f32 + 0.5) / height as f32]);
*value = painted.sample(Vec2::from_array(set.to_atlas(&grid, uv, uv)));
}
});
Ok(Arc::new(BakePaintMap { width, height, values }))
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn correction_paint_follows_the_same_surface_in_bake_coordinates() {
let mut set = TextureSet::new("Tiles", 0, 256);
set.uv_tiles = vec![1001, 1002];
set.tile_resolutions.insert(1002, 128);
let mut paint = BakePaintMap::constant(0.0).resized(128, 64).unwrap();
paint.paint(&[Vec2::new(0.625, 0.25)], 0.05, 1.0, 1.0, 1.0).unwrap();
let paint = Arc::new(paint);
let baked = paint_for_bake(&paint, &set).unwrap();
assert!(paint.sample(Vec2::new(0.625, 0.25)) > 0.99);
assert!(baked.sample(Vec2::new(0.75, 0.5)) > 0.99);
assert_eq!(baked.sample(Vec2::new(0.25, 0.5)), 0.0);
assert_eq!(paint.sample(Vec2::new(0.75, 0.5)), 0.0);
}
}
@@ -2,6 +2,8 @@
//! high-definition mesh list, the cage, and running a bake. Bakes cast their rays on the GPU
//! tracer the app installs ([`install_gpu_tracer`]) and on the CPU otherwise.
use super::model_patch;
use std::collections::BTreeMap;
use std::sync::{Arc, OnceLock};
use texturecraft_core::BakePaintTarget;
@@ -17,7 +19,7 @@ use texturecraft_core::{
use crate::commands::{CommandSpec, always, bad, boolp, f32p, strp, u64p};
use crate::{EngineError, Result, Session, cmd};
pub fn specs() -> Vec<CommandSpec> {
pub(super) fn specs() -> Vec<CommandSpec> {
vec![
cmd!(
"bake.run",
@@ -33,7 +35,7 @@ pub fn specs() -> Vec<CommandSpec> {
"Bake settings",
[],
None,
"{ts?: index|[indices]|\"all\"|\"selected\" (default: the active set), model?: complete nested BakeSettings (named enum values), preserveEnabled?: keep each texture set enabled flag when replacing the model, resolution?, antialiasing?: 1|2|4|8, dilation?, ao?: {rays?, maxDistance?, spread?: degrees (180 = hemisphere), distribution?: cosine|uniform, ignoreBackface?: never|always|byMeshName, selfOcclusion?: always|sameMeshName}, thickness?: {rays?, maxDistance?, spread?, distribution?}, bentNormal?: {rays?, maxDistance?, spread?, distribution?}, rays?, maxDistance? (all three ray maps), curvatureMethod?: normalMap|mesh, positionMode?: boundingBox|boundingSphere|none, maps?: [ids], enabled?, useLowAsHigh?, maxFrontal?, maxRear?, averageNormals?, lowSuffix?, highSuffix?}",
"{ts?: index|[indices]|\"all\"|\"selected\" (default: the active set), model?: complete nested BakeSettings (named enum values), preserveEnabled?: keep each texture set enabled flag when replacing the model, patch?: nested BakeSettings fields to update after model (omitted fields stay unchanged, null clears optional fields), resolution?, antialiasing?: 1|2|4|8, dilation?, ao?: {rays?, maxDistance?, spread?: degrees (180 = hemisphere), distribution?: cosine|uniform, ignoreBackface?: never|always|byMeshName, selfOcclusion?: always|sameMeshName}, thickness?: {rays?, maxDistance?, spread?, distribution?}, bentNormal?: {rays?, maxDistance?, spread?, distribution?}, rays?, maxDistance? (all three ray maps), curvatureMethod?: normalMap|mesh, positionMode?: boundingBox|boundingSphere|none, maps?: [ids], enabled?, useLowAsHigh?, maxFrontal?, maxRear?, averageNormals?, lowSuffix?, highSuffix?}",
always,
settings
),
@@ -90,6 +92,10 @@ fn parse_mesh(file_name: &str, bytes: Vec<u8>) -> Result<BakeMesh> {
impl Session {
pub fn bake_task(&self, ts: usize) -> Result<BakeTask> {
let set = self.doc.project.texture_set(ts)?;
if !set.has_enabled_bake_tiles() {
return Err(EngineError::Other(format!("texture set {} has no UV tiles selected for baking", set.name)));
}
let needs_low_color = set.bake.maps.opacity.is_enabled
|| (set.bake.maps.id.is_enabled && set.bake.maps.id.parameters.source == texturecraft_core::IdColorSource::MaterialColor);
let low_base_color = if needs_low_color && (set.bake.high_poly.use_low_as_high || self.bake_meshes.high.is_empty()) {
@@ -112,14 +118,25 @@ impl Session {
} else {
None
};
let skew = high.as_ref().and(self.doc.bake_paint.get(&(ts, BakePaintTarget::Skew)).cloned());
let cage_paint = high.as_ref().and(self.doc.bake_paint.get(&(ts, BakePaintTarget::Cage)).cloned());
let tiles = set.tile_grid().map_or((1, 1), |g| (g.cols, g.rows));
let painted = |target| high.as_ref().and(self.doc.bake_paint.get(&(ts, target))).map(|map| super::layout::paint_for_bake(map, set)).transpose();
let skew = painted(BakePaintTarget::Skew)?;
let cage_paint = painted(BakePaintTarget::Cage)?;
let grid = set.tile_grid();
let tiles = grid.map_or((1, 1), |grid| (grid.cols, grid.rows));
let excluded_tiles: Vec<_> = set.uv_tiles.iter().filter(|tile| set.bake_excluded_tiles.contains(tile)).filter_map(|tile| grid?.block(*tile)).collect();
let previous_maps = if excluded_tiles.is_empty() { Default::default() } else { self.doc.baked.get(&ts).cloned().unwrap_or_default() };
let tracer = GPU_TRACER.get().cloned();
Ok(BakeTask {
low_base_color,
ts,
mesh: self.mesh.clone(),
mesh: match grid.filter(|_| !set.tile_resolutions.is_empty()) {
Some(grid) => {
let mut mesh = (*self.source).clone();
mesh.map_material_uvs(set.material, |uv| texturecraft_geom::glam::Vec2::from_array(grid.to_atlas(uv.to_array())));
Arc::new(mesh)
}
None => self.mesh.clone(),
},
bvh: self.bvh.clone(),
material: set.material,
settings: set.bake.clone(),
@@ -128,6 +145,8 @@ impl Session {
skew,
cage_paint,
tiles,
excluded_tiles,
previous_maps,
tracer,
})
}
@@ -364,7 +383,7 @@ pub fn settings_params(settings: &BakeSettings) -> Value {
/// Apply only the bake parameters supplied by the caller
fn apply_settings(settings: &mut BakeSettings, params: &Value, command: &str) -> Result<()> {
// Keep the current command limits until the reference controls are integrated
// Preserve the legacy flat-parameter limits for existing callers
const MAX_DILATION_PIXELS: u32 = 256;
const MAX_SUFFIX_CHARS: usize = 64;
@@ -378,6 +397,14 @@ fn apply_settings(settings: &mut BakeSettings, params: &Value, command: &str) ->
}
}
if let Some(patch) = params.get("patch") {
let mut model = json!(settings);
model_patch::apply_patch(&mut model, patch, command)?;
let updated: BakeSettings = serde_json::from_value(model).map_err(|error| bad(command, error.to_string()))?;
validate_model_settings(&updated, command)?;
*settings = updated;
}
if let Some(resolution) = u64p(params, "resolution") {
settings.common.resolution = u32::try_from(resolution)
.ok()
@@ -604,8 +631,15 @@ fn settings(session: &mut Session, params: &Value) -> Result<Value> {
}
fn bake_run(session: &mut Session, params: &Value) -> Result<Value> {
let next = updated_settings(session, params, "bake.run")?;
let next: Vec<_> = updated_settings(session, params, "bake.run")?
.into_iter()
.filter(|(index, _)| session.doc.project.texture_sets.get(*index).is_some_and(|texture_set| texture_set.has_enabled_bake_tiles()))
.collect();
let sets: Vec<usize> = next.iter().map(|(index, _)| *index).collect();
if sets.is_empty() {
return Ok(json!({"baked": [], "tracer": []}));
}
let cpu = boolp(params, "cpu") == Some(true);
let tracers = session.edit("Bake mesh maps", |session| {
let mut tracers = Vec::with_capacity(next.len());
+20
View File
@@ -1,11 +1,31 @@
//! Baking tasks, commands, settings helpers, and the mesh-map baking API
mod bake_mesh;
mod bake_meshes;
mod bake_task;
mod layout;
mod merged_high;
mod mesh_map_command;
mod model_patch;
mod paint_command;
mod preserve_tiles;
mod tile_command;
pub use bake_mesh::BakeMesh;
pub use bake_meshes::BakeMeshes;
pub use bake_task::BakeTask;
pub use merged_high::MergedHigh;
pub use mesh_map_command::{install_gpu_tracer, meshes_json, settings_params};
pub use model_patch::settings_patch;
pub use texturecraft_bake::*;
use crate::CommandSpec;
type MaterialColors = std::sync::Arc<Vec<Option<std::sync::Arc<texturecraft_geom::BaseColor>>>>;
pub(crate) fn specs() -> Vec<CommandSpec> {
let mut commands = mesh_map_command::specs();
commands.extend(paint_command::specs());
commands.extend(tile_command::specs());
commands
}
+40
View File
@@ -0,0 +1,40 @@
use serde_json::{Value, json};
use texturecraft_core::BakeSettings;
use crate::Result;
use crate::commands::bad;
/// Only the changed fields, using the persisted model's names and enum values
pub fn settings_patch(before: &BakeSettings, after: &BakeSettings) -> Value {
changed_fields(&json!(before), &json!(after)).unwrap_or_else(|| json!({}))
}
fn changed_fields(before: &Value, after: &Value) -> Option<Value> {
if before == after {
return None;
}
if let (Some(before), Some(after)) = (before.as_object(), after.as_object()) {
let fields = after
.iter()
.filter_map(|(name, value)| changed_fields(before.get(name).unwrap_or(&Value::Null), value).map(|change| (name.clone(), change)))
.collect();
Some(Value::Object(fields))
} else {
Some(after.clone())
}
}
/// Merge known fields only; null is a value, so optional settings can be cleared
pub(super) fn apply_patch(model: &mut Value, patch: &Value, command: &str) -> Result<()> {
let fields = patch.as_object().ok_or_else(|| bad(command, "bake settings patch must be an object"))?;
for (name, value) in fields {
let target = model.get_mut(name).ok_or_else(|| bad(command, format!("unknown bake setting `{name}`")))?;
if target.is_object() {
apply_patch(target, value, command)?;
} else {
*target = value.clone();
}
}
Ok(())
}
@@ -6,7 +6,7 @@ use texturecraft_bake::BakePaintMap;
use texturecraft_core::BakePaintTarget;
use texturecraft_geom::glam::Vec2;
pub fn specs() -> Vec<CommandSpec> {
pub(super) fn specs() -> Vec<CommandSpec> {
vec![
cmd!("bake.skew.set", "Set Skew Correction", [], None, "{ts?, value?: 0..1 | path: grayscale image}", always, |session, parameters| set(
session,
@@ -65,7 +65,7 @@ fn set(session: &mut Session, parameters: &Value, target: BakePaintTarget) -> Re
session.doc.bake_paint.insert((texture_set, target), Arc::new(map));
Ok(())
})?;
Ok(crate::bake_cmds::meshes_json(session))
Ok(super::meshes_json(session))
}
fn clear(session: &mut Session, parameters: &Value, target: BakePaintTarget) -> Result<Value> {
@@ -76,7 +76,7 @@ fn clear(session: &mut Session, parameters: &Value, target: BakePaintTarget) ->
Ok(())
})?;
}
Ok(crate::bake_cmds::meshes_json(session))
Ok(super::meshes_json(session))
}
fn paint(session: &mut Session, parameters: &Value, target: BakePaintTarget) -> Result<Value> {
@@ -123,7 +123,7 @@ fn paint(session: &mut Session, parameters: &Value, target: BakePaintTarget) ->
}
Arc::make_mut(map).paint(&points, radius, value, hardness, strength).map_err(|error| bad("bake.paint", error.to_string()))
})?;
Ok(crate::bake_cmds::meshes_json(session))
Ok(super::meshes_json(session))
}
#[cfg(not(target_arch = "wasm32"))]
+54
View File
@@ -0,0 +1,54 @@
use texturecraft_bake::BakeOutput;
use texturecraft_compose::BakedMaps;
use crate::{EngineError, Result};
/// Retain excluded tiles from the worker's snapshot, resampling when output size changes
pub(super) fn restore(output: &mut BakeOutput, previous: &BakedMaps, excluded_tiles: &[(u32, u32)], grid: (u32, u32)) -> Result<()> {
if excluded_tiles.is_empty() {
return Ok(());
}
let size = (output.resolution, output.height);
let tile_width = size.0 / grid.0.max(1);
let tile_height = size.1 / grid.1.max(1);
for (map, pixels) in &mut output.maps {
let components = map.components();
for &(column, row) in excluded_tiles {
for y in row * tile_height..(row + 1) * tile_height {
let first = (y as usize * size.0 as usize + column as usize * tile_width as usize) * components;
let last = first + tile_width as usize * components;
let row_pixels = pixels.get_mut(first..last).ok_or_else(|| EngineError::Other("excluded UV tile lies outside the baked pixels".into()))?;
for (offset, pixel) in row_pixels.chunks_exact_mut(components).enumerate() {
let value = previous.sample(*map, column * tile_width + offset as u32, y, size).unwrap_or_else(|| map.neutral());
for (component, value) in pixel.iter_mut().zip(value) {
*component = value;
}
}
}
}
}
// Keep unchecked map outputs too when a partial bake changes the atlas dimensions
for map in previous.maps.keys() {
if output.maps.contains_key(map) || (previous.resolution == size.0 && previous.height(*map) == size.1) {
continue;
}
let components = map.components();
let count = (size.0 as usize)
.checked_mul(size.1 as usize)
.and_then(|count| count.checked_mul(components))
.ok_or_else(|| EngineError::Other("resized bake map exceeds the addressable size".into()))?;
let mut pixels = Vec::new();
pixels.try_reserve_exact(count).map_err(|error| EngineError::Other(format!("cannot retain mesh map {}: {error}", map.id())))?;
for y in 0..size.1 {
for x in 0..size.0 {
let value = previous.sample(*map, x, y, size).unwrap_or_else(|| map.neutral());
pixels.extend(value.into_iter().take(components));
}
}
output.maps.insert(*map, pixels);
}
Ok(())
}
+42
View File
@@ -0,0 +1,42 @@
use serde_json::{Value, json};
use crate::commands::{CommandSpec, always, bad, boolp, u64p};
use crate::set_cmds::ts_param;
use crate::{Result, Session, cmd};
pub(super) fn specs() -> Vec<CommandSpec> {
vec![cmd!(
"bake.tile.set",
"Include UV tile in bake",
[],
None,
"{ts?, tile: UDIM number, enabled: bool} → {ts, tile, enabled}; excluded tiles keep existing baked pixels",
always,
set_enabled
)]
}
fn set_enabled(session: &mut Session, params: &Value) -> Result<Value> {
const COMMAND: &str = "bake.tile.set";
let texture_set = ts_param(session, params, COMMAND)?;
let tile = u64p(params, "tile").and_then(|tile| u32::try_from(tile).ok()).ok_or_else(|| bad(COMMAND, "`tile` must be a UDIM number"))?;
let enabled = boolp(params, "enabled").ok_or_else(|| bad(COMMAND, "`enabled` must be true or false"))?;
let settings = session.doc.project.texture_set(texture_set)?;
if !settings.uv_tiles.contains(&tile) {
return Err(bad(COMMAND, format!("texture set {} has no UV tile {tile}", settings.name)));
}
let was_enabled = !settings.bake_excluded_tiles.contains(&tile);
if enabled != was_enabled {
session.edit("Include UV tile in bake", |session| {
let settings = session.doc.project.texture_set_mut(texture_set)?;
if enabled {
settings.bake_excluded_tiles.remove(&tile);
} else {
settings.bake_excluded_tiles.insert(tile);
}
Ok(())
})?;
}
Ok(json!({"ts": texture_set, "tile": tile, "enabled": enabled}))
}
+1 -2
View File
@@ -68,8 +68,7 @@ pub fn command_specs() -> &'static [CommandSpec] {
v.extend(crate::uv_tile_cmds::specs());
v.extend(crate::template_cmds::specs());
v.extend(crate::project_cmds::specs());
v.extend(crate::bake_cmds::specs());
v.extend(crate::bake_paint_cmds::specs());
v.extend(crate::bake::specs());
v.extend(crate::materialx_cmds::specs());
v.extend(crate::file_cmds::specs());
v.extend(crate::preset_cmds::specs());
+27 -19
View File
@@ -129,26 +129,34 @@ pub fn texture_sets(s: &Session) -> Value {
json!((0..s.set_count()).map(|i| texture_set(s, i)).collect::<Vec<_>>())
}
/// One texture set; UV-tiled sets list their tiles and where each sits in the texel atlas.
pub fn texture_set(s: &Session, i: usize) -> Value {
let Some(t) = s.doc.project.texture_sets.get(i) else { return Value::Null };
let grid = t.tile_grid();
let tiles: Vec<Value> =
t.uv_tiles.iter().filter_map(|u| grid?.block(*u).map(|(x, y)| json!({ "udim": u, "block": [x, y], "resolution": t.tile_resolution(*u) }))).collect();
/// One texture set, including UV tile layout and bake selection
pub fn texture_set(session: &Session, index: usize) -> Value {
let Some(texture_set) = session.doc.project.texture_sets.get(index) else { return Value::Null };
let grid = texture_set.tile_grid();
let tiles: Vec<Value> = texture_set
.uv_tiles
.iter()
.filter_map(|tile| {
grid?.block(*tile).map(|(x, y)| {
json!({"udim": tile, "block": [x, y], "resolution": texture_set.tile_resolution(*tile), "bakeEnabled": !texture_set.bake_excluded_tiles.contains(tile)})
})
})
.collect();
json!({
"index": i,
"name": t.name,
"resolution": t.resolution,
"size": t.size(),
"blockResolution": t.block_resolution(),
"uvTiles": t.uv_tiles,
"index": index,
"name": texture_set.name,
"resolution": texture_set.resolution,
"size": texture_set.size(),
"blockResolution": texture_set.block_resolution(),
"uvTiles": texture_set.uv_tiles,
"tiles": tiles,
"channels": t.channels.iter().map(|(c, f)| json!({ "channel": c.id(), "format": f.label() })).collect::<Vec<_>>(),
"layers": s.doc.project.walk(i).len(),
"parts": crate::set_cmds::parts(s, i),
"baked": crate::project_cmds::baked_json(s.doc.baked.get(&i)),
"visible": t.visible,
"active": i == s.ts(),
"channels": texture_set.channels.iter().map(|(channel, format)| json!({ "channel": channel.id(), "format": format.label() })).collect::<Vec<_>>(),
"layers": session.doc.project.walk(index).len(),
"parts": crate::set_cmds::parts(session, index),
"baked": crate::project_cmds::baked_json(session.doc.baked.get(&index)),
"visible": texture_set.visible,
"active": index == session.ts(),
})
}
@@ -161,7 +169,7 @@ pub fn session(s: &Session) -> Value {
"path": s.path,
"modified": s.modified,
"textureSets": texture_sets(s),
"bakeMeshes": crate::bake_cmds::meshes_json(s),
"bakeMeshes": crate::bake::meshes_json(s),
"activeTextureSet": ts,
"selectedLayer": s.selected_layer().map(|l| l.0),
"target": match s.target { StackTarget::Content => json!("content"), StackTarget::Mask => json!("mask"), StackTarget::Effect(e) => json!(e.0) },
+2 -6
View File
@@ -8,10 +8,7 @@
#![forbid(unsafe_code)]
#![deny(clippy::unwrap_used, clippy::expect_used, clippy::panic, clippy::unimplemented, clippy::todo, clippy::unreachable)]
pub mod bake_cmds;
#[path = "bake/mod.rs"]
mod bake_data;
mod bake_paint_cmds;
pub mod bake;
pub mod brush_preset_cmds;
pub mod camera_cmds;
pub mod commands;
@@ -51,14 +48,13 @@ pub mod tool_cmds;
pub mod uv_tile_cmds;
pub mod view_cmds;
pub use bake_data::{BakeMesh, BakeMeshes, BakeTask};
pub use bake::{BakeMesh, BakeMeshes, BakeTask};
pub use commands::{CommandSpec, command_specs, execute, find};
pub use path_tool::PathState;
pub use project_cmds::sample_session;
pub use session::{CloneFrom, CloneSource, Document, FillMode, Session, SetCache, StackTarget, StencilState, Tool, ToolState, ViewMode};
pub use set_cmds::{ResizeOutput, ResizeTask};
pub use texturecraft_bake as bake;
pub use texturecraft_compose as compose;
pub use texturecraft_core as core;
pub use texturecraft_formats as formats;
+1 -1
View File
@@ -59,7 +59,7 @@ fn set(s: &mut Session, p: &Value) -> Result<Value> {
None => resample(map.components(), (res, height), directx, |u, v| img.sample(u, v)),
// An atlas texel reads the image of the tile its mesh UV falls in.
Some((grid, imgs)) => resample(map.components(), (res, height), directx, |u, v| {
let uv = set.from_atlas(grid, [u, v]);
let uv = grid.from_atlas([u, v]);
udim_at(uv).and_then(|t| imgs.get(&t)).map_or([0.0; 4], |img| img.sample(uv[0] - uv[0].floor(), uv[1] - uv[1].floor()))
}),
};
+1
View File
@@ -172,6 +172,7 @@ pub fn filter(id: &str, size: usize) -> Option<Vec<Option<Sample>>> {
gbuf: &gbuf,
pixels: &pixels,
baked: &baked,
block_scales: p.texture_set(0).map(|set| set.block_scales()).unwrap_or_default(),
preview: None,
images: &images,
bounds: mesh.bounds(),
+2
View File
@@ -728,6 +728,7 @@ impl Session {
gbuf: &cache.gbuf,
pixels: &self.doc.pixels,
baked: self.doc.baked.get(&ts).unwrap_or(&empty),
block_scales: cache.composite.block_scales.clone(),
preview,
images: &self.images,
bounds: self.mesh.bounds(),
@@ -816,6 +817,7 @@ impl Session {
gbuf: &cache.gbuf,
pixels: &self.doc.pixels,
baked: self.doc.baked.get(&ts).unwrap_or(&empty),
block_scales: cache.composite.block_scales.clone(),
preview: None,
images: &self.images,
bounds: self.mesh.bounds(),
+91 -54
View File
@@ -39,61 +39,69 @@ pub fn specs() -> Vec<CommandSpec> {
]
}
fn tile_resolution(s: &mut Session, p: &Value) -> Result<Value> {
const CMD: &str = "textureSet.tile.resolution";
let ts = ts_param(s, p, CMD)?;
let tile = u64p(p, "tile").and_then(|t| u32::try_from(t).ok()).ok_or_else(|| bad(CMD, "`tile` (a UDIM number) is required"))?;
let r = u64p(p, "resolution").ok_or_else(|| bad(CMD, "`resolution` is required"))?;
let r = check_resolution(u32::try_from(r).unwrap_or(0))?;
let set = s.doc.project.texture_set(ts)?;
if !set.uv_tiles.contains(&tile) {
return Err(bad(CMD, format!("texture set \"{}\" has no UV tile {tile} (tiles: {:?})", set.name, set.uv_tiles)));
fn tile_resolution(session: &mut Session, params: &Value) -> Result<Value> {
const COMMAND: &str = "textureSet.tile.resolution";
let texture_set_index = ts_param(session, params, COMMAND)?;
let tile = u64p(params, "tile").and_then(|tile| u32::try_from(tile).ok()).ok_or_else(|| bad(COMMAND, "`tile` (a UDIM number) is required"))?;
let resolution = u64p(params, "resolution").ok_or_else(|| bad(COMMAND, "`resolution` is required"))?;
let resolution = check_resolution(u32::try_from(resolution).unwrap_or(0))?;
let texture_set = session.doc.project.texture_set(texture_set_index)?;
if !texture_set.uv_tiles.contains(&tile) {
return Err(bad(COMMAND, format!("texture set \"{}\" has no UV tile {tile} (tiles: {:?})", texture_set.name, texture_set.uv_tiles)));
}
if set.tile_resolution(tile) == r {
return Ok(json!({ "ts": ts, "tile": tile, "resolution": r, "size": set.size() }));
let removes_override = resolution == texture_set.resolution && texture_set.tile_resolutions.contains_key(&tile);
if texture_set.tile_resolution(tile) == resolution && !removes_override {
return Ok(json!({ "ts": texture_set_index, "tile": tile, "resolution": resolution, "size": texture_set.size() }));
}
s.cancel_stroke();
let size = s.edit("UV tile resolution", |s| {
let set = s.doc.project.texture_set_mut(ts)?;
let old = set.clone();
if r == set.resolution {
set.tile_resolutions.remove(&tile);
session.cancel_stroke();
let size = session.edit("UV tile resolution", |session| {
let texture_set = session.doc.project.texture_set_mut(texture_set_index)?;
let previous = texture_set.clone();
if resolution == texture_set.resolution {
texture_set.tile_resolutions.remove(&tile);
} else {
set.tile_resolutions.insert(tile, r);
texture_set.tile_resolutions.insert(tile, resolution);
}
check_size(texture_set)?;
let size = texture_set.size();
if previous.tile_resolution(tile) != resolution {
relayout(&mut session.doc, texture_set_index, &previous, &mut session.log)?;
}
check_size(set)?;
let size = set.size();
relayout(&mut s.doc, ts, &old, &mut s.log)?;
Ok(size)
})?;
Ok(json!({ "ts": ts, "tile": tile, "resolution": r, "size": size }))
Ok(json!({ "ts": texture_set_index, "tile": tile, "resolution": resolution, "size": size }))
}
fn uv_tiles(s: &mut Session, p: &Value) -> Result<Value> {
const CMD: &str = "textureSet.uvTiles";
let ts = ts_param(s, p, CMD)?;
let enabled = boolp(p, "enabled").ok_or_else(|| bad(CMD, "`enabled` (true or false) is required"))?;
let set = s.doc.project.texture_set(ts)?;
fn uv_tiles(session: &mut Session, params: &Value) -> Result<Value> {
const COMMAND: &str = "textureSet.uvTiles";
let texture_set_index = ts_param(session, params, COMMAND)?;
let enabled = boolp(params, "enabled").ok_or_else(|| bad(COMMAND, "`enabled` (true or false) is required"))?;
let texture_set = session.doc.project.texture_set(texture_set_index)?;
let tiles = if enabled {
detect_uv_tiles(&s.source, set.material, Some(true), &mut Vec::new()).map_err(|e| bad(CMD, format!("texture set \"{}\": {e}", set.name)))?
detect_uv_tiles(&session.source, texture_set.material, Some(true), &mut Vec::new())
.map_err(|error| bad(COMMAND, format!("texture set \"{}\": {error}", texture_set.name)))?
} else {
Vec::new()
};
if tiles == set.uv_tiles {
return Ok(json!({ "ts": ts, "uvTiles": tiles, "dropped": [] }));
if tiles == texture_set.uv_tiles {
return Ok(json!({ "ts": texture_set_index, "uvTiles": tiles, "dropped": [] }));
}
// Leaving UV tile mode keeps tile 1001 (UV 0..1), the area a classic set paints.
let dropped: Vec<u32> = set.uv_tiles.iter().copied().filter(|t| !enabled && *t != 1001).collect();
s.cancel_stroke();
s.edit(if enabled { "Use UV tiles" } else { "Stop using UV tiles" }, |s| {
let set = s.doc.project.texture_set_mut(ts)?;
let old = set.clone();
set.tile_resolutions.retain(|u, _| tiles.contains(u));
set.uv_tiles = tiles.clone();
check_size(set)?;
relayout(&mut s.doc, ts, &old, &mut s.log)
// Leaving UV tile mode keeps tile 1001, the area a classic set paints
let dropped: Vec<u32> = texture_set.uv_tiles.iter().copied().filter(|tile| !enabled && *tile != 1001).collect();
session.cancel_stroke();
session.edit(if enabled { "Use UV tiles" } else { "Stop using UV tiles" }, |session| {
let texture_set = session.doc.project.texture_set_mut(texture_set_index)?;
let previous = texture_set.clone();
texture_set.tile_resolutions.retain(|tile, _| tiles.contains(tile));
texture_set.bake_excluded_tiles.retain(|tile| tiles.contains(tile));
texture_set.uv_tiles = tiles.clone();
check_size(texture_set)?;
relayout(&mut session.doc, texture_set_index, &previous, &mut session.log)
})?;
Ok(json!({ "ts": ts, "uvTiles": tiles, "dropped": dropped }))
Ok(json!({ "ts": texture_set_index, "uvTiles": tiles, "dropped": dropped }))
}
/// Mesh UV → normalized atlas position of UV tile layout `set` (None where the layout holds
@@ -119,23 +127,30 @@ fn from_layout(set: &TextureSet, a: [f32; 2]) -> Option<[f32; 2]> {
(set.uv_tiles.contains(&udim) && local.0 <= scale && local.1 <= scale).then(|| set.from_atlas(&g, a))
}
/// Resample texture set `ts`'s painted images and baked maps from layout `old` into the set's
/// current layout (inside [`Session::edit`] after changing the set). Notes go to `log`.
/// Move painted images into the working layout and baked maps only when the tile grid changes
pub(crate) fn relayout(doc: &mut Document, ts: usize, old: &TextureSet, log: &mut Vec<String>) -> Result<()> {
let new = doc.project.texture_set(ts)?.clone();
let map = |a: [f32; 2]| from_layout(&new, a).and_then(|m| to_layout(old, m));
let ((ow, oh), (nw, nh)) = (old.size(), new.size());
let texel = |x: f32, y: f32| map([x / nw as f32, y / nh as f32]).map(|o| (o[0] * ow as f32, o[1] * oh as f32));
let all = TileImage::new(nw, nh, 1);
let map = |uv: [f32; 2]| from_layout(&new, uv).and_then(|mesh_uv| to_layout(old, mesh_uv));
let (old_size, new_size) = (old.size(), new.size());
let texel = |x: f32, y: f32| map([x / new_size.0 as f32, y / new_size.1 as f32]).map(|uv| (uv[0] * old_size.0 as f32, uv[1] * old_size.1 as f32));
let all = TileImage::new(new_size.0, new_size.1, 1);
let tiles: Vec<(u32, u32)> = (0..all.tiles_y()).flat_map(|ty| (0..all.tiles_x()).map(move |tx| (tx, ty))).collect();
// Blocks and tiles are multiples of 64 texels (resolutions are powers of two ≥ 128), so the
// map is affine (or None) over each destination tile.
crate::layer_ops::map_set_images(doc, ts, |img, empty| remap_image(img, (nw, nh), empty, &texel, &tiles, true));
// Atlas blocks align with the 64-texel storage tiles, making each mapping affine
crate::layer_ops::map_set_images(doc, ts, |image, empty| remap_image(image, new_size, empty, &texel, &tiles, true));
remap_bake_paint(doc, ts, old, &new, &map)?;
if let Some(baked) = doc.baked.get(&ts) {
match remap_baked(baked, old, &new, &map) {
Some(b) => {
doc.baked.insert(ts, b);
if old.uv_tiles != new.uv_tiles
&& let Some(baked) = doc.baked.get(&ts)
{
let mut old_bake = old.clone();
let mut new_bake = new.clone();
old_bake.tile_resolutions.clear();
new_bake.tile_resolutions.clear();
let bake_map = |uv| from_layout(&new_bake, uv).and_then(|mesh_uv| to_layout(&old_bake, mesh_uv));
match remap_baked(baked, &old_bake, &new_bake, &bake_map) {
Some(baked) => {
doc.baked.insert(ts, baked);
}
None => {
doc.baked.remove(&ts);
@@ -326,6 +341,28 @@ mod tests {
assert!(execute(&mut s, "textureSet.tile.resolution", &json!({"tile": 1001, "resolution": 100})).is_err());
}
#[test]
fn removing_a_tile_override_at_the_sets_current_resolution_restores_inheritance() {
let mut session = udim_session();
execute(&mut session, "textureSet.tile.resolution", &json!({"tile": 1002, "resolution": 128})).unwrap();
execute(&mut session, "textureSet.resolution", &json!({"resolution": 128})).unwrap();
let before = session.doc.project.clone();
let history_steps = session.history_labels().len();
execute(&mut session, "textureSet.tile.resolution", &json!({"tile": 1002, "resolution": 128})).unwrap();
assert!(session.doc.project.texture_sets[0].tile_resolutions.is_empty());
assert_eq!(session.history_labels().len(), history_steps + 1);
let reopened = Session::from_project_bytes(&session.to_project_bytes().unwrap()).unwrap();
assert!(reopened.doc.project.texture_sets[0].tile_resolutions.is_empty());
session.undo().unwrap();
assert_eq!(session.doc.project, before);
session.redo().unwrap();
execute(&mut session, "textureSet.resolution", &json!({"resolution": 256})).unwrap();
assert_eq!(session.doc.project.texture_sets[0].tile_resolution(1002), 256);
assert_eq!(session.doc.project.texture_sets[0].bake, before.texture_sets[0].bake);
}
#[test]
fn export_writes_each_tile_at_its_own_size() {
let mut s = udim_session();
+130
View File
@@ -0,0 +1,130 @@
use std::sync::Arc;
use serde_json::json;
use texturecraft_engine::bake::Progress;
use texturecraft_engine::core::BakedMap;
use texturecraft_engine::geom::{NO_TRI, UvGBuffer, primitives};
use texturecraft_engine::{Session, execute};
fn session() -> Session {
let mut session = Session::new_project("Bake detail", primitives::udim_plane(), "builtin:udim_plane", None, 256).unwrap();
execute(&mut session, "bake.settings", &json!({"resolution": 128, "maps": ["position"], "dilation": 0, "patch": {"common": {"apply_diffusion": false}}}))
.unwrap();
session
}
#[test]
fn working_tile_resolution_preserves_bake_samples_and_pixels() {
let mut session = session();
let original = session.bake_task(0).unwrap().run(&Progress::new()).unwrap();
execute(&mut session, "textureSet.tile.resolution", &json!({"tile": 1002, "resolution": 128})).unwrap();
let task = session.bake_task(0).unwrap();
let output = task.run(&Progress::new()).unwrap();
assert_eq!((output.resolution, output.height), (256, 128));
let gbuffer = UvGBuffer::new(&task.mesh, task.material, output.resolution, output.height);
let mut samples = [0usize; 2];
for (index, triangle) in gbuffer.tri.iter().enumerate() {
if *triangle != NO_TRI {
samples[(index % 256) / 128] += 1;
}
}
assert_eq!(samples, [128 * 128; 2], "each tile receives the full Bake Output Size");
assert_eq!(output.maps, original.maps);
}
#[test]
fn changing_working_resolution_never_resamples_stored_bakes() {
let mut session = session();
let output = session.bake_task(0).unwrap().run(&Progress::new()).unwrap();
session.apply_bake(0, output).unwrap();
let original = session.doc.baked[&0].clone();
for resolution in [128, 512, 256] {
execute(&mut session, "textureSet.tile.resolution", &json!({"tile": 1002, "resolution": resolution})).unwrap();
let current = &session.doc.baked[&0];
assert!(Arc::ptr_eq(&current.maps[&BakedMap::Position], &original.maps[&BakedMap::Position]), "working resize must retain the bake buffer");
assert_eq!(current, &original);
let reopened = Session::from_project_bytes(&session.to_project_bytes().unwrap()).unwrap();
assert_eq!(reopened.doc.baked[&0], original);
}
session.undo().unwrap();
assert_eq!(session.doc.baked[&0], original);
session.redo().unwrap();
assert_eq!(session.doc.baked[&0], original);
for resolution in [512, 128] {
execute(&mut session, "textureSet.resolution", &json!({"resolution": resolution})).unwrap();
assert!(Arc::ptr_eq(&session.doc.baked[&0].maps[&BakedMap::Position], &original.maps[&BakedMap::Position]));
}
}
#[test]
fn rectangular_bakes_and_excluded_vertical_tiles_ignore_working_resolution() {
let mut mesh = primitives::udim_plane();
let second_plane = mesh.uvs.len() / 2;
for uv in mesh.uvs.iter_mut().skip(second_plane) {
uv.x -= 1.0;
uv.y -= 1.0;
}
let mut session = Session::new_project("Vertical bake", mesh, "builtin:udim_plane", None, 256).unwrap();
execute(
&mut session,
"bake.settings",
&json!({"resolution": 64, "maps": ["position"], "dilation": 0, "patch": {"common": {"resolution_height": "R128", "apply_diffusion": false}}}),
)
.unwrap();
let original = session.bake_task(0).unwrap().run(&Progress::new()).unwrap();
assert_eq!((original.resolution, original.height), (64, 256));
let pixels = original.maps.clone();
session.apply_bake(0, original).unwrap();
execute(&mut session, "textureSet.tile.resolution", &json!({"tile": 1011, "resolution": 128})).unwrap();
execute(&mut session, "bake.tile.set", &json!({"tile": 1011, "enabled": false})).unwrap();
let output = session.bake_task(0).unwrap().run(&Progress::new()).unwrap();
assert_eq!(output.maps, pixels, "rebaked and excluded tiles both keep their full rectangular detail");
}
#[test]
fn imported_mesh_maps_display_and_export_the_entire_overridden_tile() {
use texturecraft_engine::compose::{DisplayKind, tile_bytes};
use texturecraft_engine::formats::export::{Dest, ExportOptions, ExportPreset, FileFormat, MapSpec, SourceRef};
let mut session = session();
execute(&mut session, "textureSet.tile.resolution", &json!({"tile": 1002, "resolution": 128})).unwrap();
let image = image::GrayImage::from_fn(128, 128, |x, y| image::Luma([(x + y) as u8]));
let mut bytes = Vec::new();
image.write_to(&mut std::io::Cursor::new(&mut bytes), image::ImageFormat::Png).unwrap();
for tile in [1001, 1002] {
session.import_resource_bytes(&format!("ao.{tile}.png"), bytes.clone()).unwrap();
}
execute(&mut session, "textureSet.meshMap.set", &json!({"map": "ambientOcclusion", "image": "ao.1001.png"})).unwrap();
while session.update() {}
let baked = &session.doc.baked[&0];
let map = BakedMap::AmbientOcclusion;
assert!((baked.scalar(map, 248, 120, (256, 128)).unwrap() - 240.0 / 255.0).abs() < 0.001);
let composite = &session.caches[0].composite;
let display = tile_bytes(composite, baked, DisplayKind::Orm, 5, 1);
assert_eq!(display[((56 * 64 + 56) * 4) as usize], 240, "the viewport samples the far corner of the smaller working tile");
let options = ExportOptions::new(ExportPreset {
name: "Bake detail".into(),
maps: vec![MapSpec {
file: "ao.$udim".into(),
format: FileFormat::Png,
bit_depth: 8,
channels: vec![(Dest::L, SourceRef::Baked { map, component: 0 })],
}],
});
let files = session.export_files(&[0], &options).unwrap();
let file = files.iter().find(|file| file.name == "ao.1002.png").unwrap();
let exported = image::load_from_memory(&file.bytes).unwrap().to_luma8();
assert_eq!(exported.dimensions(), (128, 128));
assert_eq!(exported.get_pixel(120, 120)[0], 240);
assert_eq!(exported.get_pixel(10, 10)[0], 20);
let layer = session.doc.project.texture_sets[0].stack[0];
execute(&mut session, "mask.add.black", &json!({"layer": layer.0})).unwrap();
execute(&mut session, "effect.add.generator", &json!({"layer": layer.0, "generator": "ambientOcclusion"})).unwrap();
let mask = session.mask_at(layer, &[(376, 120), (266, 10)]).unwrap();
assert_eq!(mask, vec![1.0, 0.0], "generators sample the whole bake through the working layout");
}
+112
View File
@@ -0,0 +1,112 @@
use serde_json::json;
use texturecraft_engine::core::{BakeResolution, BakeSettings};
use texturecraft_engine::geom::primitives;
use texturecraft_engine::{Session, execute};
fn session() -> Session {
let mut session = Session::new_project("Bake settings", primitives::material_ball(), "builtin:material_ball", None, 128).unwrap();
let second = &mut session.doc.project.texture_sets[1].bake;
second.common.is_enabled = false;
second.common.resolution = BakeResolution::R128;
second.common.resolution_height = Some(BakeResolution::R256);
second.maps.ao.is_enabled = false;
second.maps.ao.parameters.rays.min_distance = 0.25;
second.maps.ao.parameters.rays.rays = 16;
second.maps.height.parameters.scaling_divisor = 2.0;
session
}
#[test]
fn nested_settings_patch_preserves_other_fields_and_is_one_undo_step() {
let mut session = session();
let before = session.doc.project.clone();
let history_steps = session.history_labels().len();
let patch = json!({"maps": {"ao": {"parameters": {"rays": {"rays": 128}}}}});
let result = execute(&mut session, "bake.settings", &json!({"ts": "all", "patch": patch})).unwrap();
let mut expected = before.clone();
for texture_set in &mut expected.texture_sets {
texture_set.bake.maps.ao.parameters.rays.rays = 128;
}
assert_eq!(session.doc.project, expected);
assert_eq!(result.as_array().unwrap().len(), 2);
assert_eq!(result[1]["model"], json!(expected.texture_sets[1].bake));
assert_eq!(session.history_labels().len(), history_steps + 1);
let reopened = Session::from_project_bytes(&session.to_project_bytes().unwrap()).unwrap();
assert_eq!(reopened.doc.project.texture_sets, expected.texture_sets);
session.undo().unwrap();
assert_eq!(session.doc.project, before);
session.redo().unwrap();
assert_eq!(session.doc.project, expected);
}
#[test]
fn settings_patch_validates_every_target_before_changing_any() {
let mut session = session();
let before = session.doc.project.clone();
let history = session.history_labels();
// This maximum is valid for the active set but below the second set's minimum
let patch = json!({"maps": {"ao": {"parameters": {"rays": {"max_distance": 0.1}}}}});
let error = execute(&mut session, "bake.settings", &json!({"ts": "all", "patch": patch})).unwrap_err();
assert!(error.to_string().contains("minimum occluder distance"), "{error}");
assert_eq!(session.doc.project, before);
assert_eq!(session.history_labels(), history);
}
#[test]
fn settings_patch_rejects_unknown_fields_and_invalid_shapes() {
let mut session = session();
let before = session.doc.project.clone();
let history = session.history_labels();
for patch in [
json!(null),
json!([]),
json!({"unknown": 1}),
json!({"common": null}),
json!({"common": {"resolution": "invalid"}}),
json!({"common": {"antialiasing": true}}),
json!({"maps": {"ao": {"parameters": {"rays": {"rays": 257}}}}}),
json!({"maps": {"ao": {"parameters": {"rays": {"rayz": 128}}}}}),
] {
assert!(execute(&mut session, "bake.settings", &json!({"ts": "all", "patch": patch})).is_err(), "{patch}");
assert_eq!(session.doc.project, before);
assert_eq!(session.history_labels(), history);
}
}
#[test]
fn settings_patch_can_clear_optional_height_and_keeps_target_selection() {
let mut session = session();
let first = session.doc.project.texture_sets[0].bake.clone();
let mut second = session.doc.project.texture_sets[1].bake.clone();
let patch = json!({"common": {"resolution_height": null}});
execute(&mut session, "bake.settings", &json!({"ts": [1], "patch": patch})).unwrap();
second.common.resolution_height = None;
assert_eq!(session.doc.project.texture_sets[0].bake, first);
assert_eq!(session.doc.project.texture_sets[1].bake, second);
let history_steps = session.history_labels().len();
execute(&mut session, "bake.settings", &json!({"ts": "all", "patch": {}})).unwrap();
execute(&mut session, "bake.settings", &json!({"ts": 1, "patch": patch})).unwrap();
assert_eq!(session.history_labels().len(), history_steps);
}
#[test]
fn settings_patch_can_reset_one_section_without_replacing_other_settings() {
let mut session = session();
let mut expected = session.doc.project.clone();
let defaults = BakeSettings::default().maps.ao.parameters;
for texture_set in &mut expected.texture_sets {
texture_set.bake.maps.ao.parameters = defaults;
}
execute(&mut session, "bake.settings", &json!({"ts": "all", "patch": {"maps": {"ao": {"parameters": defaults}}}})).unwrap();
assert_eq!(session.doc.project, expected);
}
+172
View File
@@ -0,0 +1,172 @@
use std::sync::Arc;
use serde_json::{Value, json};
use texturecraft_engine::bake::Progress;
use texturecraft_engine::compose::BakedMaps;
use texturecraft_engine::core::BakedMap;
use texturecraft_engine::geom::primitives;
use texturecraft_engine::{Session, execute};
fn session() -> Session {
let mut session = Session::new_project("Tile baking", primitives::udim_plane(), "builtin:udim_plane", None, 128).unwrap();
execute(&mut session, "bake.settings", &json!({"resolution": 32, "maps": ["ambientOcclusion"], "rays": 2})).unwrap();
session
}
#[test]
fn tile_selection_is_inspectable_saved_and_undoable() {
let mut session = session();
let before = session.doc.project.clone();
let result = execute(&mut session, "bake.tile.set", &json!({"tile": 1002, "enabled": false})).unwrap();
assert_eq!(result, json!({"ts": 0, "tile": 1002, "enabled": false}));
let selected = session.doc.project.clone();
let inspected = execute(&mut session, "textureSet.inspect", &Value::Null).unwrap();
assert_eq!(inspected["tiles"][0]["bakeEnabled"], true);
assert_eq!(inspected["tiles"][1]["bakeEnabled"], false);
let reopened = Session::from_project_bytes(&session.to_project_bytes().unwrap()).unwrap();
assert_eq!(reopened.doc.project, selected);
let history = session.history_labels();
execute(&mut session, "bake.tile.set", &json!({"tile": 1002, "enabled": false})).unwrap();
assert_eq!(session.history_labels(), history);
session.undo().unwrap();
assert_eq!(session.doc.project, before);
session.redo().unwrap();
assert_eq!(session.doc.project, selected);
for params in [json!({}), json!({"tile": 1003, "enabled": false}), json!({"tile": u64::MAX, "enabled": false}), json!({"tile": 1001, "enabled": 1})] {
assert!(execute(&mut session, "bake.tile.set", &params).is_err());
assert_eq!(session.doc.project, selected);
assert_eq!(session.history_labels(), history);
}
}
#[test]
fn partial_bake_preserves_unchecked_tiles_and_uses_the_workers_selection() {
let mut session = session();
session.doc.baked.insert(0, BakedMaps { resolution: 64, maps: [(BakedMap::AmbientOcclusion, Arc::new(vec![0.25; 64 * 32]))].into() });
execute(&mut session, "bake.tile.set", &json!({"tile": 1002, "enabled": false})).unwrap();
let mut task = session.bake_task(0).unwrap();
task.tracer = None;
// Editing the checkboxes while a bake runs affects the next bake
execute(&mut session, "bake.tile.set", &json!({"tile": 1002, "enabled": true})).unwrap();
execute(&mut session, "bake.tile.set", &json!({"tile": 1001, "enabled": false})).unwrap();
let before = session.doc.baked.clone();
let output = task.run(&Progress::new()).unwrap();
session.apply_bake(0, output).unwrap();
let pixels = &session.doc.baked[&0].maps[&BakedMap::AmbientOcclusion];
for row in pixels.chunks_exact(64) {
assert!(row[..32].iter().all(|value| *value > 0.99));
assert!(row[32..].iter().all(|value| *value == 0.25));
}
session.undo().unwrap();
assert_eq!(session.doc.baked, before);
}
#[test]
fn partial_bake_resizes_retained_tiles_and_unchecked_map_outputs() {
let mut session = session();
session.doc.baked.insert(
0,
BakedMaps {
resolution: 64,
maps: [(BakedMap::AmbientOcclusion, Arc::new(vec![0.25; 64 * 32])), (BakedMap::Normal, Arc::new(vec![0.4; 64 * 32 * 3]))].into(),
},
);
execute(&mut session, "bake.tile.set", &json!({"tile": 1002, "enabled": false})).unwrap();
let result = execute(&mut session, "bake.run", &json!({"resolution": 64, "cpu": true})).unwrap();
assert_eq!(result["baked"], json!([0]));
let baked = &session.doc.baked[&0];
assert_eq!((baked.resolution, baked.height(BakedMap::AmbientOcclusion)), (128, 64));
for row in baked.maps[&BakedMap::AmbientOcclusion].chunks_exact(128) {
assert!(row[..64].iter().all(|value| *value > 0.99));
assert!(row[64..].iter().all(|value| *value == 0.25));
}
assert_eq!(baked.maps[&BakedMap::Normal].len(), 128 * 64 * 3);
assert!(baked.maps[&BakedMap::Normal].iter().all(|value| *value == 0.4));
let reopened = Session::from_project_bytes(&session.to_project_bytes().unwrap()).unwrap();
assert_eq!(reopened.doc.baked, session.doc.baked);
}
#[test]
fn tile_selection_preserves_the_correct_udim_row() {
let mut mesh = primitives::udim_plane();
let second_plane = mesh.uvs.len() / 2;
for uv in mesh.uvs.iter_mut().skip(second_plane) {
uv.x -= 1.0;
uv.y -= 1.0;
}
let mut session = Session::new_project("Vertical UV tiles", mesh, "builtin:udim_plane", None, 128).unwrap();
assert_eq!(session.doc.project.texture_sets[0].uv_tiles, [1001, 1011]);
session.doc.baked.insert(0, BakedMaps { resolution: 32, maps: [(BakedMap::AmbientOcclusion, Arc::new(vec![0.25; 32 * 64]))].into() });
execute(&mut session, "bake.tile.set", &json!({"tile": 1011, "enabled": false})).unwrap();
execute(&mut session, "bake.run", &json!({"resolution": 32, "maps": ["ambientOcclusion"], "rays": 2, "cpu": true})).unwrap();
let pixels = &session.doc.baked[&0].maps[&BakedMap::AmbientOcclusion];
assert!(pixels[..32 * 32].iter().all(|value| *value == 0.25));
assert!(pixels[32 * 32..].iter().all(|value| *value > 0.99));
}
#[test]
fn excluded_tiles_without_previous_pixels_use_neutral_values() {
let mut session = session();
execute(&mut session, "bake.tile.set", &json!({"tile": 1001, "enabled": false})).unwrap();
execute(&mut session, "bake.run", &json!({"maps": ["normal", "ambientOcclusion"], "cpu": true})).unwrap();
let baked = &session.doc.baked[&0];
for map in [BakedMap::Normal, BakedMap::AmbientOcclusion] {
for row in baked.maps[&map].chunks_exact(64 * map.components()) {
for pixel in row[..32 * map.components()].chunks_exact(map.components()) {
assert_eq!(pixel, &map.neutral()[..map.components()]);
}
}
}
}
#[test]
fn no_selected_tiles_is_a_noop_and_old_projects_include_every_tile() {
let mut session = session();
let serialized = serde_json::to_value(&session.doc.project).unwrap();
assert!(serialized["texture_sets"][0].get("bake_excluded_tiles").is_none());
let legacy: texturecraft_engine::core::Project = serde_json::from_value(serialized).unwrap();
assert!(legacy.texture_sets[0].has_enabled_bake_tiles());
for tile in [1001, 1002] {
execute(&mut session, "bake.tile.set", &json!({"tile": tile, "enabled": false})).unwrap();
}
let before = session.doc.project.clone();
let history = session.history_labels();
let result = execute(&mut session, "bake.run", &json!({"ts": "selected", "cpu": true})).unwrap();
assert_eq!(result["baked"], json!([]));
assert_eq!(session.doc.project, before);
assert!(session.doc.baked.is_empty());
assert_eq!(session.history_labels(), history);
assert!(session.bake_task(0).is_err());
execute(&mut session, "textureSet.uvTiles", &json!({"enabled": false})).unwrap();
assert!(session.doc.project.texture_sets[0].bake_excluded_tiles.is_empty());
session.undo().unwrap();
assert_eq!(session.doc.project, before);
}
#[test]
#[ignore]
fn partial_bake_timing() {
let mut session = session();
execute(&mut session, "bake.run", &json!({"resolution": 256, "rays": 64, "cpu": true})).unwrap();
for enabled in [true, false] {
execute(&mut session, "bake.tile.set", &json!({"tile": 1002, "enabled": enabled})).unwrap();
let mut task = session.bake_task(0).unwrap();
task.tracer = None;
let mut times = Vec::new();
for _ in 0..5 {
let started = std::time::Instant::now();
task.run(&Progress::new()).unwrap();
times.push(started.elapsed());
}
times.sort();
eprintln!("{} of 2 UV tiles, 256 square, AO 64 rays, CPU: median {:?}, runs {:?}", if enabled { 2 } else { 1 }, times[2], times);
}
}
+16 -12
View File
@@ -48,20 +48,24 @@ fn paint_red_at(s: &mut Session, p: Vec3) {
#[test]
fn uv_tiles_are_detected_and_inspected() {
let mut s = session();
let set = execute(&mut s, "textureSet.inspect", &Value::Null).unwrap();
let mut session = session();
let set = execute(&mut session, "textureSet.inspect", &Value::Null).unwrap();
assert_eq!(set["uvTiles"], json!([1001, 1002]));
assert_eq!(set["size"], json!([2 * RES, RES]));
assert_eq!(set["tiles"], json!([{ "udim": 1001, "block": [0, 0], "resolution": RES }, { "udim": 1002, "block": [1, 0], "resolution": RES }]));
assert_eq!(s.caches[0].size, (2 * RES, RES));
// Explicit modes: classic on the UDIM plane, one tile on a 0..1 mesh.
execute(&mut s, "project.new", &json!({"mesh": "udim_plane", "resolution": RES, "uvTiles": false})).unwrap();
assert!(s.doc.project.texture_sets[0].uv_tiles.is_empty());
execute(&mut s, "project.new", &json!({"mesh": "plane", "resolution": RES})).unwrap();
assert!(s.doc.project.texture_sets[0].uv_tiles.is_empty(), "UVs in 0..1 stay classic");
execute(&mut s, "project.new", &json!({"mesh": "plane", "resolution": RES, "uvTiles": true})).unwrap();
assert_eq!(s.doc.project.texture_sets[0].uv_tiles, vec![1001]);
assert_eq!(s.caches[0].size, (RES, RES));
assert_eq!(
set["tiles"],
json!([{ "udim": 1001, "block": [0, 0], "resolution": RES, "bakeEnabled": true }, { "udim": 1002, "block": [1, 0], "resolution": RES, "bakeEnabled": true }])
);
assert_eq!(session.caches[0].size, (2 * RES, RES));
// Explicit modes: classic on the UDIM plane, one tile on a 0..1 mesh
execute(&mut session, "project.new", &json!({"mesh": "udim_plane", "resolution": RES, "uvTiles": false})).unwrap();
assert!(session.doc.project.texture_sets[0].uv_tiles.is_empty());
execute(&mut session, "project.new", &json!({"mesh": "plane", "resolution": RES})).unwrap();
assert!(session.doc.project.texture_sets[0].uv_tiles.is_empty(), "UVs in 0..1 stay classic");
execute(&mut session, "project.new", &json!({"mesh": "plane", "resolution": RES, "uvTiles": true})).unwrap();
assert_eq!(session.doc.project.texture_sets[0].uv_tiles, vec![1001]);
assert_eq!(session.caches[0].size, (RES, RES));
}
#[test]
+5
View File
@@ -145,6 +145,11 @@ pub fn load_project(path: &Path) -> Result<ProjectFile>; // native
allocated 64×64 tile `tx`, `ty` (u32 LE) and the raw `u16` LE components (sparse, lossless).
Baked maps: the same header with 0 tiles, then `width × height × components` f32 LE.
Project format version 2 stores baked maps in uniform UV tile blocks, independent of working
tile-resolution overrides. Older projects load their stored bake pixels as-is, without converting
the old layout; their appearance may change until rebaked. Painted layers and cage/skew correction
maps retain their working atlas layout.
Loading runs `Project::validate`, refuses a newer `format_version` (`FormatError::NewerVersion`),
checks every tile against its texture set's resolution and component count, rejects repeated or
out-of-range tiles and trailing data, drops pixels of layers that are in no stack, and caps the
+3 -1
View File
@@ -596,7 +596,9 @@ impl Sampler<'_> {
fn baked(&self, m: BakedMap, at: At) -> [f32; 3] {
match at {
At::Texel(x, y) if self.set.baked.contains(&m) => self.baked.sample(m, x, y, (self.res, self.comp.height)).unwrap_or(m.neutral()),
At::Texel(x, y) if self.set.baked.contains(&m) => {
self.baked.sample_working(m, x, y, (self.res, self.comp.height), &self.scales).unwrap_or(m.neutral())
}
_ => m.neutral(),
}
}
+2
View File
@@ -455,6 +455,8 @@ fn load<R: Read + Seek>(reader: R) -> Result<ProjectFile> {
// Ignore other entries from newer minor revisions
}
pf.project.format_version = FORMAT_VERSION;
if recovered {
pf.warnings.push(
"Warning: Some project settings or mesh maps could not be imported. TextureCraft recovered what it could, using defaults where needed.".into(),
+20
View File
@@ -82,6 +82,26 @@ fn round_trip_is_identical_and_deterministic() {
assert_same(&builtin, &load_project_bytes(&save_project_bytes(&builtin).unwrap()).unwrap());
}
#[test]
fn legacy_bakes_load_as_is_without_layout_conversion() {
let mut sample = sample();
sample.pf.project.format_version = 1;
sample.pf.pixels.layers.clear();
let set = &mut sample.pf.project.texture_sets[0];
set.resolution = 256;
set.uv_tiles = vec![1001, 1002];
set.tile_resolutions.insert(1002, 128);
let pixels: Vec<f32> = (0..16).flat_map(|y| (0..32).map(move |x| (y * 32 + x) as f32)).collect();
sample.pf.baked.insert(0, BakedMaps { resolution: 32, maps: [(BakedMap::AmbientOcclusion, Arc::new(pixels))].into() });
let loaded = load_project_bytes(&save_project_bytes(&sample.pf).unwrap()).unwrap();
assert_eq!(loaded.project.format_version, FORMAT_VERSION);
assert_eq!(loaded.baked, sample.pf.baked, "old bake pixels are accepted without preserving their former layout");
assert_eq!(loaded.bake_paint, sample.pf.bake_paint, "correction paint remains in the working layout");
let reopened = load_project_bytes(&save_project_bytes(&loaded).unwrap()).unwrap();
assert_same(&loaded, &reopened);
}
#[cfg(not(target_arch = "wasm32"))]
#[test]
fn save_and_load_through_files() {
+25 -6
View File
@@ -1,27 +1,46 @@
//! Debug textures for the mesh-map view.
use texturecraft_compose::BakedMaps;
use texturecraft_core::BakedMap;
use texturecraft_texel::linear_to_srgb;
use texturecraft_core::{BakedMap, BlockScales};
/// RGBA8 of baked map `m` resampled to `size × size` stretched over the map (mid gray where not
/// baked). Scalar maps are shown as grayscale; ID maps as their colors. Values are display
/// (sRGB) encoded.
pub fn mesh_map_rgba(baked: Option<&BakedMaps>, m: BakedMap, size: u32) -> Vec<u8> {
pub fn mesh_map_rgba(baked: Option<&BakedMaps>, m: BakedMap, size: u32, working_size: (u32, u32), scales: &BlockScales) -> Vec<u8> {
let size = size.max(1);
let mut out = vec![128u8; (size * size * 4) as usize];
let Some(b) = baked.filter(|b| b.maps.contains_key(&m)) else { return out };
for y in 0..size {
for x in 0..size {
let v = b.sample(m, x, y, (size, size)).unwrap_or([0.5; 3]);
let uv = [(x as f32 + 0.5) / size as f32, (y as f32 + 0.5) / size as f32];
let v = scales.bake_uv(uv, working_size).and_then(|uv| b.sample_uv(m, uv)).unwrap_or([0.5; 3]);
let i = ((y * size + x) * 4) as usize;
for k in 0..3 {
// Data maps are shown as stored, i.e. treated as display values.
// Data maps are shown as stored
out[i + k] = (v[k].clamp(0.0, 1.0) * 255.0 + 0.5) as u8;
}
out[i + 3] = 255;
}
}
let _ = linear_to_srgb;
out
}
#[cfg(test)]
mod tests {
use super::*;
use std::sync::Arc;
use texturecraft_core::TextureSet;
#[test]
fn mesh_map_preview_places_bake_detail_in_the_working_tile() {
let mut set = TextureSet::new("Tiles", 0, 256);
set.uv_tiles = vec![1001, 1002];
set.tile_resolutions.insert(1002, 128);
let pixels = (0..128).flat_map(|y| (0..256).map(move |x| ((x % 128) + y) as f32 / 255.0)).collect();
let baked = BakedMaps { resolution: 256, maps: [(BakedMap::AmbientOcclusion, Arc::new(pixels))].into() };
let preview = mesh_map_rgba(Some(&baked), BakedMap::AmbientOcclusion, 512, set.size(), &set.block_scales());
assert_eq!(preview[(240 * 512 + 376) * 4], 240);
assert_eq!(preview[(400 * 512 + 500) * 4], 128, "unused working block area stays neutral");
}
}
-112
View File
@@ -1,112 +0,0 @@
//! Bake Mode presentation; persisted settings live in core and edits use engine commands
mod bake_paint_brush;
mod breadcrumb;
mod common_settings;
pub use bake_paint_brush::BakePaintBrush;
mod controls;
mod map_settings;
mod mesh_map_bakers;
use egui::{Ui, vec2};
use serde_json::json;
use texturecraft_engine::core::{BakeSettings, BakedMap};
use crate::TextureCraftApp;
use crate::i18n::{tr, trf};
use crate::state::Mode;
use crate::widgets::primary_button;
pub fn texture_sets(app: &mut TextureCraftApp, ui: &mut Ui) {
egui::ScrollArea::vertical().id_salt("bake_texture_sets").auto_shrink([false; 2]).show(ui, |ui| {
for set_index in 0..app.session.set_count() {
let Some(texture_set) = app.session.doc.project.texture_sets.get(set_index) else { continue };
let name = texture_set.name.clone();
let (width, height) = texture_set.bake.common.output_size();
let mut is_enabled = texture_set.bake.common.is_enabled;
ui.push_id(set_index, |ui| {
ui.horizontal(|ui| {
if ui.checkbox(&mut is_enabled, "").on_hover_text(tr("Include in Bake")).changed() {
app.run("bake.settings", json!({ "ts": set_index, "enabled": is_enabled }));
}
if ui.selectable_label(set_index == app.session.ts(), format!("{name} ({width} × {height})")).clicked() {
app.run("textureSet.select", json!({ "ts": set_index }));
}
});
});
}
});
}
/// The Mesh Map Bakers panel: which maps bake and which one Mesh Map Settings shows
pub fn mesh_map_bakers_panel(app: &mut TextureCraftApp, ui: &mut Ui) {
edit_settings(app, ui, "mesh_map_bakers", mesh_map_bakers::show);
}
/// The Mesh Map Settings panel: the breadcrumb, then the selected map's parameters
pub fn mesh_map_settings_panel(app: &mut TextureCraftApp, ui: &mut Ui) {
let Some(texture_set) = app.session.doc.project.texture_sets.get(app.session.ts()) else { return };
let selected = selected_map(app.ui.selected_baked_map, &texture_set.bake);
breadcrumb::show(app, ui, selected);
ui.separator();
edit_settings(app, ui, "mesh_map_settings", |_, ui, settings| ui.push_id(selected, |ui| map_settings::show(ui, selected, &mut settings.maps)).inner);
}
/// The Common Settings panel: output, high poly, cage and skew settings
pub fn common_settings_panel(app: &mut TextureCraftApp, ui: &mut Ui) {
edit_settings(app, ui, "bake_common_settings", common_settings::show);
}
/// The map whose settings show: the chosen one, else the first enabled map, else Normal
fn selected_map(selection: Option<BakedMap>, settings: &BakeSettings) -> BakedMap {
selection.or_else(|| settings.maps.enabled().next()).unwrap_or(BakedMap::Normal)
}
/// Draw `contents` over a copy of the active set's bake settings and run `bake.settings` on change
fn edit_settings(app: &mut TextureCraftApp, ui: &mut Ui, scroll_id: &str, contents: impl FnOnce(&mut TextureCraftApp, &mut Ui, &mut BakeSettings)) {
let set_index = app.session.ts();
let Some(before) = app.session.doc.project.texture_sets.get(set_index).map(|texture_set| texture_set.bake.clone()) else { return };
let mut settings = before.clone();
egui::ScrollArea::vertical().id_salt(scroll_id).auto_shrink([false; 2]).show(ui, |ui| contents(app, ui, &mut settings));
if settings != before {
app.run("bake.settings", json!({ "ts": set_index, "model": settings }));
}
}
pub(crate) fn bake_bar(app: &mut TextureCraftApp, ctx: &egui::Context, viewport: egui::Rect) {
egui::Area::new(egui::Id::unique("bake_bar")).constrain_to(viewport).anchor(egui::Align2::CENTER_BOTTOM, vec2(0.0, -16.0)).default_width(0.0).show(
ctx,
|ui| {
ui.horizontal(|ui| {
if let Some(progress) = app.bake_progress() {
ui.add(egui::ProgressBar::new(progress).desired_width(220.0).show_percentage());
if ui.button(tr("Cancel")).clicked() {
app.cancel_bake();
}
} else {
let texture_sets: Vec<usize> = app
.session
.doc
.project
.texture_sets
.iter()
.enumerate()
.filter(|(_, texture_set)| texture_set.bake.common.is_enabled)
.map(|(index, _)| index)
.collect();
let label = trf("Bake Selected Textures ({n})", &[("n", &texture_sets.len())]);
if ui.add_enabled(!texture_sets.is_empty(), primary_button(ui, &label)).clicked() {
app.start_bake(texture_sets);
}
}
if ui.button(tr("Return to Painting Mode")).clicked() {
app.ui.mode = Mode::Painting;
}
});
},
);
}
@@ -4,13 +4,14 @@ use crate::i18n::tr;
use crate::widgets::icon_button;
use egui::Ui;
use egui_phosphor::regular as icon;
use serde_json::json;
use serde_json::{Map, Value, json};
use texturecraft_engine::core::{
BakeAntialiasing, BakePaintTarget, BakeResolution, BakeSettings, CageType, CommonBakeSettings, MeshMatchMode, SkewCorrectionMethod,
};
/// The output and high-poly sections, then cage (needs a high poly) and skew (needs a distance cage)
pub(super) fn show(app: &mut TextureCraftApp, ui: &mut Ui, settings: &mut BakeSettings) {
pub(super) fn show(app: &mut TextureCraftApp, ui: &mut Ui, settings: &mut BakeSettings) -> Option<Value> {
let mut reset = Map::new();
ui.push_id("common", |ui| {
// Restore Defaults keeps whether the texture set is included in the bake
let is_enabled = settings.common.is_enabled;
@@ -31,6 +32,11 @@ pub(super) fn show(app: &mut TextureCraftApp, ui: &mut Ui, settings: &mut BakeSe
ui.checkbox(&mut settings.common.apply_diffusion, tr("Apply Diffusion"));
}) {
settings.common = CommonBakeSettings { is_enabled, ..CommonBakeSettings::default() };
let mut defaults = json!(settings.common);
if let Some(fields) = defaults.as_object_mut() {
fields.remove("is_enabled");
}
reset.insert("common".into(), defaults);
}
});
@@ -53,6 +59,7 @@ pub(super) fn show(app: &mut TextureCraftApp, ui: &mut Ui, settings: &mut BakeSe
}
}) {
settings.high_poly = Default::default();
reset.insert("high_poly".into(), json!(settings.high_poly));
}
});
@@ -78,6 +85,7 @@ pub(super) fn show(app: &mut TextureCraftApp, ui: &mut Ui, settings: &mut BakeSe
}
}) {
settings.cage = Default::default();
reset.insert("cage".into(), json!(settings.cage));
}
});
@@ -100,10 +108,13 @@ pub(super) fn show(app: &mut TextureCraftApp, ui: &mut Ui, settings: &mut BakeSe
number(ui, tr("Edge Contrast"), &mut settings.skew.edge_contrast, 0.0..=1.0, 2);
}) {
settings.skew = Default::default();
reset.insert("skew".into(), json!(settings.skew));
}
});
}
}
(!reset.is_empty()).then_some(Value::Object(reset))
}
fn output_size(ui: &mut Ui, settings: &mut CommonBakeSettings) {
+17 -10
View File
@@ -1,6 +1,8 @@
use super::controls::{choice, hint, integer, number};
use crate::i18n::tr;
use egui::Ui;
use serde::Serialize;
use serde_json::{Value, json};
use texturecraft_engine::core::{
AmbientOcclusionAttenuation, AmbientOcclusionSettings, BackfaceMode, BakedMap, BentNormalSettings, CurvatureMethod, CurvatureSettings, HeightNormalization,
HeightSettings, IdColorGenerator, IdColorSource, IdSettings, MeshMapSettings, PositionAxis, PositionMode, PositionNormalizationScale, PositionSettings,
@@ -8,28 +10,33 @@ use texturecraft_engine::core::{
};
/// Draw `map`'s parameters with Restore Defaults; maps without parameters say so
pub(super) fn show(ui: &mut Ui, map: BakedMap, settings: &mut MeshMapSettings) {
pub(super) fn show(ui: &mut Ui, map: BakedMap, settings: &mut MeshMapSettings) -> Option<Value> {
match map {
BakedMap::Normal | BakedMap::WorldNormal | BakedMap::Opacity => hint(ui, tr("No Parameters")),
BakedMap::Id => parameters(ui, &mut settings.id.parameters, id),
BakedMap::AmbientOcclusion => parameters(ui, &mut settings.ao.parameters, ambient_occlusion),
BakedMap::Curvature => parameters(ui, &mut settings.curvature.parameters, curvature),
BakedMap::Position => parameters(ui, &mut settings.position.parameters, position),
BakedMap::Thickness => parameters(ui, &mut settings.thickness.parameters, thickness),
BakedMap::Height => parameters(ui, &mut settings.height.parameters, height),
BakedMap::BentNormal => parameters(ui, &mut settings.bent_normal.parameters, bent_normal),
BakedMap::Normal | BakedMap::WorldNormal | BakedMap::Opacity => {
hint(ui, tr("No Parameters"));
None
}
BakedMap::Id => parameters(ui, "id", &mut settings.id.parameters, id),
BakedMap::AmbientOcclusion => parameters(ui, "ao", &mut settings.ao.parameters, ambient_occlusion),
BakedMap::Curvature => parameters(ui, "curvature", &mut settings.curvature.parameters, curvature),
BakedMap::Position => parameters(ui, "position", &mut settings.position.parameters, position),
BakedMap::Thickness => parameters(ui, "thickness", &mut settings.thickness.parameters, thickness),
BakedMap::Height => parameters(ui, "height", &mut settings.height.parameters, height),
BakedMap::BentNormal => parameters(ui, "bent_normal", &mut settings.bent_normal.parameters, bent_normal),
}
}
/// A map's controls, then a right-aligned Restore Defaults that resets only its parameters
fn parameters<T: Default>(ui: &mut Ui, parameters: &mut T, controls: impl FnOnce(&mut Ui, &mut T)) {
fn parameters<T: Default + Serialize>(ui: &mut Ui, map_key: &str, parameters: &mut T, controls: impl FnOnce(&mut Ui, &mut T)) -> Option<Value> {
controls(ui, parameters);
ui.add_space(6.0);
let restore = ui.with_layout(egui::Layout::right_to_left(egui::Align::Min), |ui| ui.button(tr("Restore Defaults"))).inner;
if restore.clicked() {
*parameters = T::default();
return Some(json!({"maps": {map_key: {"parameters": parameters}}}));
}
None
}
fn id(ui: &mut Ui, settings: &mut IdSettings) {
+216
View File
@@ -0,0 +1,216 @@
//! Bake Mode presentation; persisted settings live in core and edits use engine commands
mod bake_paint_brush;
mod breadcrumb;
mod common_settings;
pub use bake_paint_brush::BakePaintBrush;
mod controls;
mod map_settings;
mod mesh_map_bakers;
use egui::{Ui, vec2};
use egui_phosphor::regular as icon;
use serde_json::{Value, json};
use texturecraft_engine::bake::settings_patch;
use texturecraft_engine::core::{BakeSettings, BakedMap};
use crate::TextureCraftApp;
use crate::i18n::{tr, trf};
use crate::state::Mode;
use crate::widgets::{icon_button, primary_button};
pub fn texture_sets(app: &mut TextureCraftApp, ui: &mut Ui) {
egui::ScrollArea::vertical().id_salt("bake_texture_sets").auto_shrink([false; 2]).show(ui, |ui| {
for set_index in 0..app.session.set_count() {
let Some(texture_set) = app.session.doc.project.texture_sets.get(set_index) else { continue };
let name = texture_set.name.clone();
let resolution = texture_set.resolution;
let mut is_enabled = texture_set.bake.common.is_enabled;
let visible = texture_set.visible;
let tiles: Vec<_> = texture_set
.uv_tiles
.iter()
.map(|tile| (*tile, texture_set.tile_resolutions.get(tile).copied(), !texture_set.bake_excluded_tiles.contains(tile)))
.collect();
ui.push_id(set_index, |ui| {
ui.horizontal(|ui| {
let button_size = ui.spacing().interact_size.y;
if icon_button(ui, if visible { icon::EYE } else { icon::EYE_SLASH }, tr("Show or hide the texture set"), false, button_size).clicked() {
app.run("textureSet.visible", json!({ "ts": set_index }));
}
if ui.checkbox(&mut is_enabled, "").on_hover_text(tr("Include in Bake")).changed() {
app.run("bake.settings", json!({ "ts": set_index, "enabled": is_enabled }));
}
ui.with_layout(egui::Layout::right_to_left(egui::Align::Center), |ui| {
if let Some(selected) = resolution_menu(ui, tr("Texture set resolution"), format!("{resolution} × {resolution}"), resolution, None)
&& selected != resolution
{
app.start_resize(set_index, selected);
}
ui.with_layout(egui::Layout::left_to_right(egui::Align::Center), |ui| {
if ui.add(egui::Button::selectable(set_index == app.session.ts(), &name).truncate()).on_hover_text(&name).clicked() {
app.run("textureSet.select", json!({ "ts": set_index }));
}
});
});
});
if !tiles.is_empty() {
egui::CollapsingHeader::new(format!("{} ({})", tr("UV tiles (UDIM)"), tiles.len())).default_open(true).show(ui, |ui| {
for (tile, override_resolution, enabled) in &tiles {
let mut enabled = *enabled;
ui.push_id(tile, |ui| {
ui.horizontal(|ui| {
if ui.checkbox(&mut enabled, tile.to_string()).on_hover_text(tr("Include in Bake")).changed() {
app.run("bake.tile.set", json!({"ts": set_index, "tile": tile, "enabled": enabled}));
}
ui.with_layout(egui::Layout::right_to_left(egui::Align::Center), |ui| {
let text = override_resolution.map(|value| format!("{value} × {value}*")).unwrap_or_default();
let label = trf("UV tile {tile} resolution", &[("tile", &tile.to_string())]);
if let Some(selected) = resolution_menu(
ui,
&label,
text,
override_resolution.unwrap_or(resolution),
override_resolution.map(|_| resolution),
) {
app.run("textureSet.tile.resolution", json!({"ts": set_index, "tile": tile, "resolution": selected}));
}
});
})
});
}
});
}
});
}
});
}
fn resolution_menu(ui: &mut Ui, label: &str, text: String, resolution: u32, inherited_resolution: Option<u32>) -> Option<u32> {
let effective_size = format!("{resolution} × {resolution}");
let measured = if text.is_empty() { &effective_size } else { &text };
let font = egui::TextStyle::Button.resolve(ui.style());
let text_width = ui.painter().layout_no_wrap(measured.clone(), font.clone(), ui.visuals().text_color()).size().x;
let width = text_width + ui.spacing().button_padding.x * 2.0;
let response = ui.add_sized([width, ui.spacing().interact_size.y], egui::Button::new("").frame(false));
let popup_id = response.id.with("resolution_menu");
let open = egui::Popup::is_id_open(ui.ctx(), popup_id) || response.clicked();
let shown = if text.is_empty() && (response.hovered() || open) { effective_size } else { text };
ui.painter().text(response.rect.center(), egui::Align2::CENTER_CENTER, &shown, font, ui.style().interact(&response).text_color());
let mut selected = None;
egui::Popup::menu(&response).id(popup_id).show(|ui| {
if let Some(inherited) = inherited_resolution {
if ui.button(tr("Remove resolution override")).clicked() {
selected = Some(inherited);
ui.close();
}
ui.separator();
}
for candidate in [128, 256, 512, 1024, 2048, 4096, 8192] {
if ui.selectable_label(candidate == resolution, format!("{candidate} × {candidate}")).clicked() {
selected = Some(candidate);
}
}
});
response.widget_info(|| {
let mut info = egui::WidgetInfo::labeled(egui::Role::ComboBox, ui.is_enabled(), label);
info.current_text_value = Some(shown.clone());
info
});
response.on_hover_text(label);
selected
}
/// The Mesh Map Bakers panel: which maps bake and which one Mesh Map Settings shows
pub fn mesh_map_bakers_panel(app: &mut TextureCraftApp, ui: &mut Ui) {
let texture_set = json!(app.session.ts());
edit_settings(app, ui, "mesh_map_bakers", texture_set, |app, ui, settings| {
mesh_map_bakers::show(app, ui, settings);
None
});
}
/// The Mesh Map Settings panel: the breadcrumb, then the selected map's parameters
pub fn mesh_map_settings_panel(app: &mut TextureCraftApp, ui: &mut Ui) {
let Some(texture_set) = app.session.doc.project.texture_sets.get(app.session.ts()) else { return };
let selected = selected_map(app.ui.selected_baked_map, &texture_set.bake);
breadcrumb::show(app, ui, selected);
ui.separator();
edit_settings(app, ui, "mesh_map_settings", json!("all"), |_, ui, settings| {
ui.push_id(selected, |ui| map_settings::show(ui, selected, &mut settings.maps)).inner
});
}
/// The Common Settings panel: output, high poly, cage and skew settings
pub fn common_settings_panel(app: &mut TextureCraftApp, ui: &mut Ui) {
edit_settings(app, ui, "bake_common_settings", json!("all"), common_settings::show);
}
/// The map whose settings show: the chosen one, else the first enabled map, else Normal
fn selected_map(selection: Option<BakedMap>, settings: &BakeSettings) -> BakedMap {
selection.or_else(|| settings.maps.enabled().next()).unwrap_or(BakedMap::Normal)
}
/// Send changed fields and explicitly reset sections through the same undoable command
fn edit_settings(
app: &mut TextureCraftApp,
ui: &mut Ui,
scroll_id: &str,
texture_sets: Value,
contents: impl FnOnce(&mut TextureCraftApp, &mut Ui, &mut BakeSettings) -> Option<Value>,
) {
let set_index = app.session.ts();
let Some(before) = app.session.doc.project.texture_sets.get(set_index).map(|texture_set| texture_set.bake.clone()) else { return };
let mut settings = before.clone();
let reset = egui::ScrollArea::vertical().id_salt(scroll_id).auto_shrink([false; 2]).show(ui, |ui| contents(app, ui, &mut settings)).inner;
if settings == before && reset.is_none() {
return;
}
let mut patch = settings_patch(&before, &settings);
if let (Some(fields), Some(Value::Object(reset))) = (patch.as_object_mut(), reset) {
fields.extend(reset);
}
app.run("bake.settings", json!({ "ts": texture_sets, "patch": patch }));
}
pub(crate) fn bake_bar(app: &mut TextureCraftApp, ctx: &egui::Context, viewport: egui::Rect) {
egui::Area::new(egui::Id::unique("bake_bar")).constrain_to(viewport).anchor(egui::Align2::CENTER_BOTTOM, vec2(0.0, -16.0)).default_width(0.0).show(
ctx,
|ui| {
ui.horizontal(|ui| {
if let Some(progress) = app.bake_progress() {
ui.add(egui::ProgressBar::new(progress).desired_width(220.0).show_percentage());
if ui.button(tr("Cancel")).clicked() {
app.cancel_bake();
}
} else {
let texture_sets: Vec<usize> = app
.session
.doc
.project
.texture_sets
.iter()
.enumerate()
.filter(|(_, texture_set)| texture_set.bake.common.is_enabled && texture_set.has_enabled_bake_tiles())
.map(|(index, _)| index)
.collect();
let label = trf("Bake Selected Textures ({n})", &[("n", &texture_sets.len())]);
if ui.add_enabled(!texture_sets.is_empty(), primary_button(ui, &label)).clicked() {
app.start_bake(texture_sets);
}
}
if ui.button(tr("Return to Painting Mode")).clicked() {
app.ui.mode = Mode::Painting;
}
});
},
);
}
+8 -2
View File
@@ -216,8 +216,14 @@ impl GpuLink {
if self.aux.get(&ts) == Some(&key) {
continue;
}
let res = s.caches.get(ts).map_or(1024, |c| texturecraft_render::aux_size(c.size));
out.aux.push((ts, res, texturecraft_render::mesh_maps::mesh_map_rgba(s.doc.baked.get(&ts), m, res)));
let Some(cache) = s.caches.get(ts) else { continue };
let res = texturecraft_render::aux_size(cache.size);
out.aux.push((
ts,
res,
texturecraft_render::mesh_maps::mesh_map_rgba(s.doc.baked.get(&ts), m, res, cache.size, &cache.composite.block_scales),
));
self.aux.insert(ts, key);
}
}
+3
View File
@@ -1032,4 +1032,7 @@ pub const TABLE: &[(&str, &str)] = &[
("Value Bounds Max", "الحد الأقصى للقيمة"),
("Value Bounds Min", "الحد الأدنى للقيمة"),
("Vertex Color", "لون الرأس"),
("Remove resolution override", "إزالة تجاوز الدقة"),
("Texture set resolution", "دقة مجموعة الخامات"),
("UV tile {tile} resolution", "دقة بلاطة UV {tile}"),
];
+3
View File
@@ -1075,4 +1075,7 @@ pub const TABLE: &[(&str, &str)] = &[
("Value Bounds Max", "Maximaler Grenzwert"),
("Value Bounds Min", "Minimaler Grenzwert"),
("Vertex Color", "Scheitelpunktfarbe"),
("Remove resolution override", "Auflösungsüberschreibung entfernen"),
("Texture set resolution", "Auflösung des Textursets"),
("UV tile {tile} resolution", "Auflösung der UV-Kachel {tile}"),
];
+3
View File
@@ -1060,4 +1060,7 @@ pub const TABLE: &[(&str, &str)] = &[
("Value Bounds Max", "Límite máximo"),
("Value Bounds Min", "Límite mínimo"),
("Vertex Color", "Color de vértice"),
("Remove resolution override", "Quitar resolución personalizada"),
("Texture set resolution", "Resolución del conjunto de texturas"),
("UV tile {tile} resolution", "Resolución del mosaico UV {tile}"),
];
+3
View File
@@ -1084,4 +1084,7 @@ pub const TABLE: &[(&str, &str)] = &[
("Value Bounds Max", "Borne maximale"),
("Value Bounds Min", "Borne minimale"),
("Vertex Color", "Couleur des sommets"),
("Remove resolution override", "Supprimer la résolution personnalisée"),
("Texture set resolution", "Résolution de l'ensemble de textures"),
("UV tile {tile} resolution", "Résolution de la tuile UV {tile}"),
];
+3
View File
@@ -1069,4 +1069,7 @@ pub const TABLE: &[(&str, &str)] = &[
("Value Bounds Max", "Limite massimo"),
("Value Bounds Min", "Limite minimo"),
("Vertex Color", "Colore dei vertici"),
("Remove resolution override", "Rimuovi risoluzione personalizzata"),
("Texture set resolution", "Risoluzione del set di texture"),
("UV tile {tile} resolution", "Risoluzione del tile UV {tile}"),
];
+3
View File
@@ -1054,4 +1054,7 @@ pub const TABLE: &[(&str, &str)] = &[
("Value Bounds Max", "値の上限"),
("Value Bounds Min", "値の下限"),
("Vertex Color", "頂点カラー"),
("Remove resolution override", "解像度の上書きを解除"),
("Texture set resolution", "テクスチャセットの解像度"),
("UV tile {tile} resolution", "UVタイル {tile} の解像度"),
];
+3
View File
@@ -1042,4 +1042,7 @@ pub const TABLE: &[(&str, &str)] = &[
("Value Bounds Max", "값 상한"),
("Value Bounds Min", "값 하한"),
("Vertex Color", "정점 색상"),
("Remove resolution override", "해상도 재정의 제거"),
("Texture set resolution", "텍스처 세트 해상도"),
("UV tile {tile} resolution", "UV 타일 {tile} 해상도"),
];
+3
View File
@@ -1057,4 +1057,7 @@ pub const TABLE: &[(&str, &str)] = &[
("Value Bounds Max", "Limite máximo"),
("Value Bounds Min", "Limite mínimo"),
("Vertex Color", "Cor do vértice"),
("Remove resolution override", "Remover resolução personalizada"),
("Texture set resolution", "Resolução do conjunto de texturas"),
("UV tile {tile} resolution", "Resolução do tile UV {tile}"),
];
+3
View File
@@ -1000,4 +1000,7 @@ pub const TABLE: &[(&str, &str)] = &[
("Value Bounds Max", "值上限"),
("Value Bounds Min", "值下限"),
("Vertex Color", "顶点颜色"),
("Remove resolution override", "移除分辨率覆盖"),
("Texture set resolution", "纹理集分辨率"),
("UV tile {tile} resolution", "UV 图块 {tile} 的分辨率"),
];
+1 -1
View File
@@ -134,7 +134,7 @@ impl TextureCraftApp {
theme::install(&cc.egui_ctx);
// Bakes cast their rays on a GPU device of their own (created on the first bake).
#[cfg(not(target_arch = "wasm32"))]
texturecraft_engine::bake_cmds::install_gpu_tracer(Arc::new(texturecraft_render::gpu_bake::GpuBaker::new()));
texturecraft_engine::bake::install_gpu_tracer(Arc::new(texturecraft_render::gpu_bake::GpuBaker::new()));
let gpu = cc.wgpu_render_state.as_ref().map(|rs| gpu::init(rs, &cc.egui_ctx));
// The first run speaks the OS (or browser) language.
let ui = cc.storage.and_then(|s| eframe::get_value::<UiState>(s, "ui")).unwrap_or_else(|| {
+301 -1
View File
@@ -1,7 +1,7 @@
use egui::Role;
use egui_kittest::Harness;
use egui_kittest::kittest::{NodeT, Queryable};
use texturecraft_engine::core::{BakeResolution, BakedMap, CageType, CurvatureMethod, HeightNormalization};
use texturecraft_engine::core::{BakeResolution, BakeSettings, BakedMap, CageType, CurvatureMethod, HeightNormalization};
use texturecraft_ui_egui::TextureCraftApp;
use texturecraft_ui_egui::docking::Panel;
use texturecraft_ui_egui::state::Mode;
@@ -45,6 +45,306 @@ fn click(harness: &mut Harness<'_, TextureCraftApp>, label: &str) {
harness.run_steps(3);
}
fn number_field<'a>(harness: &'a Harness<'_, TextureCraftApp>, label: &str) -> egui_kittest::Node<'a> {
let label_row = harness.get_by_label(label).rect().center().y;
harness.get_all_by_role(Role::TextInput).find(|node| (node.rect().center().y - label_row).abs() < 4.0).unwrap()
}
#[test]
fn mesh_map_edits_update_all_sets_without_copying_unedited_fields() {
let mut harness = harness(Some(BakedMap::AmbientOcclusion));
let session = &mut harness.state_mut().session;
assert_eq!(session.set_count(), 2);
let second = &mut session.doc.project.texture_sets[1].bake;
*second = BakeSettings::default();
second.common.is_enabled = false;
second.common.resolution = BakeResolution::R128;
second.common.resolution_height = Some(BakeResolution::R256);
second.maps.ao.is_enabled = false;
second.maps.ao.parameters.rays.rays = 16;
second.maps.ao.parameters.ground_plane.offset = 3.0;
second.maps.height.parameters.scaling_divisor = 2.0;
let before = session.doc.project.clone();
let history_steps = session.history_labels().len();
click_checkbox(&mut harness, "Ground Plane");
let mut expected = before.clone();
for texture_set in &mut expected.texture_sets {
texture_set.bake.maps.ao.parameters.ground_plane.enabled = true;
}
let session = &mut harness.state_mut().session;
assert_eq!(session.doc.project, expected);
assert_eq!(session.history_labels().len(), history_steps + 1);
session.undo().unwrap();
assert_eq!(session.doc.project, before);
session.redo().unwrap();
assert_eq!(session.doc.project, expected);
}
#[test]
fn common_settings_edits_update_all_sets_and_keep_their_map_selection() {
let mut harness = harness(Some(BakedMap::AmbientOcclusion));
let session = &mut harness.state_mut().session;
let second = &mut session.doc.project.texture_sets[1].bake;
*second = BakeSettings::default();
second.common.is_enabled = false;
second.common.resolution = BakeResolution::R128;
second.maps.select([BakedMap::Height]);
let before = session.doc.project.clone();
harness.state_mut().ui.dock.focus(Panel::CommonSettings);
harness.run_steps(3);
click_checkbox(&mut harness, "Apply Diffusion");
let mut expected = before.clone();
for texture_set in &mut expected.texture_sets {
texture_set.bake.common.apply_diffusion = false;
}
assert_eq!(harness.state().session.doc.project, expected);
harness.get_all_by_value("64").next().unwrap().click();
harness.run_steps(3);
click(&mut harness, "256");
for texture_set in &mut expected.texture_sets {
texture_set.bake.common.resolution = BakeResolution::R256;
}
assert_eq!(harness.state().session.doc.project, expected);
click_checkbox(&mut harness, "Use Low Poly Mesh as High Poly Mesh");
for texture_set in &mut expected.texture_sets {
texture_set.bake.high_poly.use_low_as_high = true;
}
assert_eq!(harness.state().session.doc.project, expected);
}
#[test]
fn secondary_rays_edit_from_another_set_updates_all_sets() {
let mut harness = harness(Some(BakedMap::AmbientOcclusion));
let session = &mut harness.state_mut().session;
session.doc.project.texture_sets[1].bake = BakeSettings::default();
session.doc.project.texture_sets[1].bake.maps.ao.parameters.rays.rays = 16;
texturecraft_engine::execute(session, "textureSet.select", &serde_json::json!({"ts": 1})).unwrap();
harness.run_steps(3);
select_map(&mut harness, "Ambient Occlusion");
let history_steps = harness.state().session.history_labels().len();
number_field(&harness, "Secondary Rays").focus();
harness.run_steps(2);
harness.key_press_modifiers(egui::Modifiers::COMMAND, egui::Key::A);
harness.run_steps(1);
number_field(&harness, "Secondary Rays").type_text("128");
harness.run_steps(1);
harness.key_press(egui::Key::Enter);
harness.run_steps(3);
let session = &harness.state().session;
assert_eq!(session.ts(), 1);
for texture_set in &session.doc.project.texture_sets {
assert_eq!(texture_set.bake.maps.ao.parameters.rays.rays, 128);
}
assert_eq!(session.history_labels().len(), history_steps + 1);
}
#[test]
fn map_selection_stays_per_set() {
let mut harness = harness(Some(BakedMap::AmbientOcclusion));
let second = harness.state().session.doc.project.texture_sets[1].bake.clone();
click_checkbox(&mut harness, "Ambient Occlusion");
assert!(enabled_maps(&harness).is_empty());
assert_eq!(harness.state().session.doc.project.texture_sets[1].bake, second);
click_checkbox(&mut harness, "Check All");
assert_eq!(enabled_maps(&harness), BakedMap::ALL);
assert_eq!(harness.state().session.doc.project.texture_sets[1].bake, second);
}
#[test]
fn bake_texture_set_visibility_is_independent_of_bake_selection() {
let mut harness = harness(Some(BakedMap::AmbientOcclusion));
let before: Vec<_> = harness.state().session.doc.project.texture_sets.iter().map(|texture_set| texture_set.bake.clone()).collect();
let active_set = harness.state().session.ts();
harness.get_all_by_label("Show or hide the texture set").nth(1).unwrap().click();
harness.run_steps(3);
let session = &harness.state().session;
assert!(session.doc.project.texture_sets[0].visible);
assert!(!session.doc.project.texture_sets[1].visible);
assert_eq!(session.ts(), active_set);
for (texture_set, settings) in session.doc.project.texture_sets.iter().zip(&before) {
assert_eq!(&texture_set.bake, settings);
}
harness.get_all_by_label("Show or hide the texture set").nth(1).unwrap().click();
harness.run_steps(3);
assert!(harness.state().session.doc.project.texture_sets[1].visible);
}
#[test]
fn texture_set_resolution_controls_are_independent_from_bake_output() {
let mut harness = harness(Some(BakedMap::AmbientOcclusion));
let before = harness.state().session.doc.project.clone();
let active_set = harness.state().session.ts();
harness.get_all_by_value("256 × 256").nth(1).unwrap().click();
harness.run_steps(3);
click(&mut harness, "128 × 128");
wait_for_resolution(&mut harness, 1, 128);
let session = &harness.state().session;
assert_eq!(session.ts(), active_set);
assert_eq!(session.doc.project.texture_sets[0], before.texture_sets[0]);
assert_eq!(session.doc.project.texture_sets[1].bake, before.texture_sets[1].bake);
harness.state_mut().session.undo().unwrap();
assert_eq!(harness.state().session.doc.project, before);
}
fn wait_for_resolution(harness: &mut Harness<'_, TextureCraftApp>, texture_set: usize, resolution: u32) {
for _ in 0..100 {
harness.run_steps(1);
if harness.state().session.doc.project.texture_sets[texture_set].resolution == resolution {
return;
}
std::thread::sleep(std::time::Duration::from_millis(5));
}
panic!("texture set resize did not finish");
}
#[test]
fn tile_resolution_overrides_can_be_changed_and_removed_in_bake_mode() {
let session = texturecraft_engine::Session::new_project(
"Tile resolution controls",
texturecraft_engine::geom::primitives::udim_plane(),
"builtin:udim_plane",
None,
256,
)
.unwrap();
let mut harness = Harness::builder().with_size(egui::vec2(1600.0, 1500.0)).build_eframe(|context| TextureCraftApp::new(context, session));
harness.state_mut().ui.mode = Mode::Baking;
harness.run_steps(4);
let before = harness.state().session.doc.project.clone();
assert_eq!(harness.get_all_by_value("256 × 256").count(), 1);
let resolution_position = harness.get_by_label("UV tile 1002 resolution").rect().center();
harness.hover_at(resolution_position);
harness.run_steps(3);
assert_eq!(harness.get_all_by_value("256 × 256").count(), 2);
harness.hover_at(egui::pos2(900.0, 500.0));
harness.run_steps(3);
assert_eq!(harness.get_all_by_value("256 × 256").count(), 1);
harness.get_by_label("UV tile 1002 resolution").click();
harness.run_steps(3);
click(&mut harness, "128 × 128");
harness.get_by_value("128 × 128*");
let texture_set = &harness.state().session.doc.project.texture_sets[0];
assert_eq!(texture_set.resolution, 256);
assert_eq!(texture_set.tile_resolution(1001), 256);
assert_eq!(texture_set.tile_resolution(1002), 128);
assert_eq!(texture_set.bake, before.texture_sets[0].bake);
harness.get_by_value("128 × 128*").click();
harness.run_steps(3);
click(&mut harness, "Remove resolution override");
assert_eq!(harness.state().session.doc.project, before);
assert!(harness.query_by_value("128 × 128*").is_none());
assert_eq!(harness.get_all_by_value("256 × 256").count(), 1);
harness.state_mut().session.undo().unwrap();
harness.run_steps(3);
harness.get_by_value("128 × 128*");
harness.state_mut().ui.dock.focus(Panel::CommonSettings);
harness.run_steps(3);
harness.get_all_by_value("2048").next().unwrap().click();
harness.run_steps(3);
click(&mut harness, "64");
let texture_set = &harness.state().session.doc.project.texture_sets[0];
assert_eq!(texture_set.resolution, 256);
assert_eq!(texture_set.tile_resolution(1002), 128);
assert_eq!(texture_set.bake.common.resolution, BakeResolution::R64);
}
#[test]
fn bake_texture_sets_list_uv_tiles_and_their_resolutions() {
let mut session =
texturecraft_engine::Session::new_project("UV tile list", texturecraft_engine::geom::primitives::udim_plane(), "builtin:udim_plane", None, 256)
.unwrap();
texturecraft_engine::execute(&mut session, "textureSet.tile.resolution", &serde_json::json!({"tile": 1002, "resolution": 128})).unwrap();
let before = session.doc.project.clone();
let mut harness = Harness::builder().with_size(egui::vec2(1600.0, 1500.0)).build_eframe(|context| TextureCraftApp::new(context, session));
harness.state_mut().ui.mode = Mode::Baking;
harness.run_steps(4);
harness.get_by_label("1001");
harness.get_by_value("256 × 256");
harness.get_by_label("1002");
harness.get_by_value("128 × 128*");
click_checkbox(&mut harness, "1002");
assert!(harness.state().session.doc.project.texture_sets[0].bake_excluded_tiles.contains(&1002));
assert!(!harness.get_by_label("Bake Selected Textures (1)").accesskit_node().is_disabled());
click_checkbox(&mut harness, "1001");
assert!(harness.get_by_label("Bake Selected Textures (0)").accesskit_node().is_disabled());
harness.state_mut().session.undo().unwrap();
harness.state_mut().session.undo().unwrap();
harness.run_steps(3);
click(&mut harness, "UV tiles (UDIM) (2)");
assert!(harness.query_by_label("1001").is_none());
assert!(harness.query_by_label("1002").is_none());
assert_eq!(harness.state().session.doc.project, before);
}
#[test]
fn restoring_map_defaults_updates_other_sets_even_when_active_values_are_default() {
let mut harness = harness(Some(BakedMap::AmbientOcclusion));
let session = &mut harness.state_mut().session;
let second = &mut session.doc.project.texture_sets[1].bake;
*second = BakeSettings::default();
second.common.is_enabled = false;
second.maps.ao.is_enabled = false;
second.maps.ao.parameters.rays.rays = 16;
second.maps.ao.parameters.ground_plane.offset = 3.0;
let before = session.doc.project.clone();
click(&mut harness, "Restore Defaults");
let mut expected = before.clone();
expected.texture_sets[1].bake.maps.ao.parameters = BakeSettings::default().maps.ao.parameters;
let session = &mut harness.state_mut().session;
assert_eq!(session.doc.project, expected);
session.undo().unwrap();
assert_eq!(session.doc.project, before);
}
#[test]
fn restoring_common_defaults_keeps_each_sets_inclusion_and_maps() {
let mut harness = harness(Some(BakedMap::AmbientOcclusion));
let session = &mut harness.state_mut().session;
session.doc.project.texture_sets[0].bake.common = Default::default();
let second = &mut session.doc.project.texture_sets[1].bake;
*second = BakeSettings::default();
second.common.is_enabled = false;
second.common.resolution = BakeResolution::R128;
second.common.resolution_height = Some(BakeResolution::R256);
second.common.apply_diffusion = false;
second.maps.select([BakedMap::Height]);
second.high_poly.low_suffix = "_custom_low".into();
let before = session.doc.project.clone();
harness.state_mut().ui.dock.focus(Panel::CommonSettings);
harness.run_steps(3);
harness.get_all_by_role_and_label(Role::Button, "Restore Defaults").next().unwrap().click();
harness.run_steps(3);
let mut expected = before.clone();
expected.texture_sets[1].bake.common = Default::default();
expected.texture_sets[1].bake.common.is_enabled = false;
let session = &mut harness.state_mut().session;
assert_eq!(session.doc.project, expected);
session.undo().unwrap();
assert_eq!(session.doc.project, before);
}
#[test]
fn output_axes_unlock_independently_and_relock_to_width() {
let mut harness = harness(None);
+10 -6
View File
@@ -23,9 +23,13 @@ const WORKER_TIMEOUT: Duration = Duration::from_secs(60);
/// The app on the Materials tab, `step_seconds` per frame, and two materials whose names show
/// nowhere else.
fn materials_shelf(step_seconds: f32) -> (Harness<'static, TextureCraftApp>, Vec<&'static SmartMaterial>) {
fn materials_shelf(step_seconds: f32, pixels_per_point: f32) -> (Harness<'static, TextureCraftApp>, Vec<&'static SmartMaterial>) {
let session = texturecraft_engine::sample_session(256, 64).unwrap();
let mut h = Harness::builder().with_size(egui::vec2(1600.0, 960.0)).with_step_dt(step_seconds).build_eframe(|cc| TextureCraftApp::new(cc, session));
let mut h = Harness::builder()
.with_size(egui::vec2(1600.0, 960.0))
.with_step_dt(step_seconds)
.with_pixels_per_point(pixels_per_point)
.build_eframe(|cc| TextureCraftApp::new(cc, session));
h.state_mut().ui.shelf_tab = MATERIALS_TAB;
h.run_steps(4);
@@ -55,7 +59,7 @@ fn big_preview_ready(h: &mut Harness<'static, TextureCraftApp>, material: &Smart
#[test]
fn hovering_a_shelf_tile_shows_its_big_preview() {
let (mut h, materials) = materials_shelf(1.0 / 4.0);
let (mut h, materials) = materials_shelf(1.0 / 4.0, 1.0);
let material = materials[0];
let tile = h.get_by_label(material.label).rect();
assert!(largest_drawn_texture(&h, BIG_PREVIEW_SIZE).is_none(), "nothing big before the hover");
@@ -77,7 +81,7 @@ fn hovering_a_shelf_tile_shows_its_big_preview() {
#[test]
fn the_big_preview_renders_after_a_rest_but_not_during_a_sweep() {
let (mut h, materials) = materials_shelf(STEP_SECONDS);
let (mut h, materials) = materials_shelf(STEP_SECONDS, 1.0);
let (first, second) = (materials[0], materials[1]);
let (from, to) = (h.get_by_label(first.label).rect().center(), h.get_by_label(second.label).rect().center());
@@ -114,10 +118,10 @@ fn high_dpi_smart_mask_hover_stays_within_the_renderer_limit() {
use texturecraft_engine::mask_preview::MAX_PREVIEW_SIZE_PX;
use texturecraft_engine::smart_masks::SMART_MASKS;
let (mut harness, _) = materials_shelf(1.0 / 4.0);
harness.ctx.set_pixels_per_point(3.0);
let (mut harness, _) = materials_shelf(1.0 / 4.0, 3.0);
harness.state_mut().ui.shelf_tab = 2;
harness.run_steps(4);
assert_eq!(harness.ctx.pixels_per_point(), 3.0, "the test uses the native 300% display scale");
harness.get_by_label(SMART_MASKS[0].label).hover();
let expected = Some([MAX_PREVIEW_SIZE_PX; 2]);
+45
View File
@@ -161,6 +161,51 @@ fn window_snapshots() {
harness.event(egui::Event::ModifiersChanged(egui::Modifiers::NONE));
}
#[test]
#[ignore]
fn bake_uv_tiles_snapshot() {
let Some(output_dir) = std::env::var_os("TC_UI_SNAPSHOTS").map(PathBuf::from) else {
eprintln!("set TC_UI_SNAPSHOTS=<dir> to write the pictures");
return;
};
std::fs::create_dir_all(&output_dir).unwrap();
let mut session =
texturecraft_engine::Session::new_project("UV tile baking", texturecraft_engine::geom::primitives::udim_plane(), "builtin:udim_plane", None, 256)
.unwrap();
texturecraft_engine::execute(&mut session, "textureSet.tile.resolution", &serde_json::json!({"tile": 1002, "resolution": 128})).unwrap();
let mut harness = Harness::builder()
.with_size(egui::vec2(1600.0, 960.0))
.with_pixels_per_point(1.0)
.wgpu()
.build_eframe(|context| TextureCraftApp::new(context, session));
harness.state_mut().ui.mode = Mode::Baking;
save(&mut harness, &output_dir, "bake-uv-tiles");
harness.get_by_value("128 × 128*").click();
save(&mut harness, &output_dir, "bake-tile-resolution-menu");
harness.get_by_label("Remove resolution override").click();
save(&mut harness, &output_dir, "bake-tile-resolution-inherited");
assert!(harness.query_by_value("128 × 128*").is_none());
assert!(harness.state().session.doc.project.texture_sets[0].tile_resolutions.is_empty());
let inherited_resolution = harness.get_by_label("UV tile 1002 resolution").rect().center();
harness.hover_at(inherited_resolution);
save(&mut harness, &output_dir, "bake-tile-resolution-hover");
assert_eq!(harness.get_all_by_value("256 × 256").count(), 2);
harness.hover_at(egui::pos2(900.0, 500.0));
harness.state_mut().session.undo().unwrap();
harness.run_steps(3);
harness.get_by_role_and_label(egui::Role::CheckBox, "1002").click();
save(&mut harness, &output_dir, "bake-uv-tiles-partial");
assert!(harness.state().session.doc.project.texture_sets[0].bake_excluded_tiles.contains(&1002));
harness.get_by_label("Show or hide the texture set").click();
save(&mut harness, &output_dir, "bake-uv-tiles-hidden");
assert!(!harness.state().session.doc.project.texture_sets[0].visible);
assert!(harness.state().session.doc.project.texture_sets[0].bake.common.is_enabled);
}
#[test]
#[ignore]
fn smart_mask_shelf_snapshot() {
+33
View File
@@ -24,6 +24,39 @@ as the history reaches); `edit.history` lists the steps done and the undone ones
Any command takes `merge: true` to fold its edit into the previous undo step when that step has
the same label: a drag that applies a value on every frame stays one step.
Bake mode applies edits in Common Settings and Mesh Map Settings to every texture set. Each
set keeps its own enabled mesh-map checkboxes and Include in Bake flag. Edits update only the
changed fields; Restore Defaults resets the whole parameter section across all sets.
`bake.settings {ts: "all", patch: {maps: {ao: {parameters: {rays: {rays: 128}}}}}}` changes
only AO secondary rays. A `patch` uses the nested `BakeSettings` field names and named enum
values returned in the command's `model` result; omitted fields retain each set's values, and
`null` clears optional fields such as `common.resolution_height`. All targeted sets are validated
before the edit is applied as one undo step. `model` still replaces the complete settings;
when combined, `patch` follows `model`, then the flat command parameters apply. Omitting `ts`
still targets the active set for scripts that need individual control.
The bake texture-set list shows visibility eyes and expandable UV tile rows. Visibility affects
the viewport independently of bake inclusion. Its resolution menus edit the texture-set size
(`textureSet.resolution`) and individual tile overrides (`textureSet.tile.resolution`), independently
of Common Settings' bake Output Size. Overridden tiles display a resolution marked with an asterisk;
inherited tile resolutions appear only on hover or while their menu is open. Remove resolution
override hides the number and restores inheritance from the set, including when their current
sizes happen to match.
Baked maps use a uniform UV tile atlas: every selected tile receives the full bake Output Size,
including rectangular output sizes. Changing a texture-set or tile working resolution preserves
the stored bake pixels. Materials, mesh-map previews, and exports sample those pixels through
the working tile layout. Older project files load their baked pixels as-is without layout
conversion; rebaking restores correct mapping and detail.
`bake.tile.set {ts?, tile: 1002, enabled: false}`
excludes one UV tile; `textureSet.inspect` / `session.inspect` expose each tile's `bakeEnabled`.
Tile choices are saved and undoable. Unchecked tiles retain their previous baked pixels, resampled
if output size changes, or neutral values when no previous map exists. A running bake uses the
tile selection captured when its worker started. Sets with no checked tiles are skipped; their
geometry still contributes to occlusion when baking other tiles.
## Control channel (desktop app)
```sh