Auto: Fix texture set resize ownership and reduce memory peaks

Reject resize results from another project. Release stale pixels and caches before retrying a resize within the original project, preserving intervening edits and one-step undo.

Fix rectangular height sampling, seam-boundary coverage, malformed set selectors and saved channel ordering. Reduce temporary composite and mesh-partition storage, and pack mixed-aspect trace textures without changing their samples.

Keep channel actions reachable in short windows, strengthen export and modal regressions, document the control commands and remove unrelated formatting changes.
This commit is contained in:
chasse20 committed 2026-11-29 08:04:24 +00:00
1 parent 41b8a69818
commit b5d9abbb91
40 files changed
+674 -281

No files matched your search

@@ -19,7 +19,6 @@ fn main() -> ExitCode {
eprintln!("usage: man-and-completions <out-dir>");
return ExitCode::from(2);
};
let dir = Path::new(&dir);
match generate(dir) {
Ok(()) => ExitCode::SUCCESS,
@@ -37,7 +36,7 @@ pub(crate) fn generate(dir: &Path) -> std::io::Result<()> {
for &shell in Shell::value_variants() {
clap_complete::generate_to(shell, &mut cmd, "texturecraft-cli", dir)?;
}
// Build a fresh command to keep generated help subcommands out of the manual
// A fresh command: `clap_complete::generate_to` built `cmd`, adding the `help` subcommand,
// which `clap_mangen` would otherwise give pages of its own (`texturecraft-cli-help-convert.1`).
clap_mangen::generate_to(texturecraft_cli::command(), dir)
}
+3 -9
View File
@@ -304,8 +304,7 @@ impl UsageError {
/// The clap error, printed with the usage and exited with 2 like clap's own.
pub(crate) fn into_clap(self, subcommand: &str) -> clap::Error {
let mut command = crate::command();
// Built, so a subcommand's usage names the program: `texturecraft-cli run`
// Built, so a subcommand's usage names the program: `texturecraft-cli run`.
command.build();
let mut command = command.find_subcommand_mut(subcommand).map_or_else(crate::command, std::mem::take);
command.error(ErrorKind::ArgumentConflict, self.to_string())
@@ -352,21 +351,17 @@ fn batch_would_replace(a: &BatchArgs) -> Result<(), UsageError> {
let Ok(text) = std::fs::read_to_string(&a.script) else {
return Ok(());
};
let Ok(script) = serde_json::from_str::<Value>(&text) else {
return Ok(());
};
let field = |name: &str| script.get(name).and_then(Value::as_str);
let Some(output) = field("save") else {
return Ok(());
};
let input = field("open").unwrap_or("builtin:material_ball");
if input.starts_with("builtin:") {
return if a.in_place { Err(UsageError::InPlaceNotUsed) } else { Ok(()) };
}
let input = Path::new(input);
let output = Path::new(output);
match (same_project(output, input), a.in_place) {
@@ -414,15 +409,14 @@ impl Command {
pub(crate) fn parse(args: &[OsString]) -> Result<Cli, clap::Error> {
let matches = crate::command().try_get_matches_from(std::iter::once(OsString::from("texturecraft-cli")).chain(args.iter().cloned()))?;
let cli = Cli::from_arg_matches(&matches)?;
// Only an explicit token flag requires bridge mode
// An inherited TEXTURECRAFT_CONTROL_TOKEN must not force --bridge: the variable is how a
// client authenticates when --bridge is already set. Only an explicit --token flag requires it.
let token_flag_without_bridge = matches
.subcommand_matches("mcp")
.is_some_and(|mcp| mcp.value_source("token") == Some(clap::parser::ValueSource::CommandLine) && mcp.get_one::<u16>("bridge").is_none());
if token_flag_without_bridge {
return Err(UsageError::TokenNeedsBridge.into_clap("mcp"));
}
cli.command.check().map_err(|(sub, e)| e.into_clap(sub))?;
Ok(cli)
}
+4 -12
View File
@@ -72,8 +72,7 @@ where
outln!(err, "error: `{flag}` is a TextureCraft desktop launch option, not a CLI argument");
return 2;
}
// Help and the version (`help`, `-h`, `<subcommand> --help`, `-V`) come back as errors too
// Help and the version (`help`, `-h`, `<subcommand> --help`, `-V`) come back as errors too.
let cli = match parse(&args) {
Ok(cli) => cli,
Err(e) => {
@@ -148,7 +147,6 @@ fn info(a: &InfoArgs, out: &mut dyn Write) -> Result<(), CliError> {
);
return Ok(());
}
if !is_project(&a.input) {
let m = import_mesh(&a.input).map_err(|e| CliError::Read { path: a.input.clone(), message: e.to_string() })?;
print(
@@ -160,13 +158,11 @@ fn info(a: &InfoArgs, out: &mut dyn Write) -> Result<(), CliError> {
);
return Ok(());
}
let h = open(&a.input, None)?;
let mut v = h.inspect();
v["file"] = json!(file);
v["kind"] = json!("project");
// The embedded mesh is re-imported for its UV report (built-in meshes have none)
// The embedded mesh is re-imported for its UV report (built-in meshes have none).
v["uv"] = match &h.session.mesh_source {
Some((ext, bytes)) => {
let m = import_mesh_bytes(&format!("mesh.{ext}"), bytes).map_err(|e| CliError::Read { path: a.input.clone(), message: e.to_string() })?;
@@ -185,7 +181,6 @@ fn commands(a: &CommandsArgs, out: &mut dyn Write) -> Result<(), CliError> {
print(out, &list);
return Ok(());
}
for c in list.as_array().into_iter().flatten() {
let f = |k: &str| c.get(k).and_then(Value::as_str).unwrap_or_default().to_string();
outln!(out, "{:<28} {:<36} {}", f("id"), f("label"), f("params"));
@@ -226,7 +221,6 @@ fn batch(a: &BatchArgs, out: &mut dyn Write, err: &mut dyn Write) -> Result<(),
message: failure["error"].as_str().unwrap_or_default().to_string(),
});
}
match output {
Some(path) => save(&mut h, Path::new(path), err),
None => Ok(()),
@@ -234,7 +228,7 @@ fn batch(a: &BatchArgs, out: &mut dyn Write, err: &mut dyn Write) -> Result<(),
}
fn bake(a: &BakeArgs, out: &mut dyn Write, err: &mut dyn Write) -> Result<(), CliError> {
// `check` has seen to it: a project without -o is saved in place (--in-place), a mesh has -o
// `check` has seen to it: a project without -o is saved in place (--in-place), a mesh has -o.
let target = a.output.as_deref().unwrap_or(&a.input);
let mut p = json!({"ts": "all"});
if let Some(r) = a.resolution {
@@ -298,7 +292,6 @@ fn new(a: &NewArgs, err: &mut dyn Write) -> Result<(), CliError> {
if is_project(&a.input) {
return Err(CliError::AlreadyProject(a.input.clone()));
}
let mut h = open(&a.input, a.resolution)?;
if a.sample {
let bake_res = h.session.doc.project.texture_sets.first().map_or(1024, |t| t.resolution.min(1024));
@@ -317,7 +310,6 @@ fn workspace(roots: &RootArgs) -> Result<Filesystem, CliError> {
if roots.read_root.is_none() && roots.write_root.is_none() {
return Ok(Filesystem::Denied);
}
Ok(Filesystem::Workspace(AuthorizedWorkspace::new(roots.read_root.as_deref(), roots.write_root.as_deref())?))
}
@@ -335,7 +327,7 @@ fn serve(a: &ServeArgs, err: &mut dyn Write) -> Result<(), CliError> {
match a.port {
None => rpc::serve_lines(&h, std::io::stdin().lock(), std::io::stdout().lock()).map_err(CliError::Serve)?,
Some(port) => {
// Bind first: a port in use must not replace its server's token file
// Bind first: a port in use must not replace its server's token file.
let listener = rpc::bind_tcp(port)?;
let addr = listener.local_addr().map_err(CliError::Serve)?;
let (token, file) = server_token(addr.port())?;
+1 -1
View File
@@ -2,7 +2,7 @@
#![forbid(unsafe_code)]
fn main() {
// `args_os`, not `args`: a non-Unicode argument must reach clap, not panic before anything is printed
// `args_os`, not `args`: a non-Unicode argument must reach clap, not panic before anything is printed.
let code = texturecraft_cli::run(std::env::args_os().skip(1), &mut std::io::stdout(), &mut std::io::stderr());
std::process::exit(code);
}
+3 -6
View File
@@ -216,21 +216,18 @@ fn render_without_a_gpu_points_to_path_tracing() {
fn path_traced_render_needs_no_gpu() {
let d = tmp("trace");
let out = d.join("ball.png");
// On the GPU where it has compute shaders, then forced onto the CPU
// On the GPU where it has compute shaders, then forced onto the CPU.
for extra in [None, Some("--cpu")] {
let mut args = vec!["render", "builtin:material_ball", p(&out), "--size", "96x64", "--samples", "4"];
args.extend(extra);
ok(&args);
let img = image::open(&out).unwrap().to_rgb8();
assert_eq!(img.dimensions(), (96, 64));
// The lit ball in the middle is brighter than the dark backdrop corner
// The lit ball in the middle is brighter than the dark backdrop corner.
let lum = |x, y| img.get_pixel(x, y).0.iter().map(|v| *v as u32).sum::<u32>();
assert!(lum(48, 28) > lum(1, 1) + 60);
}
// --camera looks through a camera saved in the project; an unknown name is an error
// --camera looks through a camera saved in the project; an unknown name is an error.
let proj = d.join("cams.tcraft");
ok(&["run", "builtin:cube", "camera.set", r#"{"yaw": 80, "distance": 9}"#, "-o", p(&proj)]);
ok(&["run", p(&proj), "camera.add", r#"{"name": "Side"}"#, "-o", p(&proj), "--in-place"]);
+5 -9
View File
@@ -130,7 +130,7 @@ fn bad_values_conflicts_and_missing_arguments_are_refused_before_any_file_is_wri
#[test]
fn loopback_ports_take_the_host_prefix_and_a_dashed_name_follows_a_double_dash() {
// `--bridge 127.0.0.1:PORT` and `localhost:PORT` are still ports: the failure is the missing token
// `--bridge 127.0.0.1:PORT` and `localhost:PORT` are still ports: the failure is the missing token.
for bridge in ["127.0.0.1:9", "localhost:9"] {
let got = invoke(["mcp", "--bridge", bridge, "--token", "short"]);
assert_eq!(got.code, 1, "{bridge}: {}", got.err);
@@ -201,8 +201,7 @@ fn an_output_that_would_replace_an_input_is_refused_without_in_place() {
assert!(message.contains("--in-place") || message.contains("would replace"), "{args:?}: {message}");
}
assert_eq!(std::fs::read(&source).unwrap(), before, "a refused command changes nothing");
// `--in-place` lets only a project be replaced, and only by itself
// `--in-place` lets only a project be replaced, and only by itself.
let got = invoke(["run", a, "layer.add.fill", "{}", "-o", a, "--in-place"]);
assert_eq!(got.code, 0, "{}", got.err);
let got = invoke(["bake", a, "--in-place", "--resolution", "128", "--maps", "ambientOcclusion"]);
@@ -211,8 +210,7 @@ fn an_output_that_would_replace_an_input_is_refused_without_in_place() {
assert!(usage_error(&["run", a, "layer.add.fill", "{}", "-o", elsewhere.to_str().unwrap(), "--in-place"]).contains("--in-place"));
assert!(usage_error(&["bake", a, "-o", elsewhere.to_str().unwrap(), "--in-place"]).contains("--in-place"));
assert!(!elsewhere.exists());
// Headless::save appends .tcraft, so `-o scene` would replace scene.tcraft
// Headless::save appends .tcraft, so `-o scene` would replace scene.tcraft.
let unsuffixed = dir.join("a");
let unsuffixed = unsuffixed.to_str().unwrap();
let after_in_place = std::fs::read(&source).unwrap();
@@ -246,8 +244,7 @@ fn batch_runs_a_script_and_a_failing_step_fails_the_command() {
let got = invoke(argv(&[&"batch", &dir.join("missing.json")]));
assert_eq!(got.code, 1);
assert!(got.err.contains("missing.json"), "{}", got.err);
// A script that saves over the project it opened needs --in-place, and must not have run
// A script that saves over the project it opened needs --in-place, and must not have run.
let opened = project(&dir, "opened.tcraft");
let before = std::fs::read(&opened).unwrap();
let overwrite = dir.join("overwrite.json");
@@ -294,8 +291,7 @@ fn the_desktop_launch_options_are_refused_before_any_subcommand() {
fn a_path_that_is_not_valid_unicode_is_named_in_the_error() {
use std::os::unix::ffi::OsStringExt;
let dir = workdir("non-unicode");
// The engine's commands take their paths as JSON text: the command says so and names the file
// The engine's commands take their paths as JSON text: the command says so and names the file.
let input = dir.join(OsString::from_vec(b"in-\xff.tcraft".to_vec()));
let got = invoke(argv(&[&"info", &input]));
assert_eq!(got.code, 1);
+8 -12
View File
@@ -37,8 +37,7 @@ fn serve_writes_nothing_but_json_lines_to_stdout() {
fn serve_ends_quietly_and_mcp_reports_it_when_stdin_is_closed() {
let output = binary().arg("serve").stdin(Stdio::null()).output().unwrap();
assert_eq!((output.status.code(), output.stdout.is_empty(), output.stderr.is_empty()), (Some(0), true, true));
// An MCP client must open with `initialize`; end of input before it is a failed start
// An MCP client must open with `initialize`; end of input before it is a failed start.
let dir = std::env::temp_dir().join(format!("tc-mcp-stdio-{}", std::process::id()));
std::fs::create_dir_all(&dir).unwrap();
let output = binary().args(["mcp", "--read-root", dir.to_str().unwrap(), "--write-root", dir.to_str().unwrap()]).stdin(Stdio::null()).output().unwrap();
@@ -63,25 +62,21 @@ fn bridge(token_flag: Option<&str>, env: Option<&str>) -> Output {
#[test]
fn the_control_token_variable_is_a_fallback_the_flag_wins_and_an_empty_one_is_unset() {
let secret = "env-token-0123456789-secret";
// Empty or blank counts as unset: the error says to set one, as when there is none
// Empty or blank counts as unset: the error says to set one, as when there is none.
for blank in ["", " "] {
let output = bridge(None, Some(blank));
let err = String::from_utf8_lossy(&output.stderr);
assert_eq!(output.status.code(), Some(1), "{err}");
assert!(err.contains("no control token: set TEXTURECRAFT_CONTROL_TOKEN"), "{err}");
}
// The variable is used when there is no flag: a good token gets as far as connecting
// The variable is used when there is no flag: a good token gets as far as connecting.
let err = String::from_utf8_lossy(&bridge(None, Some(secret)).stderr).into_owned();
assert!(!err.contains("16 to 1024") && !err.contains(secret), "{err}");
// The flag wins over a good variable: its bad value is what is reported, without echoing either
// The flag wins over a good variable: its bad value is what is reported, without echoing either.
let err = String::from_utf8_lossy(&bridge(Some("short"), Some(secret)).stderr).into_owned();
assert!(err.contains("control token must be 16 to 1024"), "{err}");
assert!(!err.contains(secret) && !err.contains("short\n"), "{err}");
// A bad value in the variable is refused too, and its value stays out of the message
// A bad value in the variable is refused too, and its value stays out of the message.
let err = String::from_utf8_lossy(&bridge(None, Some("bad token")).stderr).into_owned();
assert!(err.contains("control token must be 16 to 1024") && !err.contains("bad token"), "{err}");
}
@@ -95,7 +90,7 @@ fn help_lists_the_variable_but_never_its_value() {
#[test]
fn a_variable_alone_grants_no_file_access() {
// The token variable is for authentication only: a headless server with no roots still refuses files
// The token variable is for authentication only: a headless server with no roots still refuses files.
let mut child =
binary().arg("serve").env("TEXTURECRAFT_CONTROL_TOKEN", "env-token-0123456789-secret").stdin(Stdio::piped()).stdout(Stdio::piped()).spawn().unwrap();
let mut stdin = child.stdin.take().unwrap();
@@ -108,7 +103,8 @@ fn a_variable_alone_grants_no_file_access() {
#[test]
fn a_token_in_the_environment_does_not_require_bridge() {
// An inherited control token also permits headless startup
// Headless MCP must parse even when TEXTURECRAFT_CONTROL_TOKEN is set; only --token on the
// command line requires --bridge.
let output = binary().args(["mcp", "--fromat"]).env("TEXTURECRAFT_CONTROL_TOKEN", "env-token-0123456789-secret").output().unwrap();
let err = String::from_utf8_lossy(&output.stderr);
assert_eq!(output.status.code(), Some(2), "{err}");
+3 -2
View File
@@ -75,7 +75,6 @@ pub fn server_token(port: u16) -> Result<(String, Option<PathBuf>), AutomationEr
validate_token(t.trim())?;
return Ok((t.trim().to_string(), None));
}
let token = generate_token()?;
let path = token_file(port);
write_token_file(&path, &token).map_err(|e| {
@@ -238,7 +237,9 @@ mod tests {
#[test]
fn a_blank_token_counts_as_not_given() {
// A blank supplied token can fall back to a nonblank inherited token
// No token anywhere (the port has no token file): the error says what to set, not that a
// blank token is invalid. A non-blank inherited TOKEN_ENV can still satisfy the client
// after a blank supplied value, so do not unwrap_err() first.
match client_token(1, Some(" ".into())) {
Err(error) => {
if std::env::var_os(TOKEN_ENV).is_none() {
+68 -17
View File
@@ -14,10 +14,10 @@ use rayon::prelude::*;
use texturecraft_core::{
AnisotropicKuwahara, BakedMap, Bevel, BevelSmooth, BlendMode, BlockScales, Channel, ChannelFormat, ChannelKind, ColorMatch, CompareSource, ContentsOffset,
CurvatureDetail, CurvatureMode, Effect, EffectKind, FLAT_CURVATURE, Fill, Filter, Filtering, Generator, GeneratorGlobal, GeneratorKind,
GrayscaleConversionParameters, HeightMask, HeightToNormal, HighpassSpace, ImageInput, KindControls, Layer, LayerId, LayerKind, Mask, MaskBackground,
MaskOutline, Mirror, NormalFormat, PreparedColorMatch, PreparedGradient, Project, Projection, RepeatMode, Sampling, SectionParameters, ShapeCrop, Source,
SourceColorMode, SourceSlopeBlur, SourceWarp, StylizedShading, TargetColorMode, TextureSet, TileGrid, TileTransform, WarpSourceMode, WearParameters,
blend1, blend3, lum, mix3, per_unit, posterize, udim_at,
GrayscaleConversionParameters, HeightMask, HeightToNormal, HeightToNormalMethod, HighpassSpace, ImageInput, KindControls, Layer, LayerId, LayerKind, Mask,
MaskBackground, MaskOutline, Mirror, NormalFormat, PreparedColorMatch, PreparedGradient, Project, Projection, RepeatMode, Sampling, SectionParameters,
ShapeCrop, Source, SourceColorMode, SourceSlopeBlur, SourceWarp, StylizedShading, TargetColorMode, TextureSet, TileGrid, TileTransform, WarpSourceMode,
WearParameters, blend1, blend3, lum, mix3, per_unit, posterize, udim_at,
};
use texturecraft_geom::glam::{Vec2, Vec3};
use texturecraft_geom::{Mesh, NO_TRI, Surface, UvGBuffer};
@@ -818,7 +818,7 @@ fn gather(
Op::SourceSlopeBlur(slope) => slope_texel(&slope, (x, y), (res, comps), (block_size, tile_size), &mut acc, (&sample, &input)),
Op::HeightToNormal(filter) => {
let center = orig.get((row * width + col) * comps..(row * width + col + 1) * comps).unwrap_or(&[]);
height_to_normal_texel(&filter, (x, y), (res, center), &mut acc, &input);
height_to_normal_texel(&filter, (x, y), (tile_size, center), &mut acc, &input);
}
Op::Kuwahara(kuwahara) => {
let radius = (kuwahara.radius.min(AnisotropicKuwahara::MAX_RADIUS) * res as f32 / FILTER_SIZE_RESOLUTION).max(MIN_FILTER_RADIUS);
@@ -959,21 +959,18 @@ fn mean_region_color(data: &[f32], fallback: [f32; 3]) -> [f32; 3] {
fn height_to_normal_texel(
filter: &HeightToNormal,
(x, y): (f32, f32),
(res, center): (u32, &[f32]),
(tile_size, center): ([u32; 2], &[f32]),
acc: &mut [f32; 5],
height: &dyn Fn(f32, f32) -> Option<f32>,
) {
let (Some(own), [red, green, blue, cov]) = (height(x, y), center) else { return };
if *cov <= 0.0 {
return;
}
let at = |dx: f32, dy: f32| height(x + dx, y + dy).unwrap_or(own);
// Sobel gradients over the kernel's weight sum
let gx = (at(1.0, -1.0) + 2.0 * at(1.0, 0.0) + at(1.0, 1.0) - at(-1.0, -1.0) - 2.0 * at(-1.0, 0.0) - at(-1.0, 1.0)) / 8.0;
let gy = (at(-1.0, 1.0) + 2.0 * at(0.0, 1.0) + at(1.0, 1.0) - at(-1.0, -1.0) - 2.0 * at(0.0, -1.0) - at(1.0, -1.0)) / 8.0;
let made = filter.normal([gx, gy], res).map(|v| v * 0.5 + 0.5);
let slope = HeightToNormalMethod::Smooth.slope(|dx, dy| height(x + dx as f32, y + dy as f32).unwrap_or(own));
let made = filter.normal_for_size(slope, tile_size).map(|value| value * 0.5 + 0.5);
let packed = if filter.overwrite { made } else { texturecraft_core::blend::rnm([red, green, blue].map(|v| v / cov), made) };
for (slot, value) in acc.iter_mut().zip(packed) {
*slot = value * cov;
@@ -3364,9 +3361,11 @@ impl<'a, 'b> Texel<'a, 'b> {
let (width, height) = (self.res, self.inp.gbuf.height);
let at = |x: u32, y: u32| self.inp.baked.sample_working(BakedMap::Height, x, y, (width, height), &self.inp.block_scales).map(|h| h[0]);
let (origin_x, origin_y, tile_width, tile_height) = if let Some(grid) = self.inp.tile_grid() {
let block = (width / grid.cols.max(1)).max(1);
let tile = ((block as f32 * self.inp.block_scales.at(self.x, self.y)).round() as u32).max(1);
(self.x / block * block, self.y / block * block, tile, tile)
let block_width = (width / grid.cols.max(1)).max(1);
let block_height = (height / grid.rows.max(1)).max(1);
let scale = self.inp.block_scales.at(self.x, self.y);
let tile_side = |block_side| ((block_side as f32 * scale).round() as u32).max(1);
(self.x / block_width * block_width, self.y / block_height * block_height, tile_side(block_width), tile_side(block_height))
} else {
(0, 0, width, height)
};
@@ -4878,20 +4877,26 @@ fn composite_block(
// Join the bands of each tile (in parallel; uncovered tiles are freed)
let joined: Vec<Joined> = results
.par_chunks(bands as usize)
.par_chunks_mut(bands as usize)
.map(|parts| {
let any = parts.iter().any(|p| p.2);
let data = (0..channels.len())
.map(|k| {
any.then(|| {
let mut v = Vec::with_capacity(parts.iter().map(|p| p.0.get(k).map_or(0, Vec::len)).sum());
for p in parts {
for p in parts.iter() {
v.extend_from_slice(p.0.get(k).map_or(&[][..], Vec::as_slice));
}
std::sync::Arc::new(v)
})
})
.collect();
// Only replay data is needed after joining the tile
for (channel_buffers, _, _) in parts {
channel_buffers.clear();
}
(data, any)
})
.collect();
@@ -5675,6 +5680,52 @@ mod tests {
assert!(close(composite.value(Channel::BaseColor, 48, 32), [1.0, 0.0, 0.0]), "the exposed side takes the fill");
}
#[test]
fn a_rectangular_height_filter_tilts_equally_for_equal_uv_slopes() {
let (width, height) = (16, 32);
let texels = (width * height) as usize;
let normals: Vec<f32> = [0.5, 0.5, 1.0, 1.0].into_iter().cycle().take(texels * 4).collect();
let coverage = vec![1.0; texels];
let heights: Vec<_> = (0..width * height).map(|index| (index % width) as f32 / width as f32 + (index / width) as f32 / height as f32).collect();
let normal = gather(
Op::HeightToNormal(HeightToNormal::LIBRARY),
(&normals, &coverage, &heights),
4,
(0, 0, width, height),
1.0,
(width, [width, height], [width, height]),
1.0,
);
let center = (height / 2 * width + width / 2) as usize * 4;
let (red, green) = (normal[center], normal[center + 1]);
assert!(red < 0.5 && green > 0.5);
assert!((1.0 - red - green).abs() < 1e-6, "equal UV slopes produced unequal tilt: {red}, {green}");
}
#[test]
fn baked_height_slopes_respect_rectangular_udim_blocks() {
let mut fixture = fixture();
let (block_width, block_height) = (64, 128);
let set = &mut fixture.project.texture_sets[0];
set.set_size(block_width, block_height);
set.uv_tiles = vec![1001, 1011];
let (width, height) = set.size();
fixture.gbuf = UvGBuffer::new(&fixture.mesh, 0, width, height);
fixture.baked.resolution = width;
let heights = (0..width * height).map(|i| (i % width) as f32 / block_width as f32 + (i / width % block_height) as f32 / block_height as f32).collect();
fixture.baked.maps.insert(BakedMap::Height, Arc::new(heights));
let images = ImageStore::default();
let inputs = inputs(&fixture, &images, None);
for y in [block_height - 1, block_height] {
let slope = Texel::new(&inputs, 10, y, 0, 0.0).height_slope();
assert_eq!(slope, Some([1.0; 2]), "slope at row {y} must stay within its rectangular tile");
}
}
#[test]
fn baked_height_slopes_stay_within_each_uv_tile() {
let mut fixture = fixture();
+23
View File
@@ -104,6 +104,29 @@ mod tests {
SeamPaddingInput::new(seams, triangles, partition)
}
#[test]
fn a_flat_seam_keeps_the_last_row_within_its_reach() {
let (width, height) = (128, 128);
let at = |x: f32, y: f32| Vec2::new(x / width as f32, y / height as f32);
// The length rounds the normalized edge slightly below one
let near = UvSeamSide { triangle: 0, start: at(1.0, 32.5), end: at(16.25, 32.5), interior: at(1.0, 40.0) };
let far = UvSeamSide { triangle: 1, start: at(65.0, 32.5), end: at(80.25, 32.5), interior: at(65.0, 100.0) };
let triangles: Vec<_> = (0..width * height)
.map(|index| match (index % width, index / width) {
(1..=15, 32..=39) => 0,
(65..=79, 32..=99) => 1,
_ => NO_TRI,
})
.collect();
let covered: Vec<_> = triangles.iter().map(|&triangle| triangle != NO_TRI).collect();
let seams = islands(vec![UvSeam { sides: [near, far] }], &triangles);
let padding = PaddingMaps::new(UvPaddingMode::Space3d, &covered, (width, height), Some(SEAM_REACH), (64, height), Some(&seams));
assert!(padding.source(true, 15, 0).is_some_and(|(x, _)| x >= 64), "the boundary row borrows from the far island");
assert!(padding.source(false, 15, 0).is_some_and(|(x, _)| x < 64), "flat padding still uses the near island");
}
#[test]
fn padding_stops_at_the_far_islands_edge() {
let (_, seams) = two_islands();
+1 -5
View File
@@ -32,11 +32,7 @@ pub(crate) fn cross_seams(flat: &DilationMap, reach: u32, block: (u32, u32), inp
let (x1, y1) = (high.x.ceil().min(size.x) as u32, high.y.ceil().min(size.y) as u32);
let mut side_islands = None;
for y in y0..y1 {
// Only the texel centres in the band beside the seam can be within its reach
let Some((low_x, high_x)) = near_edge.band_span(reach, y as f32 + 0.5) else { continue };
let row_x0 = ((low_x - 0.5).floor().max(0.0) as u32).max(x0);
let row_x1 = ((high_x + 0.5).ceil().max(0.0) as u32).min(x1);
for x in row_x0..row_x1 {
for x in near_edge.outside_columns(y, x0..x1, reach) {
let index = y * width + x;
let Some(&flat_source) = flat.src.get(index as usize) else { continue };
+46 -25
View File
@@ -1,5 +1,7 @@
//! A UV seam side in texel space
use std::ops::Range;
use texturecraft_geom::UvSeamSide;
use texturecraft_geom::glam::Vec2;
@@ -22,29 +24,49 @@ impl TexelEdge {
pub(crate) fn outside(&self, point: Vec2) -> Option<(f32, f32)> {
let direction = self.end - self.start;
let along = (point - self.start).dot(direction) / direction.length_squared();
let outside = -(point - self.start).dot(self.inward);
let outside = self.outside_distance(point);
((0.0..=1.0).contains(&along) && outside > 0.0).then_some((along, outside))
}
/// The x range at height `y` of the band `reach` deep outside the edge: every point there that `outside` takes within `reach`
pub(crate) fn band_span(&self, reach: f32, y: f32) -> Option<(f32, f32)> {
let depth = self.inward * -reach;
let corners = [self.start, self.end, self.end + depth, self.start + depth];
let mut span: Option<(f32, f32)> = None;
for (index, &from) in corners.iter().enumerate() {
let to = corners[(index + 1) % corners.len()];
if y < from.y.min(to.y) || y > from.y.max(to.y) {
continue;
}
// A level side spans its whole length at its height
let xs = if from.y == to.y { [from.x, to.x] } else { [from.x + (to.x - from.x) * (y - from.y) / (to.y - from.y); 2] };
for x in xs {
span = Some(span.map_or((x, x), |(low, high)| (low.min(x), high.max(x))));
}
}
span
fn outside_distance(&self, point: Vec2) -> f32 {
-(point - self.start).dot(self.inward)
}
/// Clip columns to the exterior distance band using the same rounded distances as `outside`
pub(crate) fn outside_columns(&self, row: u32, columns: Range<u32>, reach: f32) -> Range<u32> {
if columns.is_empty() {
return columns;
}
let distance = |column| self.outside_distance(Vec2::new(column as f32 + 0.5, row as f32 + 0.5));
if self.inward.x == 0.0 {
let outside = distance(columns.start);
return if outside > 0.0 && outside <= reach { columns } else { 0..0 };
}
// Signed distance is monotone across a row even when adjacent values round to the same distance
let (start, end) = if self.inward.x < 0.0 {
let start = first_column_after(columns.clone(), |column| distance(column) <= 0.0);
(start, first_column_after(start..columns.end, |column| distance(column) <= reach))
} else {
let start = first_column_after(columns.clone(), |column| distance(column) > reach);
(start, first_column_after(start..columns.end, |column| distance(column) > 0.0))
};
start..end
}
}
fn first_column_after(mut columns: Range<u32>, before: impl Fn(u32) -> bool) -> u32 {
while columns.start < columns.end {
let middle = columns.start.midpoint(columns.end);
if before(middle) {
columns.start = middle + 1;
} else {
columns.end = middle;
}
}
columns.start
}
#[cfg(test)]
@@ -55,23 +77,22 @@ mod tests {
use super::TexelEdge;
#[test]
fn a_diagonal_edges_band_spans_every_point_beside_it_and_little_else() {
fn a_diagonal_edges_band_spans_every_texel_beside_it_without_scanning_the_rectangle() {
let size = Vec2::splat(512.0);
let side = UvSeamSide { triangle: 0, start: Vec2::new(0.05, 0.05), end: Vec2::new(0.95, 0.9), interior: Vec2::new(0.9, 0.1) };
let edge = TexelEdge::new(side, size).unwrap();
let reach = 32.0;
let (mut beside, mut spanned) = (0, 0);
for y in 0..512 {
for y in 0..512u32 {
let centre_y = y as f32 + 0.5;
let span = edge.band_span(reach, centre_y);
spanned += span.map_or(0, |(low, high)| (high - low).ceil() as usize + 1);
let span = edge.outside_columns(y, 0..512, reach);
spanned += span.len();
for x in 0..512 {
let point = Vec2::new(x as f32 + 0.5, centre_y);
if edge.outside(point).is_some_and(|(_, outside)| outside <= reach) {
beside += 1;
let (low, high) = span.unwrap_or((f32::MAX, f32::MIN));
assert!((low..=high).contains(&point.x), "{point} is beside the edge but outside its row's span {span:?}");
assert!(span.contains(&x), "{point} is beside the edge but outside its row's span {span:?}");
}
}
}
+1
View File
@@ -112,6 +112,7 @@ mod tests {
let count = listed.len();
listed.sort();
listed.dedup();
assert_eq!(listed.len(), count, "a channel is listed twice");
assert_eq!(listed, Channel::ALL.to_vec());
}
+8 -3
View File
@@ -53,9 +53,14 @@ impl HeightToNormal {
}
/// The unit tangent-space normal (OpenGL, +Y up the image) of a height changing by `gx` per texel to the right and `gy` per texel down
pub fn normal(&self, [gx, gy]: [f32; 2], res: u32) -> [f32; 3] {
let strength = self.strength(res);
let (x, y) = (-gx * strength, gy * strength);
pub fn normal(&self, slope: [f32; 2], res: u32) -> [f32; 3] {
self.normal_for_size(slope, [res; 2])
}
/// The same tangent-space normal for a UV tile with independent width and height
pub fn normal_for_size(&self, [gx, gy]: [f32; 2], [width, height]: [u32; 2]) -> [f32; 3] {
let strength_per_uv = self.strength(1);
let (x, y) = (-gx * (strength_per_uv * width as f32), gy * (strength_per_uv * height as f32));
let length = (x * x + y * y + 1.0).sqrt();
if length.is_finite() { [x / length, y / length, 1.0 / length] } else { [0.0, 0.0, 1.0] }
}
+6 -2
View File
@@ -385,8 +385,12 @@ impl TextureSet {
/// The channels with the formats they are stored in (8-bit ones read as 16-bit without `format_precision`)
pub fn formats(&self) -> Vec<(Channel, ChannelFormat)> {
let held = |format: ChannelFormat| if self.format_precision { format } else { format.at_least_16_bit() };
self.channels.iter().map(|(channel, format)| (*channel, held(*format))).collect()
self.iter_formats().collect()
}
/// The effective storage formats in texture-set order
pub fn iter_formats(&self) -> impl Iterator<Item = (Channel, ChannelFormat)> + '_ {
self.channels.iter().map(|&(channel, format)| (channel, if self.format_precision { format } else { format.at_least_16_bit() }))
}
/// Add channel `c` in its default format (16-bit or more until a format is set, see [`TextureSet::formats`]); false when present
@@ -877,7 +877,6 @@ fn bake_run(session: &mut Session, params: &Value) -> Result<Value> {
Ok(tracer) => tracers.push(tracer),
Err(error) => {
session.bake_log.set_failed(index, &error.to_string());
// The edit rolls back the sets baked before this one too
session.bake_log.discard();
return Err(error);
+4 -10
View File
@@ -384,14 +384,11 @@ fn stage_handoff_package_in(base: &std::path::Path, file_name: &str, package: &[
if file_name.is_empty() || std::path::Path::new(file_name).file_name() != Some(std::ffi::OsStr::new(file_name)) {
return Err(EngineError::Other(format!("`{file_name}` is not a plain file name")));
}
sweep_old_handoffs(base, HANDOFF_MAX_AGE);
// Dropped (and removed) on any early return, so a failed write leaves no empty folder behind
// Dropped (and removed) on any early return, so a failed write leaves no empty folder behind.
let mut builder = tempfile::Builder::new();
builder.prefix(HANDOFF_PREFIX);
// tempfile makes folders with the default mode (0755 under the usual umask), so ask for 0700 and 0600 explicitly
// tempfile makes folders with the default mode (0755 under the usual umask), so ask for 0700 and 0600 explicitly.
#[cfg(unix)]
builder.permissions(std::os::unix::fs::PermissionsExt::from_mode(0o700));
let dir = builder.tempdir_in(base).map_err(io)?;
@@ -416,7 +413,6 @@ fn sweep_old_handoffs(base: &std::path::Path, max_age: std::time::Duration) {
if !entry.file_name().to_string_lossy().starts_with(HANDOFF_PREFIX) {
continue;
}
let Ok(meta) = std::fs::symlink_metadata(entry.path()) else { continue };
let old = meta.modified().ok().and_then(|t| t.elapsed().ok()).is_some_and(|age| age > max_age);
if meta.is_dir() && old {
@@ -873,8 +869,7 @@ mod tests {
let base = scratch("planted");
let victim = base.join("victim.txt");
std::fs::write(&victim, b"precious").unwrap();
// The old code wrote `<temp>/<name>` with `fs::write`; a hard link there reaches the victim on every platform
// The old code wrote `<temp>/<name>` with `fs::write`; a hard link there reaches the victim on every platform.
std::fs::hard_link(&victim, base.join("wood.mcraft")).unwrap();
let path = super::stage_handoff_package_in(&base, "wood.mcraft", b"package").unwrap();
@@ -927,8 +922,7 @@ mod tests {
std::fs::create_dir(dir).unwrap();
}
std::fs::write(&file, b"x").unwrap();
// Zero age limit: everything with the prefix that is a folder counts as old
// Zero age limit: everything with the prefix that is a folder counts as old.
super::sweep_old_handoffs(&base, std::time::Duration::ZERO);
assert!(!old.exists() && other.exists() && file.exists());
let young = base.join("texturecraft-open-young");
+38 -20
View File
@@ -89,6 +89,24 @@ impl SetCache {
}
}
fn has_channels(&self, set: &TextureSet) -> bool {
if self.composite.channels.len() != set.channels.len() {
return false;
}
if self.composite.channels.keys().copied().eq(set.channels.iter().map(|&(channel, _)| channel)) {
return true;
}
// Saved sets can list their channels in a different order from the composite
let mut present = [false; Channel::ALL.len()];
for &(channel, _) in &set.channels {
present[channel.index()] = true;
}
self.composite.channels.keys().all(|channel| present[channel.index()])
}
pub fn invalidate_all(&mut self) {
self.dirty.extend(self.covered_tiles.iter().copied());
}
@@ -974,31 +992,31 @@ impl Session {
pub fn sync_caches(&mut self) {
let sets = &self.doc.project.texture_sets;
self.caches.truncate(sets.len());
for (i, ts) in sets.iter().enumerate() {
match self.caches.get_mut(i) {
Some(c) if c.size == ts.size() => {
if c.uv_padding != ts.uv_padding {
c.uv_padding = ts.uv_padding;
c.padding = Arc::new(display_padding(&self.mesh, ts, &c.gbuf));
c.invalidate_all();
}
let formats = ts.formats();
if c.formats != formats {
c.formats = formats;
c.invalidate_all();
for (index, set) in sets.iter().enumerate() {
match self.caches.get_mut(index) {
Some(cache) if cache.size == set.size() => {
if cache.uv_padding != set.uv_padding {
cache.uv_padding = set.uv_padding;
cache.padding = Arc::new(display_padding(&self.mesh, set, &cache.gbuf));
cache.invalidate_all();
}
let (want, scales) = (ts.channel_list(), ts.block_scales());
if c.composite.channels.keys().copied().collect::<Vec<_>>() != want || c.composite.block_scales != scales {
c.composite = Composite { block_scales: scales, ..Composite::with_size(&want, c.size.0, c.size.1) };
c.upload.extend(texturecraft_compose::all_tiles(c.size.0, c.size.1));
c.invalidate_all();
if !cache.formats.iter().copied().eq(set.iter_formats()) {
cache.formats = set.formats();
cache.invalidate_all();
}
let scales = set.block_scales();
if !cache.has_channels(set) || cache.composite.block_scales != scales {
cache.composite = Composite { block_scales: scales, ..Composite::with_size(&set.channel_list(), cache.size.0, cache.size.1) };
cache.upload.extend(texturecraft_compose::all_tiles(cache.size.0, cache.size.1));
cache.invalidate_all();
}
}
_ => {
let cache = SetCache::new(&self.mesh, ts);
if i < self.caches.len() {
self.caches[i] = cache;
let cache = SetCache::new(&self.mesh, set);
if index < self.caches.len() {
self.caches[index] = cache;
} else {
self.caches.push(cache);
}
+60 -18
View File
@@ -93,18 +93,21 @@ pub fn parts(s: &Session, ts: usize) -> Vec<String> {
}
pub(crate) fn ts_param(s: &Session, p: &Value, cmd: &str) -> Result<usize> {
match u64p(p, "ts") {
Some(t) if (t as usize) < s.set_count() => Ok(t as usize),
Some(t) => Err(bad(cmd, format!("no texture set {t}"))),
None => Ok(s.ts()),
if p.get("ts").is_none_or(Value::is_null) {
return Ok(s.ts());
}
let index = u64p(p, "ts").ok_or_else(|| bad(cmd, "valid `ts` index required"))?;
usize::try_from(index).ok().filter(|&index| index < s.set_count()).ok_or_else(|| bad(cmd, format!("no texture set {index}")))
}
fn select(s: &mut Session, p: &Value) -> Result<Value> {
let ts = u64p(p, "ts")
.map(|index| index as usize)
.filter(|index| *index < s.set_count())
.ok_or_else(|| bad("textureSet.select", "valid `ts` index required"))?;
let cmd = "textureSet.select";
if p.get("ts").is_none_or(Value::is_null) {
return Err(bad(cmd, "valid `ts` index required"));
}
let ts = ts_param(s, p, cmd)?;
select_set(s, ts)?;
Ok(json!({ "ts": ts }))
}
@@ -148,7 +151,8 @@ pub struct ResizeTask {
height: u32,
doc: Document,
mesh: Arc<Mesh>,
/// The session's revision and mesh when the task was made: the result applies only to them.
project_id: u64,
/// The revision and mesh used to calculate this result.
from: (u64, u64),
}
@@ -161,6 +165,7 @@ pub struct ResizeOutput {
/// The set's new caches (None when its UV tile layout moved: the session rebuilds them).
cache: Option<SetCache>,
log: crate::log::SessionLog,
project_id: u64,
from: (u64, u64),
}
@@ -168,7 +173,7 @@ impl ResizeTask {
/// Resample the set's painted pixels (bilinear; strokes are not replayed) and build its
/// caches. Progress goes from 0 to 1.
pub fn run(self, progress: &texturecraft_bake::Progress) -> Result<ResizeOutput> {
let ResizeTask { ts, resolution, height, mut doc, mesh, from } = self;
let ResizeTask { ts, resolution, height, mut doc, mesh, project_id, from } = self;
let set = doc.project.texture_set_mut(ts)?;
let old = set.clone();
set.set_size(resolution, height);
@@ -190,7 +195,7 @@ impl ResizeTask {
let set = doc.project.texture_set(ts)?;
let cache = (crate::session::uv_layout(&old) == crate::session::uv_layout(set)).then(|| SetCache::new(&mesh, set));
progress.done.store(10_000, std::sync::atomic::Ordering::Relaxed);
Ok(ResizeOutput { ts, resolution, height, doc, cache, log, from })
Ok(ResizeOutput { ts, resolution, height, doc, cache, log, project_id, from })
}
}
@@ -212,15 +217,30 @@ impl Session {
let (resolution, height) = (check_resolution(width)?, check_resolution(height)?);
self.doc.project.texture_set(ts)?;
self.cancel_stroke();
Ok(ResizeTask { ts, resolution, height, doc: self.doc.clone(), mesh: self.mesh.clone(), from: (self.revision, self.mesh_id) })
Ok(ResizeTask {
ts,
resolution,
height,
doc: self.doc.clone(),
mesh: self.mesh.clone(),
project_id: self.project_id,
from: (self.revision, self.mesh_id),
})
}
/// Apply a finished resize as one undo step. When the document changed while it ran, the
/// resize runs again here on the current document.
pub fn apply_resize(&mut self, out: ResizeOutput) -> Result<Value> {
/// Apply a finished resize to its original project as one undo step. Edits made while the
/// resize ran are preserved by recomputing from the current document.
pub fn apply_resize(&mut self, mut out: ResizeOutput) -> Result<Value> {
if out.project_id != self.project_id {
return Err(bad("textureSet.resolution", "the project changed while the texture set was resizing"));
}
if out.from != (self.revision, self.mesh_id) || self.stroke_active() {
let task = self.resize_task_to(out.ts, out.resolution, out.height)?;
return self.apply_resize(task.run(&texturecraft_bake::Progress::new())?);
let (ts, width, height) = (out.ts, out.resolution, out.height);
// Release the stale pixels and cache before building their replacement
drop(out);
out = self.resize_task_to(ts, width, height)?.run(&texturecraft_bake::Progress::new())?;
}
let ResizeOutput { ts, resolution, height, doc, cache, log, .. } = out;
@@ -286,7 +306,11 @@ fn channels(s: &mut Session, p: &Value) -> Result<Value> {
return Err(bad(cmd, format!("{} is both added and removed", both.label())));
}
let sets: Vec<usize> = if boolp(p, "allSets").unwrap_or(false) { (0..s.set_count()).collect() } else { vec![ts_param(s, p, cmd)?] };
let all_sets = match p.get("allSets") {
None | Some(Value::Null) => false,
Some(value) => value.as_bool().ok_or_else(|| bad(cmd, "`allSets` must be a boolean"))?,
};
let sets: Vec<usize> = if all_sets { (0..s.set_count()).collect() } else { vec![ts_param(s, p, cmd)?] };
s.edit("Add or remove channels", |s| {
for &ts in &sets {
@@ -494,6 +518,24 @@ mod tests {
assert!(!layer_has_roughness(&s), "the layer's roughness stays off");
}
#[test]
fn invalid_set_selectors_cannot_edit_the_active_set() {
let mut session = crate::sample_session(128, 64).unwrap();
let before = session.doc.project.texture_sets[session.ts()].clone();
for ts in [json!("0"), json!(-1), json!(1_u64 << 32)] {
let params = json!({"ts": ts, "description": "wrong set"});
assert!(crate::execute(&mut session, "textureSet.settings", &params).is_err(), "{ts}");
assert_eq!(session.doc.project.texture_sets[session.ts()], before);
assert!(crate::execute(&mut session, "textureSet.select", &params).is_err(), "{ts}");
}
let invalid_scope = json!({"add": ["user7"], "allSets": "true"});
assert!(crate::execute(&mut session, "textureSet.channels", &invalid_scope).is_err());
assert_eq!(session.doc.project.texture_sets[session.ts()], before);
}
#[test]
fn malformed_size_and_setting_values_are_refused_and_change_nothing() {
let mut s = Session::new_project("t", texturecraft_geom::primitives::material_ball(), "builtin:material_ball", None, 128).unwrap();
+30
View File
@@ -1093,6 +1093,36 @@ fn committed_strokes_settle_to_the_full_composite() {
assert_eq!(full(&mut s), original);
}
#[test]
fn synchronizing_a_saved_channel_order_preserves_the_composite() {
let mut session = texturecraft_engine::sample_session(128, 64).unwrap();
session.doc.project.texture_sets[0].channels.reverse();
let bytes = session.to_project_bytes().unwrap();
let mut reopened = Session::from_project_bytes(&bytes).unwrap();
reopened.update();
reopened.caches[0].upload.clear();
reopened.sync_caches();
assert!(reopened.caches[0].dirty.is_empty(), "the unchanged set should keep its composited tiles");
assert!(reopened.caches[0].upload.is_empty(), "the unchanged set should require no uploads");
}
#[test]
fn a_pending_resize_cannot_change_a_replacement_project() {
let mut session = session_at(128);
let task = session.resize_task_to(0, 512, 256).unwrap();
execute(&mut session, "project.new", &json!({"mesh": "cube", "resolution": 128})).unwrap();
let before = session.doc.clone();
let output = task.run(&texturecraft_engine::bake::Progress::new()).unwrap();
let result = session.apply_resize(output);
assert!(result.is_err(), "a resize from the previous project was accepted");
assert!(same_document(&session.doc, &before));
assert!(session.undo_label().is_none());
}
/// A resize prepared from a snapshot and applied later matches the command, keeps edits made
/// while it ran, and undoes in one step.
#[test]
+1
View File
@@ -942,6 +942,7 @@ fn plan_outputs(project: &Project, ts: usize, mesh_name: &str, opts: &ExportOpti
psd_failures.push((name, FormatError::Invalid(reason.clone())));
continue;
}
if let Err(error) = layered_psd::preflight(set, opts, tile, bit_depth, layers.iter(), budget.working_bytes) {
psd_failures.push((name, error));
continue;
+11 -6
View File
@@ -1298,18 +1298,23 @@ fn an_export_size_that_scales_a_tall_set_past_the_largest_side_is_refused() {
#[test]
fn a_psd_scaled_past_the_largest_side_leaves_the_sets_other_maps() {
let mut fx = Fx::new(&default_channels());
fx.project.texture_sets[0].set_size(RES, RES * 4);
let (width, height) = (RES, RES * 4);
fx.project.texture_sets[0].set_size(width, height);
fx.comp = Composite::with_size(&default_channels(), width, height);
fx.coverage.resize((width * height) as usize, true);
let mut options = one_map(FileFormat::Png, 8, roughness());
let mut psd = options.preset.maps[0].clone();
(psd.file, psd.format, psd.bit_depth, psd.channels) = ("layered".into(), FileFormat::Psd, 8, rgba_half_alpha());
options.preset.maps.push(psd);
options.size = Some(MAX_IMAGE_SIZE / 2);
options.maps.insert(0, MapOverride { size: Some(MAX_IMAGE_SIZE / 4), ..MapOverride::default() });
options.maps.insert(1, MapOverride { size: Some(MAX_IMAGE_SIZE / 2), ..MapOverride::default() });
let plan = list_outputs(&fx.project, 0, "sphere", &options).unwrap();
let files = render_maps(&fx.input(), &options).unwrap();
assert!(plan.len() == 1 && plan[0].format == FileFormat::Png, "{plan:?}");
assert!(plan[0].warnings.iter().any(|warning| is_set_warning(warning)), "{:?}", plan[0].warnings);
assert_eq!(files.len(), 1);
assert!(files[0].name.ends_with(".png"));
assert_eq!(decode(&files[0]).dimensions(), (width, height));
assert!(files[0].warnings.iter().any(|warning| is_set_warning(warning) && warning.contains(&MAX_IMAGE_SIZE.to_string())));
}
#[test]
+34 -19
View File
@@ -20,42 +20,57 @@ pub struct TrianglePartition {
impl TrianglePartition {
/// Group `material`'s triangles of `mesh`: two triangles join when `edges` names a key for both
pub fn new<K: Eq + Hash + Clone>(mesh: &Mesh, material: usize, edges: impl Fn(&Mesh, usize) -> Vec<K>) -> TrianglePartition {
pub fn new<K: Eq + Hash>(mesh: &Mesh, material: usize, edges: impl Fn(&Mesh, usize) -> Vec<K>) -> TrianglePartition {
// Each triangle's edges once, in mesh order so the groups come out the same every time
let triangles: Vec<u32> = mesh.triangles_of(material).map(|triangle| triangle as u32).collect();
let position_of: HashMap<u32, usize> = triangles.iter().enumerate().map(|(position, triangle)| (*triangle, position)).collect();
let mut edge_lists: Vec<Vec<K>> = triangles.iter().map(|triangle| edges(mesh, *triangle as usize)).collect();
let mut by_edge: HashMap<K, Vec<u32>> = HashMap::new();
for (triangle, triangle_edges) in triangles.iter().zip(&edge_lists) {
for edge in triangle_edges {
by_edge.entry(edge.clone()).or_default().push(*triangle);
let mut neighbours = Vec::<Vec<usize>>::new();
let mut edge_ids = Vec::new();
let mut offsets = Vec::with_capacity(triangles.len() + 1);
offsets.push(0);
// Keep compact edge indices for traversal and release the welding keys before the search
{
let mut index_by_edge = HashMap::new();
for (position, &triangle) in triangles.iter().enumerate() {
for edge in edges(mesh, triangle as usize) {
let index = *index_by_edge.entry(edge).or_insert_with(|| {
neighbours.push(Vec::new());
neighbours.len() - 1
});
neighbours[index].push(position);
edge_ids.push(index);
}
offsets.push(edge_ids.len());
}
}
let mut groups = Vec::new();
let mut group_of = HashMap::with_capacity(triangles.len());
for &start in &triangles {
if group_of.contains_key(&start) {
let mut stack = Vec::new();
for (start, &triangle) in triangles.iter().enumerate() {
if group_of.contains_key(&triangle) {
continue;
}
let mut members = Vec::new();
let mut stack = vec![start];
group_of.insert(start, groups.len());
while let Some(triangle) = stack.pop() {
members.push(triangle);
let triangle_edges = position_of.get(&triangle).and_then(|position| edge_lists.get_mut(*position)).map(std::mem::take).unwrap_or_default();
stack.push(start);
group_of.insert(triangle, groups.len());
while let Some(position) = stack.pop() {
members.push(triangles[position]);
// Visit a shared edge once, including when many collapsed faces share the same key
for neighbour in triangle_edges.iter().flat_map(|edge| by_edge.remove(edge).into_iter().flatten()) {
if let std::collections::hash_map::Entry::Vacant(entry) = group_of.entry(neighbour) {
entry.insert(groups.len());
stack.push(neighbour);
// Visit shared edges once even when many collapsed faces share a key
for &edge in &edge_ids[offsets[position]..offsets[position + 1]] {
for neighbour in std::mem::take(&mut neighbours[edge]) {
if let std::collections::hash_map::Entry::Vacant(entry) = group_of.entry(triangles[neighbour]) {
entry.insert(groups.len());
stack.push(neighbour);
}
}
}
}
groups.push(members);
}
TrianglePartition { groups, group_of }
}
+56 -16
View File
@@ -453,27 +453,34 @@ impl GpuTracer {
if self.materials.as_ref().is_some_and(|m| m.rev == rev) {
return Ok(false);
}
let sets = renderer.display_textures();
if sets.len() > MAX_SETS || sets.iter().any(|s| s.len() != KINDS) {
return Err(format!("GPU path tracing takes at most {MAX_SETS} texture sets"));
}
let layers = sets.len() as u32 + 1;
let limits = device.limits();
if layers > limits.max_texture_array_layers {
return Err(format!("this GPU takes at most {} texture sets", limits.max_texture_array_layers.saturating_sub(1)));
}
let old = self.materials.take();
let mut arrays = Vec::with_capacity(KINDS);
for (k, kind) in DisplayKind::ALL.into_iter().enumerate() {
let size = sets.iter().filter_map(|s| s.get(k)).fold((1, 1), |(w, h), t| (t.width().max(w), t.height().max(h)));
// Fold tall textures into adjacent bands within the widest layer
let sources = sets.iter().filter_map(|set| set.get(k).copied());
let width = sources.clone().map(wgpu::Texture::width).max().unwrap_or(1);
let height = sources.clone().map(|source| source.height().div_ceil(width / source.width())).max().unwrap_or(1);
let reuse =
old.as_ref().and_then(|m| m.arrays.get(k)).filter(|(t, _)| (t.width(), t.height(), t.depth_or_array_layers()) == (size.0, size.1, layers));
old.as_ref().and_then(|m| m.arrays.get(k)).filter(|(t, _)| (t.width(), t.height(), t.depth_or_array_layers()) == (width, height, layers));
let (tex, view) = match reuse {
Some(a) => a.clone(),
None => scoped(device, "GPU path tracing: material textures", || {
let tex = device.create_texture(&wgpu::TextureDescriptor {
label: Some("tc_trace_material"),
size: wgpu::Extent3d { width: size.0, height: size.1, depth_or_array_layers: layers },
size: wgpu::Extent3d { width, height, depth_or_array_layers: layers },
mip_level_count: 1,
sample_count: 1,
dimension: wgpu::TextureDimension::D2,
@@ -488,19 +495,24 @@ impl GpuTracer {
if reuse.is_none() {
self.bind = None;
}
for (layer, src) in sets.iter().filter_map(|s| s.get(k)).enumerate() {
encoder.copy_texture_to_texture(
src.as_image_copy(),
wgpu::TexelCopyTextureInfo {
texture: &tex,
mip_level: 0,
origin: wgpu::Origin3d { x: 0, y: 0, z: layer as u32 },
aspect: wgpu::TextureAspect::All,
},
wgpu::Extent3d { width: src.width(), height: src.height(), depth_or_array_layers: 1 },
);
for (layer, source) in sources.enumerate() {
for band in 0..source.height().div_ceil(height) {
let source_y = band * height;
encoder.copy_texture_to_texture(
wgpu::TexelCopyTextureInfo { origin: wgpu::Origin3d { x: 0, y: source_y, z: 0 }, ..source.as_image_copy() },
wgpu::TexelCopyTextureInfo {
texture: &tex,
mip_level: 0,
origin: wgpu::Origin3d { x: band * source.width(), y: 0, z: layer as u32 },
aspect: wgpu::TextureAspect::All,
},
wgpu::Extent3d { width: source.width(), height: height.min(source.height() - source_y), depth_or_array_layers: 1 },
);
}
}
// The default material: one texel of the kind's neutral value.
// The default material occupies one neutral texel in the last layer
let texel = kind.default_texel();
queue.write_texture(
wgpu::TexelCopyTextureInfo {
@@ -515,10 +527,11 @@ impl GpuTracer {
);
arrays.push((tex, view));
}
let mut info: Vec<[f32; 3]> = sets
.iter()
.map(|s| {
// The set's size is its largest texture's; any kind may still be a 1×1 placeholder.
// Individual kinds may still be neutral 1×1 placeholders
let dims = s.iter().fold((1, 1), |(w, h), t| (t.width().max(w), t.height().max(h)));
let small = s.iter().enumerate().filter(|(_, t)| (t.width(), t.height()) != dims).fold(0u32, |m, (k, _)| m | 1 << k);
[dims.0 as f32, dims.1 as f32, small as f32]
@@ -1036,6 +1049,33 @@ mod tests {
}
}
#[test]
fn mixed_aspect_materials_preserve_texels_and_bound_array_storage() {
let Some((mut headless, mut tracer)) = gpu() else { return };
let scene = sphere_scene(&mut headless, crate::ibl::environment("Studio Soft", 32), &WHITE);
let display = TraceDisplay::from_display(&Default::default());
let settings = TraceSettings { bounces: 2 };
let tall = ((128, 513), 0);
let wide = ((512, 128), 1);
headless.renderer.set_texture_sets(&headless.device, &headless.queue, &[tall], 1);
for tile_y in 0..9 {
let color = [23 * tile_y as u8, 255 - 23 * tile_y as u8, 0, 255];
headless.renderer.upload_tile(&headless.device, &headless.queue, 0, DisplayKind::BaseColor, 0, tile_y, &color.repeat(64 * 64));
}
let render = |tracer: &mut GpuTracer, headless: &Headless| {
tracer.render(&headless.device, &headless.queue, &headless.renderer, &scene, &camera(), &settings, &display, [48, 36], 8).unwrap().2
};
let reference = render(&mut tracer, &headless);
headless.renderer.set_texture_sets(&headless.device, &headless.queue, &[tall, wide], 2);
headless.renderer.upload_tile(&headless.device, &headless.queue, 1, DisplayKind::BaseColor, 0, 0, &[255; 64 * 64 * 4]);
let mixed = render(&mut tracer, &headless);
assert_eq!(mixed, reference, "adding another material must preserve every sample of the tall set");
let array = &tracer.materials.as_ref().unwrap().arrays[0].0;
assert!(array.width() * array.height() < 2 * 128 * 513, "a partial last band must still fit in a compact array layer");
}
#[test]
fn gpu_reads_full_size_channels_beside_placeholders() {
// A 1×1 base-color placeholder must not limit sampling of the full-size roughness map
+1 -1
View File
@@ -434,7 +434,7 @@ const DITHER_FRAME_STEP: vec2<f32> = vec2<f32>(17.0, 59.0);
// Lit single-channel views keep the legacy specular level multiplier
const LEGACY_DIELECTRIC_F0_SCALE: f32 = 0.08;
// The change of height per texel (`ts` = one texel in UV) to the right and down: Sobel when g.uv_rotation.w is 1, else the neighbours across (as HeightToNormalMethod::slope)
// Match the axial and Sobel kernels in HeightToNormalMethod::slope
fn height_slope(uv: vec2<f32>, ts: vec2<f32>) -> vec2<f32> {
let r = textureSample(t_height, samp, uv + vec2<f32>(ts.x, 0.0)).r;
let l = textureSample(t_height, samp, uv - vec2<f32>(ts.x, 0.0)).r;
+26 -20
View File
@@ -213,31 +213,37 @@ fn occluded(o: vec3<f32>, d: vec3<f32>) -> bool {
// ---- Materials ----
// The change of height per texel to the right and down: Sobel when smooth, else the neighbours across (as HeightToNormalMethod::slope)
// Match the axial and Sobel kernels in HeightToNormalMethod::slope
fn height_slope(layer: u32, uv: vec2<f32>, sobel: bool) -> vec2<f32> {
let r = textureLoad(t_height, texel(layer, 3u, uv, 1, 0), layer, 0).r;
let l = textureLoad(t_height, texel(layer, 3u, uv, -1, 0), layer, 0).r;
let d = textureLoad(t_height, texel(layer, 3u, uv, 0, 1), layer, 0).r;
let u = textureLoad(t_height, texel(layer, 3u, uv, 0, -1), layer, 0).r;
let r = textureLoad(t_height, texel(layer, 3u, uv, 1, 0, i32(textureDimensions(t_height).y)), layer, 0).r;
let l = textureLoad(t_height, texel(layer, 3u, uv, -1, 0, i32(textureDimensions(t_height).y)), layer, 0).r;
let d = textureLoad(t_height, texel(layer, 3u, uv, 0, 1, i32(textureDimensions(t_height).y)), layer, 0).r;
let u = textureLoad(t_height, texel(layer, 3u, uv, 0, -1, i32(textureDimensions(t_height).y)), layer, 0).r;
if (!sobel) {
return vec2<f32>(r - l, d - u) * 0.5;
}
let ru = textureLoad(t_height, texel(layer, 3u, uv, 1, -1), layer, 0).r;
let rd = textureLoad(t_height, texel(layer, 3u, uv, 1, 1), layer, 0).r;
let lu = textureLoad(t_height, texel(layer, 3u, uv, -1, -1), layer, 0).r;
let ld = textureLoad(t_height, texel(layer, 3u, uv, -1, 1), layer, 0).r;
let ru = textureLoad(t_height, texel(layer, 3u, uv, 1, -1, i32(textureDimensions(t_height).y)), layer, 0).r;
let rd = textureLoad(t_height, texel(layer, 3u, uv, 1, 1, i32(textureDimensions(t_height).y)), layer, 0).r;
let lu = textureLoad(t_height, texel(layer, 3u, uv, -1, -1, i32(textureDimensions(t_height).y)), layer, 0).r;
let ld = textureLoad(t_height, texel(layer, 3u, uv, -1, 1, i32(textureDimensions(t_height).y)), layer, 0).r;
return vec2<f32>(ru + 2.0 * r + rd - lu - 2.0 * l - ld, ld + 2.0 * d + rd - lu - 2.0 * u - ru) / 8.0;
}
// Texel of `uv` (nearest, wrapped) in kind `k` of layer `layer`, offset by (dx, dy).
fn texel(layer: u32, k: u32, uv: vec2<f32>, dx: i32, dy: i32) -> vec2<i32> {
// Wrap in the source texture before mapping the sample into its array layer
fn texel(layer: u32, k: u32, uv: vec2<f32>, dx: i32, dy: i32, band_height: i32) -> vec2<i32> {
let info = P.sets[layer];
let small = ((u32(info.z) >> k) & 1u) == 1u;
let dims = select(max(vec2<i32>(info.xy), vec2<i32>(1)), vec2<i32>(1), small);
let x = i32(floor(uv.x * f32(dims.x))) + dx;
let y = i32(floor(uv.y * f32(dims.y))) + dy;
return vec2<i32>(((x % dims.x) + dims.x) % dims.x, ((y % dims.y) + dims.y) % dims.y);
let wrapped = vec2<i32>(((x % dims.x) + dims.x) % dims.x, ((y % dims.y) + dims.y) % dims.y);
if (wrapped.y < band_height) {
return wrapped;
}
// The upload lays successive vertical bands side by side
return vec2<i32>(wrapped.x + (wrapped.y / band_height) * dims.x, wrapped.y % band_height);
}
struct Surface {
@@ -308,14 +314,14 @@ fn surface(hit: Hit, o: vec3<f32>, d: vec3<f32>) -> Surface {
let uv = vec2<f32>(verts[ix.x * 2u].w, a0.w) * w0 + vec2<f32>(verts[ix.y * 2u].w, a1.w) * u + vec2<f32>(verts[ix.z * 2u].w, a2.w) * v;
let tw = a0.xyz * w0 + a1.xyz * u + a2.xyz * v;
let base_t = textureLoad(t_base, texel(layer, 0u, uv, 0, 0), layer, 0);
let orm = textureLoad(t_orm, texel(layer, 1u, uv, 0, 0), layer, 0);
let nrm_t = textureLoad(t_normal, texel(layer, 2u, uv, 0, 0), layer, 0);
let hgt = textureLoad(t_height, texel(layer, 3u, uv, 0, 0), layer, 0);
let emi = textureLoad(t_emissive, texel(layer, 4u, uv, 0, 0), layer, 0);
let lobes = textureLoad(t_lobes, texel(layer, 5u, uv, 0, 0), layer, 0);
let sheen_t = textureLoad(t_sheen, texel(layer, 6u, uv, 0, 0), layer, 0);
let extra = textureLoad(t_extra, texel(layer, 7u, uv, 0, 0), layer, 0);
let base_t = textureLoad(t_base, texel(layer, 0u, uv, 0, 0, i32(textureDimensions(t_base).y)), layer, 0);
let orm = textureLoad(t_orm, texel(layer, 1u, uv, 0, 0, i32(textureDimensions(t_orm).y)), layer, 0);
let nrm_t = textureLoad(t_normal, texel(layer, 2u, uv, 0, 0, i32(textureDimensions(t_normal).y)), layer, 0);
let hgt = textureLoad(t_height, texel(layer, 3u, uv, 0, 0, i32(textureDimensions(t_height).y)), layer, 0);
let emi = textureLoad(t_emissive, texel(layer, 4u, uv, 0, 0, i32(textureDimensions(t_emissive).y)), layer, 0);
let lobes = textureLoad(t_lobes, texel(layer, 5u, uv, 0, 0, i32(textureDimensions(t_lobes).y)), layer, 0);
let sheen_t = textureLoad(t_sheen, texel(layer, 6u, uv, 0, 0, i32(textureDimensions(t_sheen).y)), layer, 0);
let extra = textureLoad(t_extra, texel(layer, 7u, uv, 0, 0, i32(textureDimensions(t_extra).y)), layer, 0);
let info = P.sets[layer];
-2
View File
@@ -268,7 +268,6 @@ fn matching_not_enabled(ui: &mut Ui) {
let tokens = Tokens::get(ui.ctx());
let mut text = egui::text::LayoutJob::default();
let format = |font| egui::TextFormat { font_id: font, color: tokens.text, ..Default::default() };
// One sentence to translate, its setting and value kept apart to set them in SemiBold
let sentence = tr("Set {setting} to {value} to pair parts by name.");
let (before, rest) = sentence.split_once("{setting}").unwrap_or(("", sentence));
@@ -296,7 +295,6 @@ fn baking_process(ui: &mut Ui, maps: &[BakeLogMap], issues_only: bool) -> Option
let mut opened = None;
for (index, row) in maps.iter().enumerate().filter(|(_, row)| !issues_only || row.state.is_issue()) {
let (rect, open_clicked) = map_row(ui, row);
// Bring the next map into view too, so the list shows what comes after the map being baked
if newly_followed && followed == Some(index) {
ui.scroll_to_rect(rect.with_max_y(rect.bottom() + ROW_HEIGHT), None);
+12 -49
View File
@@ -1,12 +1,13 @@
//! The dialog that adds and removes a texture set's channels: every channel by group, ticked when the set has it
use std::sync::Arc;
mod footer_layout;
use egui::{Align2, CornerRadius, FontId, Galley, Rect, RichText, Sense, Stroke, StrokeKind, Ui, pos2, vec2};
use egui::{Align2, CornerRadius, FontId, Rect, RichText, Sense, Stroke, StrokeKind, Ui, pos2, vec2};
use egui_phosphor::regular as icon;
use serde_json::json;
use texturecraft_engine::core::{Channel, ChannelGroup, TextureSet};
use self::footer_layout::FooterLayout;
use crate::TextureCraftApp;
use crate::i18n::tr;
use crate::property_sheet::{CHECK_SIZE, PropertySheet, paint_check, paint_keyboard_focus};
@@ -107,11 +108,11 @@ impl ChannelManager {
let closed = title_bar(ui, &tokens, opening);
ui.add_space(BODY_AIR);
// The list gets what the title bar, the footer and the air between them leave, so Apply stays in a short window
let window = ctx.content_rect().height();
let room = window - TITLE_BAR_HEIGHT - BODY_AIR - FOOTER_AIR - footer.height - EDGE_AIR;
let max_height = (window * MAX_HEIGHT_SHARE).min(room).max(0.0);
egui::ScrollArea::both().auto_shrink([false, true]).max_height(max_height).show(ui, |ui| manager.columns(ui));
// Reserve room for the title and footer so Apply stays visible
let window_height = ctx.content_rect().height();
let room = window_height - TITLE_BAR_HEIGHT - BODY_AIR - FOOTER_AIR - footer.height() - EDGE_AIR;
let max_height = (window_height * MAX_HEIGHT_SHARE).min(room).max(0.0);
egui::ScrollArea::both().auto_shrink([false, true]).min_scrolled_height(0.0).max_height(max_height).show(ui, |ui| manager.columns(ui));
ui.add_space(FOOTER_AIR);
let (apply, cancel) = manager.footer(ui, &tokens, footer);
ui.add_space(EDGE_AIR);
@@ -212,60 +213,22 @@ impl ChannelManager {
/// "Apply to all Texture Sets", the ⊘ legend, then Cancel and Apply at the right; returns (Apply, Cancel) clicked
fn footer(&mut self, ui: &mut Ui, tokens: &Tokens, layout: FooterLayout) -> (bool, bool) {
let FooterLayout { label, text, legend_text, legend_below, height } = layout;
let (row, _) = ui.allocate_exact_size(vec2(ui.available_width(), height), Sense::hover());
let (row, _) = ui.allocate_exact_size(vec2(ui.available_width(), layout.height()), Sense::hover());
ui.painter().hline(row.x_range(), row.top() - FOOTER_AIR / 2.0, Stroke::new(1.0, tokens.separator));
let center_y = row.top() + BUTTON_SIZE.y / 2.0;
let check = Rect::from_min_size(pos2(row.left() + EDGE_AIR, center_y - CHECK_SIZE / 2.0), vec2(CHECK_SIZE, CHECK_SIZE));
let hit = Rect::from_min_max(pos2(check.left(), row.top()), pos2(check.right() + CHECK_TO_LABEL + text.size().x, row.top() + BUTTON_SIZE.y));
let (check, hit) = layout.checkbox_rects(row);
let response = ui.interact(hit, ui.scope_id().with("all_sets"), Sense::click());
response.widget_info(|| egui::WidgetInfo::selected(egui::Role::CheckBox, true, self.all_sets, label));
response.widget_info(|| egui::WidgetInfo::selected(egui::Role::CheckBox, true, self.all_sets, layout.checkbox_label));
if response.clicked() {
self.all_sets = !self.all_sets;
}
paint_check(ui.painter(), tokens, check, Some(self.all_sets), response.hovered());
ui.painter().galley(pos2(check.right() + CHECK_TO_LABEL, center_y - text.size().y / 2.0), text, tokens.text);
paint_keyboard_focus(ui, &response, tokens);
let legend = if legend_below { pos2(check.left(), center_y + BUTTON_SIZE.y + BUTTON_GAP) } else { pos2(hit.right() + LEGEND_GAP, center_y) };
let glyph = ui.painter().text(legend, Align2::LEFT_CENTER, icon::PROHIBIT, FontId::proportional(SMALL_TEXT_SIZE), tokens.text_dim);
let text_left = glyph.right() + LEGEND_GLYPH_TO_TEXT;
ui.painter().galley(pos2(text_left, legend.y - legend_text.size().y / 2.0), legend_text, tokens.text_dim);
let apply = Rect::from_min_size(pos2(row.right() - EDGE_AIR - BUTTON_SIZE.x, row.bottom() - BUTTON_SIZE.y), BUTTON_SIZE);
let cancel = apply.translate(vec2(-(BUTTON_SIZE.x + BUTTON_GAP), 0.0));
let (apply, cancel) = layout.paint_labels(ui, tokens, row, check, hit);
(dialog_button(ui, tokens, apply, tr("Apply")), dialog_button(ui, tokens, cancel, tr("Cancel")))
}
}
/// The footer's texts and rows, worked out before the channel list so the list can leave the footer its height
struct FooterLayout {
label: &'static str,
text: Arc<Galley>,
legend_text: Arc<Galley>,
legend_below: bool,
height: f32,
}
impl FooterLayout {
fn new(ui: &Ui, tokens: &Tokens) -> Self {
let width = ui.available_width();
let label = tr("Apply to all Texture Sets");
let text = ui.painter().layout_no_wrap(label.to_owned(), FontId::proportional(TEXT_SIZE), tokens.text);
let legend_text = ui.painter().layout_no_wrap(tr("Not used by the shader").to_owned(), FontId::proportional(SMALL_TEXT_SIZE), tokens.text_dim);
let left_width = EDGE_AIR + CHECK_SIZE + CHECK_TO_LABEL + text.size().x + LEGEND_GAP + SMALL_TEXT_SIZE + LEGEND_GLYPH_TO_TEXT + legend_text.size().x;
// A narrow footer puts the buttons on a row of their own, and the legend under the check when the two don't fit side by side
let legend_below = width < left_width + EDGE_AIR;
let stacked = legend_below || width < left_width + BUTTON_GAP + 2.0 * BUTTON_SIZE.x + 2.0 * EDGE_AIR;
let rows = 1.0 + f32::from(u8::from(legend_below)) + f32::from(u8::from(stacked));
let height = rows * BUTTON_SIZE.y + (rows - 1.0) * BUTTON_GAP;
FooterLayout { label, text, legend_text, legend_below, height }
}
}
/// The title and × at the right; returns whether × was clicked
fn title_bar(ui: &mut Ui, tokens: &Tokens, opening: bool) -> bool {
let (bar, _) = ui.allocate_exact_size(vec2(ui.available_width(), TITLE_BAR_HEIGHT), Sense::hover());
@@ -0,0 +1,97 @@
use std::sync::Arc;
use egui::{FontId, Galley, Rect, Sense, Ui, pos2, vec2};
use egui_phosphor::regular as icon;
use super::{BUTTON_GAP, BUTTON_SIZE, CHECK_SIZE, CHECK_TO_LABEL, EDGE_AIR, LEGEND_GAP, LEGEND_GLYPH_TO_TEXT, SMALL_TEXT_SIZE, TEXT_SIZE};
use crate::i18n::tr;
use crate::theme::Tokens;
/// The measured footer, used for both painting and reserving space below the channel list
pub(super) struct FooterLayout {
pub(super) checkbox_label: &'static str,
checkbox_text: Arc<Galley>,
legend_label: &'static str,
legend_glyph: Arc<Galley>,
legend_text: Arc<Galley>,
first_row_height: f32,
legend_row_height: f32,
buttons_row_height: f32,
button_gap: f32,
button_width: f32,
}
impl FooterLayout {
pub(super) fn new(ui: &Ui, tokens: &Tokens) -> Self {
let content_width = (ui.available_width() - 2.0 * EDGE_AIR).max(0.0);
let checkbox_label = tr("Apply to all Texture Sets");
let checkbox_text =
ui.painter().layout(checkbox_label.into(), FontId::proportional(TEXT_SIZE), tokens.text, (content_width - CHECK_SIZE - CHECK_TO_LABEL).max(0.0));
let legend_label = tr("Not used by the shader");
let legend_font = FontId::proportional(SMALL_TEXT_SIZE);
let legend_glyph = ui.painter().layout_no_wrap(icon::PROHIBIT.into(), legend_font.clone(), tokens.text_dim);
let legend_text_offset = legend_glyph.size().x + LEGEND_GLYPH_TO_TEXT;
let legend_text = ui.painter().layout(legend_label.into(), legend_font, tokens.text_dim, (content_width - legend_text_offset).max(0.0));
let left_width = CHECK_SIZE + CHECK_TO_LABEL + checkbox_text.size().x + LEGEND_GAP + legend_text_offset + legend_text.size().x;
let checkbox_height = BUTTON_SIZE.y.max(checkbox_text.size().y);
let legend_height = legend_glyph.size().y.max(legend_text.size().y);
let (first_row_height, legend_row_height) = if left_width > content_width {
(checkbox_height, BUTTON_GAP + BUTTON_SIZE.y.max(legend_height))
} else {
(checkbox_height.max(legend_height), 0.0)
};
let buttons_row_height = if left_width + 2.0 * (BUTTON_SIZE.x + BUTTON_GAP) > content_width { BUTTON_GAP + BUTTON_SIZE.y } else { 0.0 };
let button_gap = BUTTON_GAP.min(content_width);
let button_width = BUTTON_SIZE.x.min((content_width - button_gap) / 2.0);
Self {
checkbox_label,
checkbox_text,
legend_label,
legend_glyph,
legend_text,
first_row_height,
legend_row_height,
buttons_row_height,
button_gap,
button_width,
}
}
pub(super) fn height(&self) -> f32 {
self.first_row_height + self.legend_row_height + self.buttons_row_height
}
pub(super) fn checkbox_rects(&self, row: Rect) -> (Rect, Rect) {
let left = row.left() + EDGE_AIR;
let hit = Rect::from_min_size(pos2(left, row.top()), vec2(CHECK_SIZE + CHECK_TO_LABEL + self.checkbox_text.size().x, self.first_row_height));
let check = Rect::from_center_size(pos2(left + CHECK_SIZE / 2.0, hit.center().y), vec2(CHECK_SIZE, CHECK_SIZE));
(check, hit)
}
pub(super) fn paint_labels(self, ui: &Ui, tokens: &Tokens, row: Rect, check: Rect, hit: Rect) -> (Rect, Rect) {
let paint = |left, center, galley: Arc<Galley>, color| {
ui.painter().galley(pos2(left, center - galley.size().y / 2.0), galley, color);
};
paint(check.right() + CHECK_TO_LABEL, hit.center().y, self.checkbox_text, tokens.text);
let (legend_left, legend_center_y) = if self.legend_row_height > 0.0 {
(check.left(), hit.bottom() + (BUTTON_GAP + self.legend_row_height) / 2.0)
} else {
(hit.right() + LEGEND_GAP, hit.center().y)
};
let legend_offset = self.legend_glyph.size().x + LEGEND_GLYPH_TO_TEXT;
let legend_height = self.legend_glyph.size().y.max(self.legend_text.size().y);
let legend_rect =
Rect::from_min_size(pos2(legend_left, legend_center_y - legend_height / 2.0), vec2(legend_offset + self.legend_text.size().x, legend_height));
ui.interact(legend_rect, ui.scope_id().with("legend"), Sense::hover())
.widget_info(|| egui::WidgetInfo::labeled(egui::Role::Label, true, self.legend_label));
paint(legend_left, legend_center_y, self.legend_glyph, tokens.text_dim);
paint(legend_left + legend_offset, legend_center_y, self.legend_text, tokens.text_dim);
let apply = Rect::from_min_size(pos2(row.right() - EDGE_AIR - self.button_width, row.bottom() - BUTTON_SIZE.y), vec2(self.button_width, BUTTON_SIZE.y));
let cancel = apply.translate(vec2(-(self.button_width + self.button_gap), 0.0));
(apply, cancel)
}
}
-2
View File
@@ -30,7 +30,6 @@ pub enum Panel {
Assets,
/// A second Assets panel with its own search, type and folder (the Assets panel's folder button)
AssetsSecond,
// Saved layouts name the bake panels by their earlier names
#[serde(rename = "BakeMaps")]
MeshMapSettings,
@@ -116,7 +115,6 @@ impl Panel {
match self {
Panel::Viewport => "Viewport",
Panel::Assets => "Assets",
// The second panel shows every type at first, so it's named for that, as the reference names it
Panel::AssetsSecond => "All",
Panel::MeshMapSettings => "Mesh Map Settings",
+2 -1
View File
@@ -378,7 +378,8 @@ mod tests {
assert_eq!(Script::of_language("de"), None);
assert_eq!(Script::of_language("ru"), None);
for l in &crate::i18n::LANGUAGES {
// Both UI fonts already cover Cyrillic
// Past the Latin blocks and their diacritics. Cyrillic needs no fallback: the UI fonts
// themselves carry it (egui's Ubuntu and craft-fonts' Inter).
let other_script = l.name.chars().any(|c| c > '\u{036F}' && !('\u{0400}'..='\u{04FF}').contains(&c));
assert_eq!(other_script, Script::of_language(l.code).is_some(), "{}", l.code);
}
+1 -1
View File
@@ -526,7 +526,7 @@ pub fn shortcuts(app: &mut TextureCraftApp, ctx: &egui::Context) {
app.ui.export.rename_key = true;
}
// Give the hovered texture set list first use of its rename and menu keys, as Escape, never under a dialog
// Keep the texture set list's shortcuts inactive behind a dialog
if over_set_list && !modal_open {
let menu = input.consume_key(Modifiers::SHIFT, Key::F10) || input.consume_key(Modifiers::NONE, Key::Menu);
set_list_keys = (input.consume_key(Modifiers::NONE, Key::F2), menu);
@@ -82,7 +82,7 @@ impl PropertySheet<'_> {
/// Controls the sheet has no row for yet, laid out by egui between the panel's edges
pub(crate) fn embed<R>(&mut self, body: impl FnOnce(&mut egui::Ui) -> R) -> R {
let width = self.right - self.left;
let width = (self.right - self.left).max(0.0);
let top = self.cursor_y();
let inner = self.ui.horizontal(|ui| {
ui.add_space(self.left - ui.cursor().left());
+40
View File
@@ -553,6 +553,11 @@ fn glyph_button(ui: &mut Ui, id: impl egui::AsIdSalt, rect: Rect, glyph: &str, l
#[cfg(test)]
mod tests {
use std::sync::{
Arc,
atomic::{AtomicBool, Ordering},
};
use egui_kittest::Harness;
use egui_kittest::kittest::Queryable as _;
@@ -710,6 +715,41 @@ mod tests {
assert!(harness.state().ui.mode == mode, "the mode stayed");
}
#[test]
fn a_modal_opening_over_the_hovered_list_blocks_its_row_keys() {
let mut harness = harness("material_ball");
let name = harness.state().session.doc.project.texture_sets[1].name.clone();
click(&mut harness, egui::Role::ListItem, &name, egui::PointerButton::Primary);
harness.state_mut().ui.keymap.insert("ui.layout.3d".into(), "F7".into());
// Open the modal after the list records its hover for the next pass
let modal = egui::LayerId::new(egui::Order::Foreground, egui::Id::unique("test_modal"));
let open = Arc::new(AtomicBool::new(false));
let open_in_pass = Arc::clone(&open);
harness.ctx.on_end_pass(
"open test modal",
Arc::new(move |ui| {
if open_in_pass.swap(false, Ordering::Relaxed) {
ui.ctx().memory_mut(|memory| memory.set_modal_layer(modal));
}
}),
);
for (key, modifiers) in [(egui::Key::F2, egui::Modifiers::NONE), (egui::Key::F10, egui::Modifiers::SHIFT), (egui::Key::Menu, egui::Modifiers::NONE)] {
harness.run_steps(2);
open.store(true, Ordering::Relaxed);
harness.step();
assert_eq!(harness.ctx.memory(|memory| memory.top_modal_layer()), Some(modal));
assert!(pointer_over(&harness.ctx), "the list still reports hover from the opening pass");
harness.event(egui::Event::Key { key, physical_key: None, pressed: true, repeat: false, modifiers });
harness.step();
assert!(ListState::stored(&harness.ctx).unwrap().edit.is_none(), "{key:?} did not start a rename behind the modal");
assert!(!Popup::is_any_open(&harness.ctx), "{key:?} did not open the row menu behind the modal");
}
}
#[test]
fn a_rename_under_way_is_dropped_when_another_project_replaces_this_one() {
let mut harness = harness("material_ball");
@@ -26,7 +26,7 @@ impl ListState {
egui::Id::unique("texture_set_list_state")
}
/// The state for the project and mesh `owner`; another project or mesh starts over, keeping only the descriptions choice
/// Restore row state for `owner`. The description preference and last hover pass survive a change of project or mesh.
pub(crate) fn load(ctx: &egui::Context, owner: (u64, u64)) -> Self {
let state: Self = ctx.data(|data| data.get_temp::<Self>(Self::id())).unwrap_or_default();
if state.owner == owner {
+32 -3
View File
@@ -171,6 +171,10 @@ fn channels(app: &mut TextureCraftApp, sheet: &mut PropertySheet<'_>, ts: usize,
/// A channel: its name, its format with the gear that lists the formats, and × (Base color stays); returns the format picked and whether × was clicked
fn channel_row(sheet: &mut PropertySheet<'_>, channel: Channel, format: ChannelFormat) -> (Option<ChannelFormat>, bool) {
sheet.embed(|ui| {
if ui.available_width() < 2.0 * GLYPH_BUTTON + GLYPH_GAP {
return (None, false);
}
let tokens = Tokens::get(ui.ctx());
let (rect, _) = ui.allocate_exact_size(vec2(ui.available_width(), CHANNEL_ROW_HEIGHT), Sense::hover());
let name = tr(channel.label());
@@ -469,11 +473,36 @@ mod tests {
}
#[test]
fn a_short_channel_window_keeps_apply_on_screen() {
// A narrow window stacks the footer to three rows: the channel list must leave room for all of them
fn a_very_narrow_channel_window_wraps_its_checkbox_label() {
let mut harness = harness("material_ball");
click(&mut harness, egui::Role::Button, "Add or remove channels");
harness.set_size(vec2(300.0, 400.0));
harness.set_size(vec2(165.0, 300.0));
harness.run_steps(5);
let label = "Apply to all Texture Sets";
let (text, clip) = harness
.output()
.shapes
.iter()
.find_map(|shape| match &shape.shape {
egui::Shape::Text(text) if text.galley.text() == label => Some((text.visual_bounding_rect(), shape.clip_rect)),
_ => None,
})
.expect("the footer paints its checkbox label");
assert!(clip.contains_rect(text), "the checkbox text must fit on screen: {text:?}");
let checkbox = harness.get_by_role_and_label(egui::Role::CheckBox, label).rect();
let legend = harness.get_by_role_and_label(egui::Role::Label, "Not used by the shader").rect();
let apply = harness.get_by_role_and_label(egui::Role::Button, "Apply").rect();
assert!(checkbox.bottom() < legend.top() && legend.bottom() < apply.top(), "the three footer rows must stay separate");
}
#[test]
fn a_short_channel_window_keeps_apply_on_screen() {
let mut harness = harness("material_ball");
click(&mut harness, egui::Role::Button, "Add or remove channels");
harness.set_size(vec2(300.0, 175.0));
harness.run_steps(5);
let screen = harness.ctx.content_rect();
-1
View File
@@ -33,7 +33,6 @@ impl ToastAction {
ToastAction::UpdateResources { project } if project != app.session.project_id => {}
#[cfg(not(target_arch = "wasm32"))]
ToastAction::UpdateResources { .. } => crate::resources_updater::update(app, None),
// The browser has no files to read again
#[cfg(target_arch = "wasm32")]
ToastAction::UpdateResources { .. } => {}
-1
View File
@@ -488,7 +488,6 @@ pub fn tool_shelf(app: &mut TextureCraftApp, ui: &mut egui::Ui) {
let bake_brush = tool == Tool::Paint && app.ui.bake_paint_brush.on;
(bake_brush, bake_brush)
}
// A greyed tool never shows as selected, even while it stays equipped
_ => {
let usable = crate::menus::enabled(app, &command);
+24 -2
View File
@@ -72,11 +72,32 @@ fn the_view_shows_each_map_as_it_lands_and_the_previous_mode_comes_back() {
#[test]
fn cancelling_before_a_map_finishes_restores_the_view_and_leaves_the_document_alone() {
use std::sync::{Arc, atomic::Ordering, mpsc};
use texturecraft_engine::bake::Progress;
use texturecraft_ui_egui::RunningBake;
let mut harness = harness();
let before = harness.state().session.doc.baked.get(&0).cloned();
let progress = Arc::new(Progress::new());
// One frame starts the worker; a finished map shows only from the next one
harness.state_mut().start_bake(vec![0]);
// Keep both worker channels open and empty so cancellation precedes the first map
let (_map_sender, maps) = mpsc::channel();
let (_result_sender, receiver) = mpsc::channel();
let app = harness.state_mut();
app.start_bake(vec![0]);
let job = app.bake.as_mut().unwrap();
let set_index = job.queue.remove(0);
job.current = Some(RunningBake {
set_index,
progress: Arc::clone(&progress),
receiver,
maps,
maps_done: Default::default(),
maps_total: MAPS.len(),
finished: Default::default(),
sources: Default::default(),
painted_stroke: 0,
});
harness.run_steps(1);
assert!(harness.state().session.bake_preview_active());
@@ -87,6 +108,7 @@ fn cancelling_before_a_map_finishes_restores_the_view_and_leaves_the_document_al
harness.state_mut().cancel_bake();
harness.run_steps(2);
assert!(progress.cancel.load(Ordering::Relaxed), "cancellation reaches the running worker");
assert_eq!(harness.state().session.view, ViewMode::UvChecker);
assert!(!harness.state().session.bake_preview_active() && harness.state().bake.is_none());
assert_eq!(harness.state().session.doc.baked.get(&0).cloned(), before);
+21
View File
@@ -237,6 +237,27 @@ project file or an export (`file.exportTextures` and the CLI export the whole st
back), and removing the soloed layer ends it. `session.inspect` reports it as `solo`
(`{layer, ignoreMask}` or `null`).
### Texture sets
`textureSet.resolution {ts: 0, resolution: 512, height: 256}` resizes the working
texture set to 512 texels across and 256 down. Each side must be a power of two
from 128 to 8192. Omitting `height` makes the set square. A set with individual
UV tile resolution overrides must stay square. Export size overrides set the
width and preserve the texture set's aspect ratio.
`textureSet.settings {ts: 0, normalMixing: "replace", aoMixing: "none",
heightToNormal: "sharp", uvPadding: "3d"}` changes those four settings in one
undo step. `textureSet.inspect {ts: 0}` reports the size, settings and channels.
Across-seam padding is the default for new sets. Older sets without a padding
mode keep island-edge padding.
`textureSet.channels {ts: 0, add: ["user0"]}` adds a stored, exportable channel.
Use `remove` to remove channels and `allSets: true` to apply the same edits to
every set. Inspect reports `shaded: false` for channels the viewport shader
does not use. `textureSet.channel.format {ts: 0, channel: "user0", format: "L8"}`
sets the composite format without lowering the precision of the painted layer
data. Float format selections currently store 16-bit precision.
## Control channel (desktop app)
```sh