Auto: Integrate main and preserve tool and compositor fixes

Integrate shared translation catalogs, updated Craft libraries, generator adjustments and input overrides, mesh replacement, shared format readers, and layer-panel controls.

Preserve tool-availability guards, quick-mask path protection, brush-cursor behavior, compositor cache reuse and buffer cleanup, and reduced dirty-tile selection work. Include import and allocation bounds, atomic-save protection, material-link compatibility, regression tests, documentation, and upstream build and packaging updates.
This commit is contained in:
chasse20 committed 2026-11-15 20:55:47 +00:00
commit a43dadbaa5
54 files changed
+3471 -1701

No files matched your search

Generated
+70 -9
View File
@@ -758,7 +758,7 @@ dependencies = [
[[package]]
name = "craft-dialogs"
version = "0.1.0"
source = "git+https://github.com/storytold/craft-libs?rev=6e03f65bf45181db77ba6229716e6624db9eb25b#6e03f65bf45181db77ba6229716e6624db9eb25b"
source = "git+https://github.com/storytold/craft-libs?rev=390fe98b0dd3fb84db7c3af7cbd958db4e8cc585#390fe98b0dd3fb84db7c3af7cbd958db4e8cc585"
dependencies = [
"block2 0.6.2",
"objc2 0.6.5",
@@ -771,12 +771,12 @@ dependencies = [
[[package]]
name = "craft-fonts-build"
version = "0.1.0"
source = "git+https://github.com/storytold/craft-libs?rev=6e03f65bf45181db77ba6229716e6624db9eb25b#6e03f65bf45181db77ba6229716e6624db9eb25b"
source = "git+https://github.com/storytold/craft-libs?rev=390fe98b0dd3fb84db7c3af7cbd958db4e8cc585#390fe98b0dd3fb84db7c3af7cbd958db4e8cc585"
[[package]]
name = "craft-i18n"
version = "0.1.0"
source = "git+https://github.com/storytold/craft-libs?rev=6e03f65bf45181db77ba6229716e6624db9eb25b#6e03f65bf45181db77ba6229716e6624db9eb25b"
source = "git+https://github.com/storytold/craft-libs?rev=390fe98b0dd3fb84db7c3af7cbd958db4e8cc585#390fe98b0dd3fb84db7c3af7cbd958db4e8cc585"
dependencies = [
"fixed_decimal",
"icu_decimal",
@@ -799,17 +799,37 @@ dependencies = [
[[package]]
name = "craft-keymap"
version = "0.1.0"
source = "git+https://github.com/storytold/craft-libs?rev=6e03f65bf45181db77ba6229716e6624db9eb25b#6e03f65bf45181db77ba6229716e6624db9eb25b"
source = "git+https://github.com/storytold/craft-libs?rev=390fe98b0dd3fb84db7c3af7cbd958db4e8cc585#390fe98b0dd3fb84db7c3af7cbd958db4e8cc585"
dependencies = [
"egui",
"serde",
"serde_json",
]
[[package]]
name = "craft-materialx"
version = "0.1.0"
source = "git+https://github.com/storytold/craft-libs?rev=390fe98b0dd3fb84db7c3af7cbd958db4e8cc585#390fe98b0dd3fb84db7c3af7cbd958db4e8cc585"
dependencies = [
"craft-xml",
"thiserror 2.0.21",
]
[[package]]
name = "craft-mcmat"
version = "0.1.0"
source = "git+https://github.com/storytold/craft-libs?rev=c376774f15ae7cd3b06a7ac664f01a8645af4b83#c376774f15ae7cd3b06a7ac664f01a8645af4b83"
dependencies = [
"craft-zip",
"serde",
"serde_json",
"thiserror 2.0.21",
]
[[package]]
name = "craft-menu"
version = "0.1.0"
source = "git+https://github.com/storytold/craft-libs?rev=6e03f65bf45181db77ba6229716e6624db9eb25b#6e03f65bf45181db77ba6229716e6624db9eb25b"
source = "git+https://github.com/storytold/craft-libs?rev=390fe98b0dd3fb84db7c3af7cbd958db4e8cc585#390fe98b0dd3fb84db7c3af7cbd958db4e8cc585"
dependencies = [
"craft-keymap",
"craft-quit",
@@ -819,10 +839,15 @@ dependencies = [
"objc2-app-kit 0.3.2",
]
[[package]]
name = "craft-mesh"
version = "0.1.0"
source = "git+https://github.com/storytold/craft-libs?rev=d6ed8c20f12188c1f39c89b3a8436bd0d09c3748#d6ed8c20f12188c1f39c89b3a8436bd0d09c3748"
[[package]]
name = "craft-quit"
version = "0.1.0"
source = "git+https://github.com/storytold/craft-libs?rev=6e03f65bf45181db77ba6229716e6624db9eb25b#6e03f65bf45181db77ba6229716e6624db9eb25b"
source = "git+https://github.com/storytold/craft-libs?rev=390fe98b0dd3fb84db7c3af7cbd958db4e8cc585#390fe98b0dd3fb84db7c3af7cbd958db4e8cc585"
dependencies = [
"dispatch2",
"egui",
@@ -830,10 +855,21 @@ dependencies = [
"objc2-app-kit 0.3.2",
]
[[package]]
name = "craft-tcraft"
version = "0.1.0"
source = "git+https://github.com/storytold/craft-libs?rev=c376774f15ae7cd3b06a7ac664f01a8645af4b83#c376774f15ae7cd3b06a7ac664f01a8645af4b83"
dependencies = [
"craft-zip",
"serde",
"serde_json",
"thiserror 2.0.21",
]
[[package]]
name = "craft-ui"
version = "0.1.0"
source = "git+https://github.com/storytold/craft-libs?rev=6e03f65bf45181db77ba6229716e6624db9eb25b#6e03f65bf45181db77ba6229716e6624db9eb25b"
source = "git+https://github.com/storytold/craft-libs?rev=390fe98b0dd3fb84db7c3af7cbd958db4e8cc585#390fe98b0dd3fb84db7c3af7cbd958db4e8cc585"
dependencies = [
"craft-fonts-build",
"craft-i18n",
@@ -854,7 +890,7 @@ dependencies = [
[[package]]
name = "craft-update"
version = "0.1.0"
source = "git+https://github.com/storytold/craft-libs?rev=6e03f65bf45181db77ba6229716e6624db9eb25b#6e03f65bf45181db77ba6229716e6624db9eb25b"
source = "git+https://github.com/storytold/craft-libs?rev=390fe98b0dd3fb84db7c3af7cbd958db4e8cc585#390fe98b0dd3fb84db7c3af7cbd958db4e8cc585"
dependencies = [
"chrono",
"dunce",
@@ -881,7 +917,7 @@ dependencies = [
[[package]]
name = "craft-window"
version = "0.1.0"
source = "git+https://github.com/storytold/craft-libs?rev=6e03f65bf45181db77ba6229716e6624db9eb25b#6e03f65bf45181db77ba6229716e6624db9eb25b"
source = "git+https://github.com/storytold/craft-libs?rev=390fe98b0dd3fb84db7c3af7cbd958db4e8cc585#390fe98b0dd3fb84db7c3af7cbd958db4e8cc585"
dependencies = [
"egui",
"objc2 0.6.5",
@@ -889,6 +925,26 @@ dependencies = [
"wayland-client",
]
[[package]]
name = "craft-xml"
version = "0.1.0"
source = "git+https://github.com/storytold/craft-libs?rev=390fe98b0dd3fb84db7c3af7cbd958db4e8cc585#390fe98b0dd3fb84db7c3af7cbd958db4e8cc585"
dependencies = [
"quick-xml 0.41.0",
"serde",
"thiserror 2.0.21",
]
[[package]]
name = "craft-zip"
version = "0.1.0"
source = "git+https://github.com/storytold/craft-libs?rev=c376774f15ae7cd3b06a7ac664f01a8645af4b83#c376774f15ae7cd3b06a7ac664f01a8645af4b83"
dependencies = [
"flate2",
"thiserror 2.0.21",
"zip",
]
[[package]]
name = "crc32fast"
version = "1.5.2"
@@ -4369,6 +4425,11 @@ name = "texturecraft-formats"
version = "0.6.1"
dependencies = [
"base64 0.22.1",
"craft-materialx",
"craft-mcmat",
"craft-mesh",
"craft-tcraft",
"craft-zip",
"exr",
"flate2",
"gltf",
+13 -8
View File
@@ -66,20 +66,25 @@ rustix = { version = "1", default-features = false, features = ["std", "fs", "pr
# Shared Craft egui components (widget palette, icon buttons, panel docking): storytold/craft-libs,
# MIT OR Apache-2.0, pinned to one rev.
# Shared catalog lookup, pinned with the other Craft libraries.
craft-i18n = { git = "https://github.com/storytold/craft-libs", rev = "6e03f65bf45181db77ba6229716e6624db9eb25b" }
craft-ui = { git = "https://github.com/storytold/craft-libs", rev = "6e03f65bf45181db77ba6229716e6624db9eb25b", features = ["serde"] }
craft-i18n = { git = "https://github.com/storytold/craft-libs", rev = "390fe98b0dd3fb84db7c3af7cbd958db4e8cc585" }
craft-ui = { git = "https://github.com/storytold/craft-libs", rev = "390fe98b0dd3fb84db7c3af7cbd958db4e8cc585", features = ["serde"] }
craft-materialx = { git = "https://github.com/storytold/craft-libs", rev = "390fe98b0dd3fb84db7c3af7cbd958db4e8cc585" }
craft-tcraft = { git = "https://github.com/storytold/craft-libs", rev = "c376774f15ae7cd3b06a7ac664f01a8645af4b83" }
craft-zip = { git = "https://github.com/storytold/craft-libs", rev = "c376774f15ae7cd3b06a7ac664f01a8645af4b83" }
craft-mesh = { git = "https://github.com/storytold/craft-libs", rev = "d6ed8c20f12188c1f39c89b3a8436bd0d09c3748", default-features = false, features = ["stl"] }
craft-mcmat = { git = "https://github.com/storytold/craft-libs", rev = "c376774f15ae7cd3b06a7ac664f01a8645af4b83" }
# Who draws the window frame, and the app-drawn strip as the title bar (crates/ui-egui/src/titlebar.rs).
craft-window = { git = "https://github.com/storytold/craft-libs", rev = "6e03f65bf45181db77ba6229716e6624db9eb25b", features = ["egui"] }
craft-window = { git = "https://github.com/storytold/craft-libs", rev = "390fe98b0dd3fb84db7c3af7cbd958db4e8cc585", features = ["egui"] }
# Release checks, the update prompt and the update helper (crates/ui-egui/src/updates_ui.rs).
craft-update = { git = "https://github.com/storytold/craft-libs", rev = "6e03f65bf45181db77ba6229716e6624db9eb25b", features = ["egui"] }
craft-update = { git = "https://github.com/storytold/craft-libs", rev = "390fe98b0dd3fb84db7c3af7cbd958db4e8cc585", features = ["egui"] }
# File dialogs that never block the frame (crates/ui-egui/src/file_dialogs.rs).
craft-dialogs = { git = "https://github.com/storytold/craft-libs", rev = "6e03f65bf45181db77ba6229716e6624db9eb25b" }
craft-dialogs = { git = "https://github.com/storytold/craft-libs", rev = "390fe98b0dd3fb84db7c3af7cbd958db4e8cc585" }
# Shortcut chords, lookup and dispatch (crates/ui-egui/src/keymap.rs).
craft-keymap = { git = "https://github.com/storytold/craft-libs", rev = "6e03f65bf45181db77ba6229716e6624db9eb25b", features = ["egui"] }
craft-keymap = { git = "https://github.com/storytold/craft-libs", rev = "390fe98b0dd3fb84db7c3af7cbd958db4e8cc585", features = ["egui"] }
# Quitting the macOS way instead of closing the window (crates/ui-egui/src/windows.rs).
craft-quit = { git = "https://github.com/storytold/craft-libs", rev = "6e03f65bf45181db77ba6229716e6624db9eb25b", features = ["egui"] }
craft-quit = { git = "https://github.com/storytold/craft-libs", rev = "390fe98b0dd3fb84db7c3af7cbd958db4e8cc585", features = ["egui"] }
# The macOS app menu whose Quit asks about unsaved changes (apps/texturecraft/src/main.rs).
craft-menu = { git = "https://github.com/storytold/craft-libs", rev = "6e03f65bf45181db77ba6229716e6624db9eb25b" }
craft-menu = { git = "https://github.com/storytold/craft-libs", rev = "390fe98b0dd3fb84db7c3af7cbd958db4e8cc585" }
# egui 0.37 and winit: the suite's forks (storytold/egui, storytold/winit), as craft-libs pins them.
[patch.crates-io]
+2 -1
View File
@@ -157,6 +157,7 @@ impl StackKey {
match &effect.kind {
EffectKind::Fill { source, .. } => record_image_reference(source),
EffectKind::Material(fill) => fill.sources.values().for_each(&mut record_image_reference),
EffectKind::Generator(generator) => generator.inputs.values().for_each(&mut record_image_reference),
_ => {}
}
}
@@ -279,7 +280,7 @@ impl BelowCache {
self.clock += 1;
*stamp = self.clock;
self.order.push_back((t, self.clock));
// Drop superseded uses once they outnumber the tiles.
// Drop superseded uses once they outnumber the tiles
if self.order.len() > 2 * self.tiles.len() + 64 {
let tiles = &self.tiles;
self.order.retain(|(t, s)| tiles.get(t).is_some_and(|(stamp, _)| stamp == s));
+2 -3
View File
@@ -125,8 +125,7 @@ fn store(curvature: &Arc<Vec<f32>>, key: CacheKey, scales: &BlockScales, sizes:
sizes
};
// Keep distinct layouts: thumbnails and the viewport alternate on the same bake.
// Replacing only this variant prevents them from repeatedly rebuilding each other.
// Keep layout variants so thumbnails and the viewport reuse their own levels
cache.retain(|entry| entry.0.strong_count() > 0 && !is_entry_for(entry, curvature, key, scales));
let sizes = Arc::new(sizes);
cache.push((Arc::downgrade(curvature), key, scales.clone(), sizes.clone()));
@@ -410,7 +409,7 @@ mod tests {
}
}
// Cache lifecycle tests must not evict each other's entries in parallel.
// Cache lifecycle tests must not evict each other's entries in parallel
static CACHE_TESTS: Mutex<()> = Mutex::new(());
#[test]
+397 -124
View File
@@ -279,12 +279,24 @@ fn neighbourhood(effects: &[Effect], res: u32) -> Option<(usize, f32, Op)> {
neighbourhood_filters(effects, res).last()
}
/// Below this a coverage weight counts as no coverage at all.
const MIN_COVERAGE_WEIGHT: f32 = 1e-6;
/// Filter sizes are texels at this many texels per side (2K), scaled to the resolution they run at.
const FILTER_SIZE_RESOLUTION: f32 = 2048.0;
/// The smallest radius a filter runs at, in texels.
const MIN_FILTER_RADIUS: f32 = 0.5;
/// Sharpen's blur radius at [`FILTER_SIZE_RESOLUTION`], and the smallest it runs at, in texels.
const SHARPEN_RADIUS: f32 = 1.5;
const MIN_SHARPEN_RADIUS: f32 = 0.75;
/// The neighbourhood filters of an effect stack, bottom → top: index among the visible effects, radius in texels (`res` texels per UV tile across) and what it does.
fn neighbourhood_filters(effects: &[Effect], res: u32) -> impl Iterator<Item = (usize, f32, Op)> + '_ {
let texels = move |size: f32| (size * res as f32 / 2048.0).max(0.5);
let texels = move |size: f32| (size * res as f32 / FILTER_SIZE_RESOLUTION).max(MIN_FILTER_RADIUS);
effects.iter().filter(|effect| effect.visible).enumerate().filter_map(move |(index, effect)| match &effect.kind {
EffectKind::Filter(Filter::Blur { radius }) if *radius > 0.0 => Some((index, texels(*radius), Op::Blur(None))),
EffectKind::Filter(Filter::Sharpen { amount }) => Some((index, (1.5 * res as f32 / 2048.0).max(0.75), Op::Blur(Some(*amount)))),
EffectKind::Filter(Filter::Sharpen { amount }) => {
Some((index, (SHARPEN_RADIUS * res as f32 / FILTER_SIZE_RESOLUTION).max(MIN_SHARPEN_RADIUS), Op::Blur(Some(*amount))))
}
EffectKind::Filter(Filter::DirectionalBlur { radius, angle }) if *radius > 0.0 => Some((index, texels(*radius), Op::Line(direction(*angle)))),
EffectKind::Filter(Filter::Warp { intensity, scale, seed }) if *intensity > 0.0 => {
Some((index, texels(*intensity), Op::Warp { scale: *scale, seed: *seed, dir: None }))
@@ -298,6 +310,10 @@ fn neighbourhood_filters(effects: &[Effect], res: u32) -> impl Iterator<Item = (
EffectKind::Filter(Filter::Bevel { width }) => Some((index, texels(*width * 0.5), Op::Bevel)),
EffectKind::Filter(Filter::Glow { radius, amount }) => Some((index, texels(*radius), Op::Glow(*amount))),
EffectKind::Filter(Filter::Mosaic { size }) => Some((index, texels(*size), Op::Mosaic)),
// Independent of `res`, so every caller agrees on which effects are stages; the reach covers the cells, then the blur around them
EffectKind::Generator(generator) if generator.global.blur > 0.0 || generator.resolution.can_reduce() => {
Some((index, texels(generator.global.blur_radius()) + generator.resolution.largest_cell(res) as f32, Op::Blur(None)))
}
EffectKind::Filter(Filter::SlopeBlur { radius, scale, seed }) if *radius > 0.0 => {
Some((index, texels(*radius), Op::Slope { scale: *scale, seed: *seed }))
}
@@ -618,63 +634,74 @@ fn is_box_blur(op: Op) -> bool {
/// The stack up to and including neighbourhood filter `filter` over texel `region`, continued from `start` (the filter below's field) when given.
#[allow(clippy::too_many_arguments)]
fn filter_region(
inp: &Inputs,
inputs: &Inputs,
channels: &[Channel],
below: &Fields,
id: LayerId,
job: Job,
effects: &[Effect],
(index, radius, op): (usize, f32, Op),
(rx0, ry0, w, h): (u32, u32, u32, u32),
(region_x, region_y, width, height): (u32, u32, u32, u32),
start: Option<(usize, &Field)>,
) -> Option<Field> {
// Tiny coverage sums make normalization unstable
const MIN_FILTER_WEIGHT: f32 = 1e-6;
let filter_effect = effects.iter().filter(|effect| effect.visible).nth(index);
let opacity = filter_effect.map(|effect| effect.opacity.clamp(0.0, 1.0)).unwrap_or(1.0);
let (radius_texels, _) = filter_extent(radius, op, inputs.gbuf.width.max(inputs.gbuf.height));
let opacity = effects.iter().filter(|effect| effect.visible).nth(index).map(|effect| effect.opacity.clamp(0.0, 1.0)).unwrap_or(1.0);
let (radius_texels, _) = filter_extent(radius, op, inp.gbuf.width.max(inp.gbuf.height));
let component_count = match job {
// Generator stages keep their ramp beside the mask stack below
let generator = match (job, filter_effect.map(|effect| (&effect.kind, effect.blend))) {
(Job::Mask(_), Some((EffectKind::Generator(generator), blend))) => Some((generator, blend)),
_ => None,
};
let components = match job {
Job::Mask(_) if generator.is_some() => 2,
Job::Mask(_) => 1,
Job::Content(_) => 4,
};
// Evaluate the stack up to the filter, tile by tile (content premultiplied by coverage)
let (rx1, ry1) = (rx0 + w, ry0 + h);
let region_tiles: Vec<(u32, u32)> = (ry0 / TILE..ry1.div_ceil(TILE)).flat_map(|y| (rx0 / TILE..rx1.div_ceil(TILE)).map(move |x| (x, y))).collect();
let (region_right, region_bottom) = (region_x + width, region_y + height);
let region_tiles: Vec<(u32, u32)> =
(region_y / TILE..region_bottom.div_ceil(TILE)).flat_map(|y| (region_x / TILE..region_right.div_ceil(TILE)).map(move |x| (x, y))).collect();
let parts: Vec<Vec<(u32, u32, [f32; 4])>> = region_tiles
.par_iter()
.map(|&(tx, ty)| {
let anchor_nodes = anchor_plan(inp, id, channels, tx, ty, Some(below));
let preview_tile = inp.preview.and_then(|preview| preview.alpha.tile(tx, ty));
.map(|&(tile_x, tile_y)| {
let anchor_nodes = anchor_plan(inputs, id, channels, tile_x, tile_y, Some(below));
let preview_tile = inputs.preview.and_then(|preview| preview.alpha.tile(tile_x, tile_y));
let mut mask = None;
let mut nodes = Vec::new();
let mut generator_sizes = None;
match job {
Job::Mask(layer_mask) => {
let Some(mut mask_stack) = mask_plan(inp, id, layer_mask, tx, ty, None) else { return Vec::new() };
let Some(mut mask_stack) = mask_plan(inputs, id, layer_mask, tile_x, tile_y, None) else { return Vec::new() };
generator_sizes = mask_stack.effects.get(index).and_then(|effect| effect.curvature_sizes.clone());
mask_stack.effects.truncate(index);
mask_stack.start = start;
mask = Some(mask_stack);
}
Job::Content(channel) => {
nodes = plan(inp, &[id], &[channel], tx, ty, 0, Some(below));
nodes = plan(inputs, &[id], &[channel], tile_x, tile_y, 0, Some(below));
if let Some(channel_plan) = nodes.first_mut().and_then(|node| node.chans.first_mut()) {
channel_plan.effects.truncate(index);
channel_plan.start = start;
}
}
}
tile_texels(inp.gbuf, tx, ty)
tile_texels(inputs.gbuf, tile_x, tile_y)
.map(|(x, y, offset)| {
let mut texel = Texel::new(inp, x, y, offset, stroke_at(preview_tile, offset));
let mut texel = Texel::new(inputs, x, y, offset, stroke_at(preview_tile, offset));
if !anchor_nodes.is_empty() {
texel.anchors_below(&anchor_nodes, id);
}
let value = match (&mask, nodes.first()) {
(Some(mask_stack), _) => [texel.mask(mask_stack), 0.0, 0.0, 0.0],
(Some(mask_stack), _) => {
let ramp = generator.map_or(0.0, |(generator, _)| texel.generator_ramp(generator, generator_sizes.as_deref()));
[texel.mask(mask_stack), ramp, 0.0, 0.0]
}
(None, Some(node)) => match node.chans.first().and_then(|channel_plan| texel.content(&node.content, channel_plan)) {
Some((color, alpha)) => [color[0] * alpha, color[1] * alpha, color[2] * alpha, alpha],
Some((color, coverage)) => [color[0] * coverage, color[1] * coverage, color[2] * coverage, coverage],
None => [0.0; 4],
},
(None, None) => [0.0; 4],
@@ -686,103 +713,214 @@ fn filter_region(
.collect();
// Scatter into the region, a row of tiles at a time (the region is tile aligned)
let texel_count = (w * h) as usize;
let mut original_values = vec![0.0f32; texel_count * component_count];
let mut coverage = vec![0.0f32; texel_count];
let row_tiles = (rx1.div_ceil(TILE) - rx0 / TILE).max(1) as usize;
let band = (TILE * w) as usize;
original_values.par_chunks_mut(band * component_count).zip(coverage.par_chunks_mut(band)).zip(parts.par_chunks(row_tiles)).for_each(
|((original_values, coverage), row)| {
for &(x, y, value) in row.iter().flatten() {
let texel = (((y - ry0) % TILE) * w + (x - rx0)) as usize;
if let (Some(covered), Some(pixel)) = (coverage.get_mut(texel), original_values.get_mut(texel * component_count..(texel + 1) * component_count))
{
*covered = 1.0;
pixel.copy_from_slice(&value[..component_count]);
}
let texel_count = (width * height) as usize;
let mut stack_values = vec![0.0f32; texel_count * components];
let mut cover = vec![0.0f32; texel_count];
let row_tiles = (region_right.div_ceil(TILE) - region_x / TILE).max(1) as usize;
let band = (TILE * width) as usize;
stack_values.par_chunks_mut(band * components).zip(cover.par_chunks_mut(band)).zip(parts.par_chunks(row_tiles)).for_each(|((stack_values, cover), row)| {
for &(x, y, value) in row.iter().flatten() {
let texel = (((y - region_y) % TILE) * width + (x - region_x)) as usize;
if let (Some(covered), Some(pixel)) = (cover.get_mut(texel), stack_values.get_mut(texel * components..(texel + 1) * components)) {
*covered = 1.0;
pixel.copy_from_slice(&value[..components]);
}
},
);
}
});
// Release scattered texels before allocating filter buffers
// Release tile scatter data before allocating filter buffers
drop(parts);
// High pass centers on the channel's midpoint value (0 for signed channels like height)
let midpoint = match job {
// High pass centers on the channel's middle value (0 for signed channels like height)
let middle = match job {
Job::Content(channel) if channel.kind() == ChannelKind::Signed => 0.0,
_ => 0.5,
};
// A smaller UV tile has fewer texels per UV unit, so its filters reach fewer texels
let filtered = |scale: f32| -> Vec<f32> {
let sampling_resolution = ((inp.tile_res() as f32 * scale).round() as u32).max(1);
let scaled_radius = neighbourhood_filters(effects, sampling_resolution)
let tile_resolution = ((inputs.tile_res() as f32 * scale).round() as u32).max(1);
if let Some((generator, blend)) = generator {
let texture_set = inputs.project.texture_set(inputs.ts).map_or(inputs.tile_res(), |set| set.resolution);
return generator_region(generator, blend, opacity, &stack_values, &cover, (region_x, region_y, width, height), (tile_resolution, texture_set));
}
let scaled_radius = neighbourhood_filters(effects, tile_resolution)
.find(|filter| filter.0 == index)
.map_or(radius_texels, |filter| filter.1.round().clamp(1.0, radius_texels as f32) as u32);
if !is_box_blur(op) {
return gather(op, &original_values, &coverage, component_count, (rx0, ry0, w, h), scaled_radius as f32, sampling_resolution, opacity);
return gather(op, &stack_values, &cover, components, (region_x, region_y, width, height), scaled_radius as f32, tile_resolution, opacity);
}
// Weighted so uncovered texels don't bleed in
let (width, height, blur_radius) = (w as usize, h as usize, scaled_radius as usize);
let mut weights = coverage.clone();
blur(&mut weights, width, height, blur_radius);
let mut data = original_values.clone();
for component in 0..component_count {
let mut sums: Vec<f32> = original_values
.par_chunks(component_count)
.with_min_len(MIN_PARALLEL_TEXELS)
.map(|pixel| pixel.get(component).copied().unwrap_or(0.0))
.collect();
blur(&mut sums, width, height, blur_radius);
data.par_chunks_mut(component_count).with_min_len(MIN_PARALLEL_TEXELS).zip(sums.par_iter()).zip(weights.par_iter()).for_each(
|((pixel, sum), weight)| {
// Content is premultiplied, so the midpoint value is too (coverage itself is kept)
let alpha = if component_count == 4 { pixel.get(3).copied().unwrap_or(0.0) } else { 1.0 };
if *weight > MIN_FILTER_WEIGHT
&& let Some(slot) = pixel.get_mut(component)
{
let (original, blurred) = (*slot, sum / weight);
let result = match op {
Op::Blur(Some(amount)) => original + amount * (original - blurred),
Op::HighPass if component < 3 => original - blurred + midpoint * alpha,
// Away from 0 by at most the value itself: 0 at the edge, full inside
Op::Bevel if component < 3 => original.signum() * original.abs().min((2.0 * blurred * original.signum() - original.abs()).max(0.0)),
Op::Glow(amount) if component < 3 => original + amount * blurred,
Op::HighPass | Op::Bevel | Op::Glow(_) => original,
_ => blurred,
};
*slot = original + (result - original) * opacity;
}
},
);
let (columns, rows, blur_radius) = (width as usize, height as usize, scaled_radius as usize);
let mut weights = cover.clone();
blur(&mut weights, columns, rows, blur_radius);
let mut filtered_values = stack_values.clone();
for component in 0..components {
let mut sums: Vec<f32> = stack_values.par_chunks(components).map(|pixel| pixel.get(component).copied().unwrap_or(0.0)).collect();
blur(&mut sums, columns, rows, blur_radius);
filtered_values.par_chunks_mut(components).zip(sums.par_iter()).zip(weights.par_iter()).for_each(|((pixel, sum), weight)| {
// Content is premultiplied, so the middle value is too (coverage itself is kept)
let coverage = if components == 4 { pixel.get(3).copied().unwrap_or(0.0) } else { 1.0 };
if *weight > MIN_COVERAGE_WEIGHT
&& let Some(slot) = pixel.get_mut(component)
{
let (original, blurred) = (*slot, sum / weight);
let result = match op {
Op::Blur(Some(amount)) => original + amount * (original - blurred),
Op::HighPass if component < 3 => original - blurred + middle * coverage,
// Away from 0 by at most the value itself: 0 at the edge, full inside
Op::Bevel if component < 3 => original.signum() * original.abs().min((2.0 * blurred * original.signum() - original.abs()).max(0.0)),
Op::Glow(amount) if component < 3 => original + amount * blurred,
Op::HighPass | Op::Bevel | Op::Glow(_) => original,
_ => blurred,
};
*slot = original + (result - original) * opacity;
}
});
}
data
filtered_values
};
// Each block keeps the result at its tile's scale (blocks are TILE aligned)
let scales = inp.project.texture_set(inp.ts).map(TextureSet::block_scales).unwrap_or_default();
let mut levels: Vec<f32> =
(ry0..ry1).step_by(TILE as usize).flat_map(|y| (rx0..rx1).step_by(TILE as usize).map(move |x| (x, y))).map(|(x, y)| scales.at(x, y)).collect();
let scales = inputs.project.texture_set(inputs.ts).map(TextureSet::block_scales).unwrap_or_default();
let mut levels: Vec<f32> = (region_y..region_bottom)
.step_by(TILE as usize)
.flat_map(|y| (region_x..region_right).step_by(TILE as usize).map(move |x| (x, y)))
.map(|(x, y)| scales.at(x, y))
.collect();
levels.sort_by(f32::total_cmp);
levels.dedup();
let (first, rest) = levels.split_first().map_or((1.0, &[][..]), |(first, rest)| (*first, rest));
let mut data = filtered(first);
// A generator stage's field is the mask alone
let field_components = if generator.is_some() { 1 } else { components };
let mut result = filtered(first);
for &scale in rest {
let other = filtered(scale);
let row = w as usize * component_count;
data.par_chunks_mut(row).zip(other.par_chunks(row)).enumerate().for_each(|(y, (dst, src))| {
for (x, (target, source)) in dst.chunks_mut(component_count).zip(src.chunks(component_count)).enumerate() {
if scales.at(rx0 + x as u32, ry0 + y as u32) == scale {
let rescaled = filtered(scale);
let row = width as usize * field_components;
result.par_chunks_mut(row).zip(rescaled.par_chunks(row)).enumerate().for_each(|(y, (target_row, source_row))| {
for (x, (target, source)) in target_row.chunks_mut(field_components).zip(source_row.chunks(field_components)).enumerate() {
if scales.at(region_x + x as u32, region_y + y as u32) == scale {
target.copy_from_slice(source);
}
}
});
}
unpremultiply(&mut data, component_count);
Some(Field { x0: rx0, y0: ry0, w, h, comps: component_count, data })
unpremultiply(&mut result, field_components);
Some(Field { x0: region_x, y0: region_y, w: width, h: height, comps: field_components, data: result })
}
/// The mask over a region after a generator at its own resolution and blur: `stack` is (stack below, generator ramp) per texel, sizes in texels per side.
fn generator_region(
generator: &Generator,
blend: BlendMode,
opacity: f32,
stack: &[f32],
cover: &[f32],
(region_x, region_y, width, height): (u32, u32, u32, u32),
(uv_tile, texture_set): (u32, u32),
) -> Vec<f32> {
let (columns, rows) = (width as usize, height as usize);
let mut ramps: Vec<f32> = stack.par_chunks(2).map(|texel| texel.get(1).copied().unwrap_or(0.0)).collect();
// Coarser than the UV tile: averaged over cells, then the blur around them
let cell = generator.resolution.cell(uv_tile, texture_set) as usize;
if cell > 1 {
ramps = resampled_by_cells(&ramps, cover, (region_x as usize, region_y as usize, columns, rows), cell);
}
let blur_radius = generator.global.blur_radius_at(uv_tile).round() as usize;
if blur_radius > 0 {
let mut weights = cover.to_vec();
blur(&mut weights, columns, rows, blur_radius);
let mut sums: Vec<f32> = ramps.iter().zip(cover).map(|(ramp, covered)| ramp * covered).collect();
blur(&mut sums, columns, rows, blur_radius);
ramps.par_iter_mut().zip(sums.par_iter().zip(weights.par_iter())).for_each(|(ramp, (sum, weight))| {
if *weight > MIN_COVERAGE_WEIGHT {
*ramp = sum / weight;
}
});
}
// Finished and blended over the stack below, like the generator effect itself
stack
.par_chunks(2)
.zip(ramps.par_iter())
.map(|(texel, ramp)| {
let below = texel.first().copied().unwrap_or(0.0);
let generated = finish_generator(generator, *ramp);
below + (blend1(blend, below, generated) - below) * opacity
})
.collect()
}
/// `values` averaged over `cell` × `cell` texel cells on the mesh (`cover`), read back bilinearly between cell centers.
fn resampled_by_cells(values: &[f32], cover: &[f32], (region_x, region_y, width, height): (usize, usize, usize, usize), cell: usize) -> Vec<f32> {
// Cells are aligned to absolute texel positions, so a texel's cell is the same in every region
let (first_column, first_row) = (region_x / cell, region_y / cell);
let columns = (region_x + width).div_ceil(cell) - first_column;
let rows = (region_y + height).div_ceil(cell) - first_row;
// Each cell's coverage-weighted average, a row of cells at a time
let averages: Vec<Option<f32>> = (0..rows)
.into_par_iter()
.flat_map_iter(|row| {
let mut sums = vec![(0.0f32, 0.0f32); columns];
let first_y = ((first_row + row) * cell).saturating_sub(region_y);
let last_y = ((first_row + row + 1) * cell).saturating_sub(region_y).min(height);
for y in first_y..last_y {
for x in 0..width {
let texel = y * width + x;
let covered = cover.get(texel).copied().unwrap_or(0.0);
if let Some((sum, weight)) = sums.get_mut((region_x + x) / cell - first_column) {
*sum += values.get(texel).copied().unwrap_or(0.0) * covered;
*weight += covered;
}
}
}
sums.into_iter().map(|(sum, weight)| (weight > MIN_COVERAGE_WEIGHT).then(|| sum / weight))
})
.collect();
let average = |column: isize, row: isize| -> Option<f32> {
let column = column.clamp(0, columns as isize - 1) as usize;
let row = row.clamp(0, rows as isize - 1) as usize;
averages.get(row * columns + column).copied().flatten()
};
let cell_size = cell as f32;
(0..height)
.into_par_iter()
.flat_map_iter(|y| (0..width).map(move |x| (x, y)))
.map(|(x, y)| {
// Position in cells, relative to the first cell's center
let cell_x = ((region_x + x) as f32 + 0.5) / cell_size - 0.5 - first_column as f32;
let cell_y = ((region_y + y) as f32 + 0.5) / cell_size - 0.5 - first_row as f32;
let (left, top) = (cell_x.floor(), cell_y.floor());
let (offset_x, offset_y) = (cell_x - left, cell_y - top);
let (left, top) = (left as isize, top as isize);
let corners = [
(left, top, (1.0 - offset_x) * (1.0 - offset_y)),
(left + 1, top, offset_x * (1.0 - offset_y)),
(left, top + 1, (1.0 - offset_x) * offset_y),
(left + 1, top + 1, offset_x * offset_y),
];
let (sum, weight) = corners.iter().fold((0.0, 0.0), |(sum, weight), &(column, row, corner_weight)| match average(column, row) {
Some(value) => (sum + value * corner_weight, weight + corner_weight),
None => (sum, weight),
});
if weight > MIN_COVERAGE_WEIGHT { sum / weight } else { values.get(y * width + x).copied().unwrap_or(0.0) }
})
.collect()
}
/// A generator's (possibly blurred) ramp after balance, contrast, invert and offset.
fn finish_generator(generator: &Generator, ramp: f32) -> f32 {
let value = generator.global.apply(ramp);
let value = if generator.invert { 1.0 - value } else { value };
let offset = if generator.offset.is_finite() { generator.offset } else { 0.0 };
(value + offset).clamp(0.0, 1.0)
}
/// Clamp filtered masks to 0..1, and turn filtered content back into straight values.
@@ -1259,15 +1397,21 @@ impl<'a, 'b> Texel<'a, 'b> {
}
}
fn generator(&mut self, generator: &Generator, curvature_sizes: Option<&CurvatureSizes>) -> f32 {
/// The generator's ramp at this texel, before its global blur, balance, contrast and invert.
fn generator_ramp(&mut self, generator: &Generator, curvature_sizes: Option<&CurvatureSizes>) -> f32 {
let coords = self.coords();
let signal = match (generator.kind, &generator.detail) {
(GeneratorKind::Curvature | GeneratorKind::EdgeWear, Some(detail)) => self.curvature_detail(detail, curvature_sizes),
(GeneratorKind::EdgeWear, None) => (self.baked(BakedMap::Curvature).unwrap_or(0.5) - 0.5) * 2.0,
(GeneratorKind::Curvature, None) => self.baked(BakedMap::Curvature).unwrap_or(0.5),
(GeneratorKind::Dirt, _) => 1.0 - self.baked(BakedMap::AmbientOcclusion).unwrap_or(1.0),
(GeneratorKind::AmbientOcclusion, _) => self.baked(BakedMap::AmbientOcclusion).unwrap_or(1.0),
(GeneratorKind::ThinAreas, _) => 1.0 - self.baked(BakedMap::Thickness).unwrap_or(1.0),
(GeneratorKind::Curvature | GeneratorKind::EdgeWear, Some(detail)) => {
// Detail sizes are blurred copies of the mesh map, so a replaced curvature input reads at its own size only
let sizes = if generator.inputs.contains_key(&BakedMap::Curvature) { None } else { curvature_sizes };
let curvature = self.generator_input(generator, BakedMap::Curvature);
self.curvature_detail(detail, sizes, curvature)
}
(GeneratorKind::EdgeWear, None) => (self.generator_input(generator, BakedMap::Curvature).unwrap_or(0.5) - 0.5) * 2.0,
(GeneratorKind::Curvature, None) => self.generator_input(generator, BakedMap::Curvature).unwrap_or(0.5),
(GeneratorKind::Dirt, _) => 1.0 - self.generator_input(generator, BakedMap::AmbientOcclusion).unwrap_or(1.0),
(GeneratorKind::AmbientOcclusion, _) => self.generator_input(generator, BakedMap::AmbientOcclusion).unwrap_or(1.0),
(GeneratorKind::ThinAreas, _) => 1.0 - self.generator_input(generator, BakedMap::Thickness).unwrap_or(1.0),
(GeneratorKind::Position, _) => coords.pos.dot(Vec3::from(generator.direction).try_normalize().unwrap_or(Vec3::Y)) * 0.5 + 0.5,
(GeneratorKind::Direction, _) => coords.nrm.dot(Vec3::from(generator.direction).try_normalize().unwrap_or(Vec3::Y)) * 0.5 + 0.5,
};
@@ -1284,12 +1428,29 @@ impl<'a, 'b> Texel<'a, 'b> {
signal
};
// A smooth step from black to white over 2 × softness around 1 − level, then the offset
generator.shape(signal)
// A smooth step from black to white over 2 × softness around 1 − level
let threshold = 1.0 - generator.level.clamp(0.0, 1.0);
let softness = generator.softness.max(Generator::MIN_SOFTNESS);
let ramp = ((signal - (threshold - softness)) / (2.0 * softness)).clamp(0.0, 1.0);
ramp * ramp * (3.0 - 2.0 * ramp)
}
/// The curvature of `detail`'s mode at this texel: each detail size's edges and cavities, weighted and combined like a screen blend.
fn curvature_detail(&self, detail: &CurvatureDetail, curvature_sizes: Option<&CurvatureSizes>) -> f32 {
/// The generator's value at this texel: its ramp finished by balance, contrast, invert and offset (its blur and resolution need neighbours: see [`generator_region`]).
fn generator(&mut self, generator: &Generator, curvature_sizes: Option<&CurvatureSizes>) -> f32 {
let ramp = self.generator_ramp(generator, curvature_sizes);
finish_generator(generator, ramp)
}
/// Generator input `map` at this texel: what replaces the mesh map in the generator's inputs, else the mesh map (None when not baked).
fn generator_input(&mut self, generator: &Generator, map: BakedMap) -> Option<f32> {
match generator.inputs.get(&map) {
Some(source) => Some(self.source(source, &Projection::default(), ChannelKind::Scalar)[0]),
None => self.baked(map),
}
}
/// The curvature of `detail`'s mode at this texel from `curvature` (None: nothing to read), with its blurred detail sizes when given.
fn curvature_detail(&self, detail: &CurvatureDetail, curvature_sizes: Option<&CurvatureSizes>, curvature: Option<f32>) -> f32 {
let combine = |edges: f32, cavities: f32| match detail.mode {
CurvatureMode::Edges => edges,
CurvatureMode::Cavities => cavities,
@@ -1298,7 +1459,7 @@ impl<'a, 'b> Texel<'a, 'b> {
};
// Without curvature to read the texel is flat: no edges or cavities
let Some(curvature) = self.baked(BakedMap::Curvature) else { return combine(0.0, 0.0) };
let Some(curvature) = curvature else { return combine(0.0, 0.0) };
let working_size = (self.res, self.inp.gbuf.height);
let texel_uv = [(self.x as f32 + 0.5) / working_size.0.max(1) as f32, (self.y as f32 + 0.5) / working_size.1.max(1) as f32];
@@ -2392,7 +2553,7 @@ pub fn flatten_layer(inputs: &Inputs, id: LayerId, tiles: &[(u32, u32)]) -> Opti
#[cfg(test)]
mod tests {
use super::*;
use texturecraft_core::{ChannelBlend, Effect, Layer, Procedural, ProceduralKind, TextureSet};
use texturecraft_core::{ChannelBlend, Effect, Layer, OutputResolution, Procedural, ProceduralKind, ResolutionMode, TextureSet};
use texturecraft_geom::primitives;
struct Fixture {
@@ -2731,42 +2892,154 @@ mod tests {
assert!(blurred_then_warped.iter().zip(&warped).any(|(chained, single)| (chained - single).abs() > 0.1), "the blur under the warp still runs");
}
#[test]
fn larger_curvature_detail_sizes_reach_further_from_an_edge() {
/// A 256² set whose curvature map has a one-texel ridge in column `ridge_x` (flat elsewhere), and a white fill layer to mask.
fn ridge_fixture(ridge_x: usize) -> (Fixture, LayerId) {
let mut fixture = fixture();
fixture.gbuf = UvGBuffer::new(&fixture.mesh, 0, 256, 256);
fixture.project.texture_sets[0].resolution = 256;
let ridge: Vec<f32> = (0..256 * 256).map(|texel| if texel % 256 == 128 { 1.0 } else { 0.5 }).collect();
let ridge: Vec<f32> = (0..256 * 256).map(|texel| if texel % 256 == ridge_x { 1.0 } else { 0.5 }).collect();
fixture.baked = BakedMaps { resolution: 256, maps: [(BakedMap::Curvature, Arc::new(ridge))].into() };
let layer = fill_layer(&mut fixture.project, [1.0; 3], 1.0);
let row_with = |fixture: &mut Fixture, weights: [f32; 7]| -> Vec<f32> {
(fixture, layer)
}
/// `layer`'s mask made of `effects` (bottom first) on black, read along row 128 over `xs`.
fn mask_row(fixture: &mut Fixture, layer: LayerId, effects: Vec<Effect>, xs: std::ops::Range<u32>) -> Vec<f32> {
let mut mask = Mask::new(MaskBackground::Black);
mask.effects = effects;
fixture.project.layer_mut(layer).unwrap().mask = Some(mask);
let images = Default::default();
let inputs = Inputs {
project: &fixture.project,
ts: 0,
mesh: &fixture.mesh,
gbuf: &fixture.gbuf,
pixels: &fixture.pixels,
baked: &fixture.baked,
block_scales: BlockScales::default(),
preview: None,
images: &images,
bounds: fixture.mesh.bounds(),
};
mask_at(&inputs, layer, &xs.map(|x| (x, 128)).collect::<Vec<_>>()).unwrap()
}
/// A generator effect of `fixture`'s project.
fn generator_effect(fixture: &mut Fixture, generator: Generator) -> Effect {
Effect::new(fixture.project.alloc_id(), EffectKind::Generator(generator))
}
/// An edge wear generator that marks exactly the curvature ridge (the map as baked, a hard step).
fn ridge_generator() -> Generator {
Generator { level: 0.5, softness: 0.01, noise_amount: 0.0, detail: None, ..Generator::new(GeneratorKind::EdgeWear) }
}
#[test]
fn larger_curvature_detail_sizes_reach_further_from_an_edge() {
let (mut fixture, layer) = ridge_fixture(128);
let mut row_with = |weights: [f32; 7]| {
let detail = CurvatureDetail { mode: CurvatureMode::Edges, weights };
let generator = Generator { level: 0.5, softness: 0.5, noise_amount: 0.0, detail: Some(detail), ..Generator::new(GeneratorKind::Curvature) };
let effect = generator_effect(&mut fixture, generator);
mask_row(&mut fixture, layer, vec![effect], 120..137)
};
// The sampled ridge is index 8; five texels to its left is index 3
let (ridge, five_texels_away) = (8, 3);
let finest = row_with([1.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0]);
let largest = row_with([0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 1.0]);
assert!(finest[ridge] > 0.99 && finest[five_texels_away] < 0.01, "the map itself marks only the ridge: {finest:?}");
assert!(largest[ridge] > 0.99 && largest[five_texels_away] > 0.5, "the largest size reaches texels away from it: {largest:?}");
}
#[test]
fn a_replaced_curvature_input_is_read_at_its_own_size_only() {
let (mut fixture, layer) = ridge_fixture(128);
let detail = CurvatureDetail { mode: CurvatureMode::Edges, weights: [0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 1.0] };
let mut generator = Generator { level: 0.5, softness: 0.5, noise_amount: 0.0, detail: Some(detail), ..Generator::new(GeneratorKind::Curvature) };
generator.inputs.insert(BakedMap::Curvature, Source::Uniform([0.5; 3]));
let effect = generator_effect(&mut fixture, generator);
let row = mask_row(&mut fixture, layer, vec![effect], 120..137);
// The largest size alone would mark the ridge and texels around it; the flat input marks nothing
assert!(row.iter().all(|value| *value < 0.01), "the detail sizes of the mesh map are not read: {row:?}");
}
#[test]
fn generator_blur_softens_only_the_generator_not_the_stack_below() {
let (mut fixture, layer) = ridge_fixture(100);
let mut row_with = |blur: f32| {
let checker = Source::Procedural { pattern: Procedural::new(ProceduralKind::Checker), low: [0.0; 3], high: [1.0; 3] };
let below = Effect::new(fixture.project.alloc_id(), EffectKind::Fill { source: checker, projection: Projection::default() });
let mut generator = ridge_generator();
generator.global.blur = blur;
let mut lighten = generator_effect(&mut fixture, generator);
lighten.blend = BlendMode::Lighten;
mask_row(&mut fixture, layer, vec![below, lighten], 40..111)
};
// The sampled row crosses a checker edge; indices below 30 are outside the blur
let (ridge, five_texels_away, far) = (60, 55, 0..30);
let sharp = row_with(0.0);
let blurred = row_with(1.0);
assert!(sharp[ridge] > 0.99 && sharp[five_texels_away] < 0.01, "unblurred, the ridge is one texel: {sharp:?}");
assert!(blurred[ridge] < 0.99 && blurred[ridge] > blurred[five_texels_away], "the blur spreads the ridge: {blurred:?}");
assert!(blurred[five_texels_away] > 0.01, "and reaches texels away from it: {blurred:?}");
for texel in far {
assert_eq!(blurred[texel], sharp[texel], "the checker below keeps its hard edges at texel {texel}");
}
}
#[test]
fn a_lower_generator_resolution_spreads_a_ridge_over_its_cell() {
let (mut fixture, layer) = ridge_fixture(100);
let mut row_with = |factor: i8| {
let mut generator = ridge_generator();
generator.resolution.factor = factor;
let effect = generator_effect(&mut fixture, generator);
mask_row(&mut fixture, layer, vec![effect], 80..121)
};
// At one eighth resolution, each cell spans eight texels
let (ridge, beside, far) = (20, 18, 0);
let full = row_with(0);
let eighth = row_with(-3);
assert!(full[ridge] > 0.99 && full[beside] < 0.01, "at full resolution the ridge is one texel: {full:?}");
assert!(eighth[ridge] < 0.5 && eighth[beside] > 0.01, "an eighth of the resolution averages it over its cell: {eighth:?}");
assert!(eighth[far] < 0.01, "texels a few cells away stay black: {eighth:?}");
}
#[test]
fn every_caller_lists_the_same_generator_stages_whatever_resolution_it_passes() {
let custom = OutputResolution { mode: ResolutionMode::Custom, custom: 1024, factor: 0 };
let effects = [Effect::new(LayerId(1), EffectKind::Generator(Generator { resolution: custom, ..Generator::new(GeneratorKind::Dirt) }))];
// Tile and whole-set resolutions must select the same generator stage
let at_tile: Vec<usize> = neighbourhood_filters(&effects, 1024).map(|stage| stage.0).collect();
let at_set_width: Vec<usize> = neighbourhood_filters(&effects, 2048).map(|stage| stage.0).collect();
assert_eq!(at_tile, at_set_width);
assert_eq!(at_tile, [0], "a custom resolution can be coarser than some UV tile, so it is a stage");
}
#[test]
fn a_generator_input_replaced_by_a_value_is_read_instead_of_the_mesh_map() {
let mut fixture = fixture();
fixture.baked = BakedMaps { resolution: 64, maps: [(BakedMap::AmbientOcclusion, Arc::new(vec![1.0; 64 * 64]))].into() };
let layer = fill_layer(&mut fixture.project, [1.0; 3], 1.0);
let value_with = |fixture: &mut Fixture, input: Option<f32>| -> f32 {
let mut generator = Generator { level: 0.5, softness: 0.1, noise_amount: 0.0, ..Generator::new(GeneratorKind::Dirt) };
if let Some(value) = input {
generator.inputs.insert(BakedMap::AmbientOcclusion, Source::Uniform([value; 3]));
}
let mut mask = Mask::new(MaskBackground::Black);
mask.effects.push(Effect::new(fixture.project.alloc_id(), EffectKind::Generator(generator)));
fixture.project.layer_mut(layer).unwrap().mask = Some(mask);
let images = Default::default();
let inputs = Inputs {
project: &fixture.project,
ts: 0,
mesh: &fixture.mesh,
gbuf: &fixture.gbuf,
pixels: &fixture.pixels,
baked: &fixture.baked,
block_scales: BlockScales::default(),
preview: None,
images: &images,
bounds: fixture.mesh.bounds(),
};
mask_at(&inputs, layer, &(120..137).map(|x| (x, 128)).collect::<Vec<_>>()).unwrap()
run(fixture, None).value(Channel::BaseColor, 20, 20)[0]
};
// The row starts at x 120: the ridge is its ninth texel, five texels left of it the fourth
let (ridge, five_texels_away) = (8, 3);
let finest = row_with(&mut fixture, [1.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0]);
let largest = row_with(&mut fixture, [0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 1.0]);
assert!(finest[ridge] > 0.99 && finest[five_texels_away] < 0.01, "the map itself marks only the ridge: {finest:?}");
assert!(largest[ridge] > 0.99 && largest[five_texels_away] > 0.5, "the largest size reaches texels away from it: {largest:?}");
// Dark occlusion reveals dirt while the baked white map stays clear
let (baked, black) = (value_with(&mut fixture, None), value_with(&mut fixture, Some(0.0)));
assert!(black > 0.99 && baked < black - 0.2, "baked {baked}, black input {black}");
}
#[test]
+35 -2
View File
@@ -6,8 +6,8 @@ use std::collections::BTreeMap;
use texturecraft_compose::{BelowCache, Composite, Inputs, PaintTarget, PixelStore, StrokePreview, all_tiles, composite_tiles, composite_tiles_cached};
use texturecraft_core::{
BlendMode, Channel, Effect, EffectKind, Fill, Filter, Generator, GeneratorKind, HeightMask, Layer, LayerId, LayerKind, Mask, MaskBackground, Procedural,
ProceduralKind, Project, Projection, Source, TextureSet,
BakedMap, BlendMode, Channel, Effect, EffectKind, Fill, Filter, Generator, GeneratorKind, HeightMask, Layer, LayerId, LayerKind, Mask, MaskBackground,
Procedural, ProceduralKind, Project, Projection, Source, TextureSet,
};
use texturecraft_geom::{Mesh, UvGBuffer, primitives};
use texturecraft_texel::{TILE, TileImage, to_u16};
@@ -799,3 +799,36 @@ fn cached_stack_tracks_referenced_images_only() {
assert!(output == expected, "{stage}");
}
}
#[test]
fn generator_input_image_changes_invalidate_stack_key() {
use std::sync::Arc;
use texturecraft_compose::{ImageRes, ImageStore, StackKey};
let mut fixture = fixture();
heavy_stack(&mut fixture);
let generated_layer = fixture.project.texture_sets[0].stack[1];
let mask = fixture.project.layer_mut(generated_layer).unwrap().mask.as_mut().unwrap();
let EffectKind::Generator(generator) = &mut mask.effects[0].kind else { panic!("expected generator") };
*generator = Generator::new(GeneratorKind::Dirt);
generator.inputs.insert(BakedMap::AmbientOcclusion, Source::image("used"));
let image = |value| Arc::new(ImageRes { width: RES, height: RES, rgba: vec![[value; 4]; (RES * RES) as usize], srgb: false });
let mut images = ImageStore::default();
images.insert("used".into(), image(0.1));
let baked = Default::default();
let roots = &fixture.project.texture_sets[0].stack;
let key = |images: &ImageStore| StackKey::new(&fixture.project, &fixture.pixels, &baked, images, 0, roots).unwrap();
let original = key(&images);
images.insert("unrelated".into(), image(0.5));
assert_eq!(key(&images), original, "an unrelated image leaves the key unchanged");
let old_image = Arc::downgrade(&images["used"]);
images.insert("used".into(), image(0.9));
assert!(old_image.upgrade().is_none(), "the cache must not retain the old image pixels");
assert!(key(&images) != original, "replacing a generator input must invalidate the cache");
images.remove("used");
assert!(key(&images) != original, "removing a generator input must invalidate the cache");
}
+108 -4
View File
@@ -4,13 +4,19 @@ use std::collections::BTreeMap;
use serde::{Deserialize, Serialize};
use crate::{BlendMode, Channel, ChannelKind, lum};
use crate::{BakedMap, BlendMode, Channel, ChannelKind, lum};
mod curvature_detail;
mod curvature_mode;
mod generator_global;
mod output_resolution;
mod resolution_mode;
pub use curvature_detail::CurvatureDetail;
pub use curvature_mode::CurvatureMode;
pub use generator_global::GeneratorGlobal;
pub use output_resolution::OutputResolution;
pub use resolution_mode::ResolutionMode;
/// Id of a layer or effect (one id space per project).
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash, PartialOrd, Ord, Serialize, Deserialize)]
@@ -526,6 +532,17 @@ impl GeneratorKind {
GeneratorKind::Direction => "Light / direction",
}
}
/// The mesh maps this kind reads, each an input that an image, a uniform value or an anchor can replace.
pub fn inputs(self) -> &'static [BakedMap] {
match self {
GeneratorKind::EdgeWear | GeneratorKind::Curvature => &[BakedMap::Curvature],
GeneratorKind::Dirt | GeneratorKind::AmbientOcclusion => &[BakedMap::AmbientOcclusion],
GeneratorKind::ThinAreas => &[BakedMap::Thickness],
GeneratorKind::Position | GeneratorKind::Direction => &[],
}
}
pub fn parse(s: &str) -> Option<GeneratorKind> {
let norm = |x: &str| x.to_ascii_lowercase().replace([' ', '_', '-', ':'], "");
GeneratorKind::ALL.into_iter().find(|k| norm(&format!("{k:?}")) == norm(s) || norm(k.label()) == norm(s))
@@ -552,9 +569,25 @@ pub struct Generator {
/// Mode and detail sizes of `Curvature` / `EdgeWear` generators (None: the curvature map as baked, as before detail sizes existed).
#[serde(default, skip_serializing_if = "Option::is_none")]
pub detail: Option<CurvatureDetail>,
/// Blur, balance and contrast of the finished value (neutral for generators saved before they existed).
#[serde(default, skip_serializing_if = "GeneratorGlobal::is_neutral")]
pub global: GeneratorGlobal,
/// The resolution the generator is computed at (the texture set's for generators saved before it existed).
#[serde(default, skip_serializing_if = "OutputResolution::is_default")]
pub resolution: OutputResolution,
/// What an input reads instead of its mesh map (an image, a uniform value or an anchor); inputs not listed read their mesh map.
#[serde(default, skip_serializing_if = "BTreeMap::is_empty")]
pub inputs: BTreeMap<BakedMap, Source>,
}
impl Generator {
/// The softest a ramp gets, so its threshold never divides by zero.
pub const MIN_SOFTNESS: f32 = 1e-3;
/// The most noise a generator mixes in, and the range of its noise scale.
pub const MAX_NOISE_AMOUNT: f32 = 2.0;
pub const MIN_NOISE_SCALE: f32 = 0.01;
pub const MAX_NOISE_SCALE: f32 = 1000.0;
pub fn new(kind: GeneratorKind) -> Generator {
let (level, softness, noise_amount) = match kind {
GeneratorKind::EdgeWear => (0.5, 0.25, 0.3),
@@ -568,7 +601,21 @@ impl Generator {
GeneratorKind::EdgeWear => Some(CurvatureDetail { mode: CurvatureMode::Edges, weights: CurvatureDetail::EDGE_WEIGHTS }),
_ => None,
};
Generator { kind, level, softness, noise_amount, noise_scale: 8.0, seed: 7, offset: 0.0, direction: [0.0, 1.0, 0.0], invert: false, detail }
Generator {
kind,
level,
softness,
noise_amount,
noise_scale: 8.0,
seed: 7,
offset: 0.0,
direction: [0.0, 1.0, 0.0],
invert: false,
detail,
global: GeneratorGlobal::default(),
resolution: OutputResolution::default(),
inputs: BTreeMap::new(),
}
}
/// The mask value for a (noise-broken) signal `s`: the smooth threshold at `level` over
@@ -1038,14 +1085,46 @@ impl EffectKind {
matches!(self, EffectKind::Paint | EffectKind::Path(_))
}
/// Anchor points read by this effect's sources.
/// Whether a source of this effect (a fill, a material or a generator input) reads an anchor point.
fn reads_anchor(&self) -> bool {
match self {
EffectKind::Fill { source, .. } => source.anchor().is_some(),
EffectKind::Material(f) => f.sources.values().any(|s| s.anchor().is_some()),
EffectKind::Material(fill) => fill.sources.values().any(|source| source.anchor().is_some()),
EffectKind::Generator(generator) => generator.inputs.values().any(|source| source.anchor().is_some()),
_ => false,
}
}
/// The anchor points this effect's sources read, with the channel each reads.
pub fn anchors_read(&self) -> Vec<(LayerId, Channel)> {
let sources: Vec<&Source> = match self {
EffectKind::Fill { source, .. } => vec![source],
EffectKind::Material(fill) => fill.sources.values().collect(),
EffectKind::Generator(generator) => generator.inputs.values().collect(),
_ => Vec::new(),
};
sources
.into_iter()
.filter_map(|source| match source {
Source::Anchor { anchor, channel } => Some((*anchor, *channel)),
_ => None,
})
.collect()
}
/// The image resources this effect's sources read (a fill, material or generator input).
pub fn images_read(&self) -> impl Iterator<Item = &str> {
let sources: Vec<&Source> = match self {
EffectKind::Fill { source, .. } => vec![source],
EffectKind::Material(fill) => fill.sources.values().collect(),
EffectKind::Generator(generator) => generator.inputs.values().collect(),
_ => Vec::new(),
};
sources.into_iter().filter_map(|source| match source {
Source::Image { name, .. } => Some(name.as_str()),
_ => None,
})
}
}
impl Layer {
@@ -1080,6 +1159,15 @@ impl Effect {
mod tests {
use super::*;
#[test]
fn material_effect_images_are_reported_as_used() {
let mut fill = Fill::default();
fill.sources.insert(Channel::BaseColor, Source::image("material.png"));
let effect = EffectKind::Material(fill);
assert_eq!(effect.images_read().collect::<Vec<_>>(), vec!["material.png"]);
}
#[test]
fn generator_offset_shifts_the_mask_value() {
let mut g = Generator::new(GeneratorKind::Position);
@@ -1115,6 +1203,22 @@ mod tests {
assert_eq!(Generator::new(GeneratorKind::Dirt).detail, None, "only curvature and edge wear generators have detail sizes");
}
#[test]
fn generators_saved_before_the_new_settings_load_and_save_unchanged() {
let saved = serde_json::to_value(Generator::new(GeneratorKind::Dirt)).unwrap();
for field in ["global", "resolution", "inputs"] {
assert!(saved.get(field).is_none(), "a default `{field}` is not written, so saved files stay as they were");
}
let loaded: Generator = serde_json::from_value(saved).unwrap();
assert!(loaded.global.is_neutral());
let mut blurred = Generator::new(GeneratorKind::Dirt);
blurred.global.blur = 0.5;
let round_trip: Generator = serde_json::from_value(serde_json::to_value(&blurred).unwrap()).unwrap();
assert_eq!(round_trip, blurred);
}
#[test]
fn levels_map_range_and_gamma() {
let l = Levels { in_low: 0.2, in_high: 0.6, gamma: 1.0, out_low: 0.0, out_high: 1.0 };
+96
View File
@@ -0,0 +1,96 @@
use serde::{Deserialize, Serialize};
/// Adjustments every generator applies to its finished value: a blur, then balance and contrast.
#[derive(Clone, Copy, Debug, PartialEq, Serialize, Deserialize)]
pub struct GeneratorGlobal {
/// Blur of the generated value (0..1 of [`GeneratorGlobal::MAX_BLUR`]).
pub blur: f32,
/// Shifts the value darker (below 0.5) or brighter (above 0.5); 0.5 leaves it unchanged.
pub balance: f32,
/// Narrows the ramp around its middle (0 unchanged, 1 a hard step).
pub contrast: f32,
}
impl GeneratorGlobal {
/// The widest blur, as a radius in texels at [`GeneratorGlobal::BLUR_RESOLUTION`].
pub const MAX_BLUR: f32 = 64.0;
/// Narrower than this, the balanced range is a hard step.
pub const MIN_RANGE: f32 = 1e-6;
/// The texels per side the blur radius is measured at (2K).
pub const BLUR_RESOLUTION: f32 = 2048.0;
pub fn is_neutral(&self) -> bool {
*self == GeneratorGlobal::default()
}
/// The blur as a radius in texels at [`GeneratorGlobal::BLUR_RESOLUTION`].
pub fn blur_radius(&self) -> f32 {
self.blur.clamp(0.0, 1.0) * GeneratorGlobal::MAX_BLUR
}
/// The blur as a radius in texels at `resolution` texels per side.
pub fn blur_radius_at(&self, resolution: u32) -> f32 {
self.blur_radius() * resolution as f32 / GeneratorGlobal::BLUR_RESOLUTION
}
/// `value` after balance and contrast: balance picks the input range stretched to 0..1, contrast narrows it around its middle.
pub fn apply(&self, value: f32) -> f32 {
if self.balance == 0.5 && self.contrast == 0.0 {
return value;
}
let balance = self.balance.clamp(0.0, 1.0);
let (low, high) = ((1.0 - 2.0 * balance).max(0.0), (2.0 - 2.0 * balance).min(1.0));
let middle = (low + high) * 0.5;
let keep = 1.0 - self.contrast.clamp(0.0, 1.0);
let (low, high) = (middle - (middle - low) * keep, middle + (high - middle) * keep);
if high - low < GeneratorGlobal::MIN_RANGE {
return if value >= middle { 1.0 } else { 0.0 };
}
((value - low) / (high - low)).clamp(0.0, 1.0)
}
}
impl Default for GeneratorGlobal {
fn default() -> Self {
GeneratorGlobal { blur: 0.0, balance: 0.5, contrast: 0.0 }
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn neutral_settings_leave_the_value_unchanged() {
let global = GeneratorGlobal::default();
for value in [0.0, 0.1, 0.5, 0.93, 1.0] {
assert_eq!(global.apply(value), value);
}
}
#[test]
fn balance_darkens_below_the_middle_and_brightens_above() {
let darker = GeneratorGlobal { balance: 0.25, ..GeneratorGlobal::default() };
assert_eq!(darker.apply(0.4), 0.0, "the lower half goes black");
assert!((darker.apply(0.75) - 0.5).abs() < 1e-6, "the upper half stretches over the whole range");
let brighter = GeneratorGlobal { balance: 0.75, ..GeneratorGlobal::default() };
assert!((brighter.apply(0.25) - 0.5).abs() < 1e-6);
assert_eq!(brighter.apply(0.6), 1.0, "the upper half goes white");
assert_eq!(GeneratorGlobal { balance: 0.0, ..GeneratorGlobal::default() }.apply(0.99), 0.0);
assert_eq!(GeneratorGlobal { balance: 1.0, ..GeneratorGlobal::default() }.apply(0.01), 1.0);
}
#[test]
fn full_contrast_is_a_step_at_the_middle_of_the_balanced_range() {
let step = GeneratorGlobal { contrast: 1.0, ..GeneratorGlobal::default() };
assert_eq!(step.apply(0.49), 0.0);
assert_eq!(step.apply(0.51), 1.0);
let half = GeneratorGlobal { contrast: 0.5, ..GeneratorGlobal::default() };
assert_eq!(half.apply(0.25), 0.0);
assert!((half.apply(0.5) - 0.5).abs() < 1e-6);
assert_eq!(half.apply(0.75), 1.0);
}
}
+120
View File
@@ -0,0 +1,120 @@
use serde::{Deserialize, Serialize};
use super::resolution_mode::ResolutionMode;
/// The resolution a generator computes its output at, before it is sampled onto the texture set.
#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize)]
pub struct OutputResolution {
pub mode: ResolutionMode,
/// Texels per side for [`ResolutionMode::Custom`].
pub custom: u32,
/// Power of two applied to the base size (−3 = 1/8 … 3 = ×8; 0 = the same as the context).
pub factor: i8,
}
impl OutputResolution {
/// The factors the reference app offers: 1/8 to ×8.
pub const FACTORS: std::ops::RangeInclusive<i8> = -3..=3;
/// The sizes offered for [`ResolutionMode::Custom`].
pub const CUSTOM_SIZES: [u32; 6] = [128, 256, 512, 1024, 2048, 4096];
/// The largest output, the largest texture set resolution.
pub const MAX_SIZE: u32 = 8192;
/// The coarsest output: one value per this many texels of the context per side (a compositing tile).
pub const MAX_CELL: u32 = 64;
pub fn is_default(&self) -> bool {
*self == OutputResolution::default()
}
/// Whether some UV tile can get a coarser output than its own resolution (a custom size, the set's size or a factor below 1).
pub fn can_reduce(&self) -> bool {
matches!(self.mode, ResolutionMode::Custom | ResolutionMode::TextureSet) || self.factor < 0
}
/// The largest cell a UV tile of up to `uv_tile` texels per side can get, whatever its texture set's resolution.
pub fn largest_cell(&self, uv_tile: u32) -> u32 {
if self.mode == ResolutionMode::TextureSet { OutputResolution::MAX_CELL } else { self.cell(uv_tile, uv_tile) }
}
/// Texels per side of the output for a UV tile of `uv_tile` texels per side in a texture set of `texture_set`.
pub fn output_size(&self, uv_tile: u32, texture_set: u32) -> u32 {
let base = match self.mode {
ResolutionMode::Auto | ResolutionMode::UvTile => uv_tile,
ResolutionMode::TextureSet => texture_set,
ResolutionMode::Custom => self.custom,
};
let factor = self.factor.clamp(*OutputResolution::FACTORS.start(), *OutputResolution::FACTORS.end());
let scaled = if factor >= 0 { base.saturating_mul(1 << factor) } else { base >> -factor };
// Hostile tile sizes can make the minimum exceed the supported maximum
let minimum = (uv_tile / OutputResolution::MAX_CELL).clamp(1, OutputResolution::MAX_SIZE);
scaled.clamp(minimum, OutputResolution::MAX_SIZE)
}
/// How many texels of the UV tile one output texel covers per side (1 when the output is as fine or finer).
pub fn cell(&self, uv_tile: u32, texture_set: u32) -> u32 {
(uv_tile / self.output_size(uv_tile, texture_set)).max(1)
}
}
impl Default for OutputResolution {
fn default() -> Self {
OutputResolution { mode: ResolutionMode::Auto, custom: 2048, factor: 0 }
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn the_default_follows_the_uv_tile() {
let resolution = OutputResolution::default();
assert_eq!(resolution.output_size(1024, 2048), 1024);
assert_eq!(resolution.cell(1024, 2048), 1);
assert!(!resolution.can_reduce());
}
#[test]
fn the_texture_set_mode_reads_the_set_not_the_uv_tile() {
let resolution = OutputResolution { mode: ResolutionMode::TextureSet, factor: -1, ..OutputResolution::default() };
assert_eq!(resolution.output_size(512, 2048), 1024, "half the set's 2048");
assert_eq!(resolution.cell(512, 2048), 1, "finer than the 512 tile: one texel per texel");
}
#[test]
fn factors_and_custom_sizes_scale_the_output() {
let eighth = OutputResolution { factor: -3, ..OutputResolution::default() };
assert_eq!((eighth.output_size(2048, 2048), eighth.cell(2048, 2048)), (256, 8));
let custom = OutputResolution { mode: ResolutionMode::Custom, custom: 512, factor: 1 };
assert_eq!((custom.output_size(2048, 2048), custom.cell(2048, 2048)), (1024, 2));
let finer = OutputResolution { factor: 3, ..OutputResolution::default() };
assert_eq!((finer.output_size(2048, 2048), finer.cell(2048, 2048)), (8192, 1), "a finer output than the tile keeps one texel per texel");
}
#[test]
fn the_largest_cell_covers_any_texture_set() {
let set = OutputResolution { mode: ResolutionMode::TextureSet, ..OutputResolution::default() };
assert!(set.can_reduce(), "a UV tile larger than its set gets the set's coarser size");
assert_eq!(set.largest_cell(2048), OutputResolution::MAX_CELL);
assert_eq!(OutputResolution { factor: -2, ..OutputResolution::default() }.largest_cell(2048), 4);
}
#[test]
fn hostile_sizes_stay_within_the_largest_output_and_the_coarsest_cell() {
let huge = OutputResolution { mode: ResolutionMode::Custom, custom: u32::MAX, factor: i8::MAX };
assert_eq!(huge.output_size(2048, 2048), OutputResolution::MAX_SIZE);
let tiny = OutputResolution { mode: ResolutionMode::Custom, custom: 1, factor: -3 };
assert_eq!(tiny.cell(4096, 4096), OutputResolution::MAX_CELL);
}
#[test]
fn hostile_uv_tile_size_does_not_panic() {
let resolution = OutputResolution::default();
assert_eq!(resolution.output_size(u32::MAX, 2048), OutputResolution::MAX_SIZE);
}
}
+32
View File
@@ -0,0 +1,32 @@
use serde::{Deserialize, Serialize};
/// What a generator's output resolution is based on.
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash, Serialize, Deserialize)]
pub enum ResolutionMode {
/// The context: the resolution of the UV tile it is computed for.
Auto,
/// The texture set's resolution.
TextureSet,
/// The UV tile's resolution.
UvTile,
/// A size of its own.
Custom,
}
impl ResolutionMode {
pub const ALL: [ResolutionMode; 4] = [ResolutionMode::Auto, ResolutionMode::TextureSet, ResolutionMode::UvTile, ResolutionMode::Custom];
pub fn label(self) -> &'static str {
match self {
ResolutionMode::Auto => "Auto",
ResolutionMode::TextureSet => "Texture set",
ResolutionMode::UvTile => "UV tile",
ResolutionMode::Custom => "Custom",
}
}
pub fn parse(name: &str) -> Option<ResolutionMode> {
let norm = |text: &str| text.to_ascii_lowercase().replace([' ', '_', '-'], "");
ResolutionMode::ALL.into_iter().find(|mode| norm(&format!("{mode:?}")) == norm(name) || norm(mode.label()) == norm(name))
}
}
+3 -3
View File
@@ -24,9 +24,9 @@ pub use bake::{
pub use blend::{BlendMode, blend1, blend3, lum, mix3};
pub use channel::{Channel, ChannelFormat, ChannelKind};
pub use layer::{
ChannelBlend, CompareOp, CurvatureDetail, CurvatureMode, Decal, Effect, EffectKind, Fill, Filter, Generator, GeneratorKind, HeightMask, Layer, LayerId,
LayerKind, Levels, LinkParam, LinkPreset, Mask, MaskBackground, MaterialLink, PathShape, Procedural, ProceduralKind, Projection, Source, gradient,
hsl_adjust, per_unit,
ChannelBlend, CompareOp, CurvatureDetail, CurvatureMode, Decal, Effect, EffectKind, Fill, Filter, Generator, GeneratorGlobal, GeneratorKind, HeightMask,
Layer, LayerId, LayerKind, Levels, LinkParam, LinkPreset, Mask, MaskBackground, MaterialLink, OutputResolution, PathShape, Procedural, ProceduralKind,
Projection, ResolutionMode, Source, gradient, hsl_adjust, per_unit,
};
pub use project::{
AoMixing, BlockScales, Camera, DepthOfField, DisplaySettings, FORMAT_VERSION, MAX_RESOLUTION, MIN_RESOLUTION, NormalFormat, NormalMixing, Project,
+56 -45
View File
@@ -2,7 +2,7 @@
//! clipboard: it holds a layer or an effect.
use serde_json::{Value, json};
use texturecraft_core::{EffectKind, LayerId, Mask, MaskBackground, Source};
use texturecraft_core::{EffectKind, LayerId, Mask, MaskBackground};
use crate::commands::{CommandSpec, bad, has_layer, layer_param, strp};
use crate::layer_ops::{empty_texel, fit};
@@ -55,26 +55,29 @@ fn cut(s: &mut Session, p: &Value) -> Result<Value> {
Ok(json!({ "cut": eid }))
}
fn paste(s: &mut Session, p: &Value) -> Result<Value> {
fn paste(session: &mut Session, params: &Value) -> Result<Value> {
const CMD: &str = "effect.paste";
let (src, eid) = s.clipboard.clone().ok_or_else(|| bad(CMD, "the clipboard holds no effect"))?;
let effect = src.project.effect(eid).map(|(_, e)| e.clone()).ok_or_else(|| bad(CMD, "the clipboard holds no effect"))?;
let layer = layer_param(s, CMD, p)?;
// The selected effect's stack, or the content or mask the selection targets.
let selected = match s.target {
StackTarget::Effect(x) if s.selected_layer() == Some(layer) => Some(x),
let (copied, copied_id) = session.clipboard.clone().ok_or_else(|| bad(CMD, "the clipboard holds no effect"))?;
let effect = copied.project.effect(copied_id).map(|(_, effect)| effect.clone()).ok_or_else(|| bad(CMD, "the clipboard holds no effect"))?;
let layer = layer_param(session, CMD, params)?;
// The selected effect's stack, or the content or mask the selection targets
let selected = match session.target {
StackTarget::Effect(selected) if session.selected_layer() == Some(layer) => Some(selected),
_ => None,
};
let in_content = |s: &Session, x: LayerId| {
s.doc.project.effect(x).and_then(|(o, _)| s.doc.project.layers.get(&o)).is_some_and(|l| l.content_effects.iter().any(|e| e.id == x))
let in_content = |session: &Session, effect_id: LayerId| {
let owner = session.doc.project.effect(effect_id).and_then(|(owner, _)| session.doc.project.layers.get(&owner));
owner.is_some_and(|owner| owner.content_effects.iter().any(|effect| effect.id == effect_id))
};
let asked = strp(p, "target").is_some();
let asked = strp(params, "target").is_some();
let content = match selected {
_ if asked => content_target(p, CMD)?,
Some(x) => in_content(s, x),
None => s.target == StackTarget::Content && s.selected_layer() == Some(layer),
_ if asked => content_target(params, CMD)?,
Some(selected) => in_content(session, selected),
None => session.target == StackTarget::Content && session.selected_layer() == Some(layer),
};
// Effects that fit one stack only go there, unless another was asked for.
// Effects that fit one stack only go there, unless another was asked for
let content = match effect.kind.content_only() {
Some(only) if only != content && asked => {
return Err(bad(CMD, format!("{} effects go on the {}", effect.kind.name(), if only { "layer content" } else { "mask" })));
@@ -82,46 +85,54 @@ fn paste(s: &mut Session, p: &Value) -> Result<Value> {
Some(only) => only,
None => content,
};
// An instance's content and (unless it has its own) mask belong to its source.
let owner = if content { s.doc.project.content_layer(layer).map_or(layer, |l| l.id) } else { s.doc.project.mask_owner(layer) };
let owner_layer = s.doc.project.layer(owner)?;
// An instance's content and (unless it has its own) mask belong to its source
let owner = if content { session.doc.project.content_layer(layer).map_or(layer, |source| source.id) } else { session.doc.project.mask_owner(layer) };
let owner_layer = session.doc.project.layer(owner)?;
if content && owner_layer.is_group() {
return Err(EngineError::Other(format!("\"{}\" is a folder: content effects go on paint and fill layers", owner_layer.name)));
}
// A fill reading an anchor point needs one below its new layer.
if let EffectKind::Fill { source: Source::Anchor { anchor, channel }, .. } = &effect.kind {
anchor_source(s, CMD, owner, *anchor, *channel)?;
// Each anchor point the effect reads must be below its new layer
for (anchor, channel) in effect.kind.anchors_read() {
anchor_source(session, CMD, owner, anchor, channel)?;
}
let (ts, _, _) = s.doc.project.locate(owner).ok_or_else(|| bad(CMD, "the layer is not in a stack"))?;
let (size, channels) = s.doc.project.texture_set(ts).map(|t| (t.size(), t.channel_list()))?;
let new = s.edit("Paste effect", |s| {
let new = s.doc.project.alloc_id();
let l = s.doc.project.layer_mut(owner)?;
let list = if content {
&mut l.content_effects
let (set, _, _) = session.doc.project.locate(owner).ok_or_else(|| bad(CMD, "the layer is not in a stack"))?;
let (size, channels) = session.doc.project.texture_set(set).map(|texture_set| (texture_set.size(), texture_set.channel_list()))?;
let pasted = session.edit("Paste effect", |session| {
let pasted = session.doc.project.alloc_id();
let owner_layer = session.doc.project.layer_mut(owner)?;
let stack = if content {
&mut owner_layer.content_effects
} else {
let bg = if matches!(effect.kind, EffectKind::Generator(_) | EffectKind::Fill { .. }) { MaskBackground::Black } else { MaskBackground::White };
&mut l.mask.get_or_insert_with(|| Mask::new(bg)).effects
let background =
if matches!(effect.kind, EffectKind::Generator(_) | EffectKind::Fill { .. }) { MaskBackground::Black } else { MaskBackground::White };
&mut owner_layer.mask.get_or_insert_with(|| Mask::new(background)).effects
};
let at = selected.and_then(|x| list.iter().position(|e| e.id == x)).map_or(list.len(), |i| i + 1);
list.insert(at, texturecraft_core::Effect { id: new, ..effect.clone() });
// Painted pixels come along, resampled to the set's size (a mask's paint stays a mask's).
if let Some(img) = src.pixels.masks.get(&eid).filter(|_| !content) {
s.doc.pixels.masks.insert(new, fit(img, size, &[0, 0]));
let index = selected.and_then(|selected| stack.iter().position(|effect| effect.id == selected)).map_or(stack.len(), |position| position + 1);
stack.insert(index, texturecraft_core::Effect { id: pasted, ..effect.clone() });
// Painted pixels come along, resampled to the set's size (a mask's paint stays a mask's)
if let Some(image) = copied.pixels.masks.get(&copied_id).filter(|_| !content) {
session.doc.pixels.masks.insert(pasted, fit(image, size, &[0, 0]));
}
for c in channels.iter().copied().filter(|_| content) {
if let Some(img) = src.pixels.layer(eid, c) {
s.doc.pixels.layers.insert((new, c), fit(img, size, &empty_texel(c)));
for channel in channels.iter().copied().filter(|_| content) {
if let Some(image) = copied.pixels.layer(copied_id, channel) {
session.doc.pixels.layers.insert((pasted, channel), fit(image, size, &empty_texel(channel)));
}
}
// The target belongs to the active set's selection: a paste into another set leaves it.
if let Some((lts, _, _)) = s.doc.project.locate(layer) {
s.selected.insert(lts, layer);
if lts == s.ts() {
s.target = StackTarget::Effect(new);
// The target belongs to the active set's selection: a paste into another set leaves it
if let Some((layer_set, _, _)) = session.doc.project.locate(layer) {
session.selected.insert(layer_set, layer);
if layer_set == session.ts() {
session.target = StackTarget::Effect(pasted);
}
}
Ok(new)
Ok(pasted)
})?;
Ok(json!({ "effect": new.0 }))
Ok(json!({ "effect": pasted.0 }))
}
+110
View File
@@ -37,6 +37,15 @@ pub fn specs() -> Vec<CommandSpec> {
always,
reimport
),
cmd!(
"file.changeMesh",
"Change mesh",
[],
None,
"{path: the new mesh file, preserveStrokes?: bool (painted pixels follow the surface where the UVs differ; default true)} → {preserved?: texels re-projected}. Keeps layers, texture sets and settings; texture sets map to the new mesh by material index",
always,
change_mesh
),
cmd!(
"file.exportTextures",
"Export textures",
@@ -438,6 +447,16 @@ fn reimport(s: &mut Session, p: &Value) -> Result<Value> {
Ok(reply)
}
#[cfg(not(target_arch = "wasm32"))]
fn change_mesh(s: &mut Session, p: &Value) -> Result<Value> {
let path = native::path_param(p, "path", "file.changeMesh")?;
let file = native::read_mesh("file.changeMesh", path)?;
let reply = s.reimport_mesh(Some(file), crate::commands::boolp(p, "preserveStrokes").unwrap_or(true))?;
// Only after the swap succeeded: Reimport mesh and Save keep following the new file.
s.doc.project.mesh_path = native::absolute(path);
Ok(reply)
}
#[cfg(not(target_arch = "wasm32"))]
impl Session {
/// The file the mesh was imported from, when it is still there: what Reimport mesh reads again.
@@ -471,6 +490,19 @@ impl Session {
let mut next = Session::new(doc, mesh, source)?;
next.log.extend(warnings);
next.path = self.path.clone();
next.sync_images();
// The high polys and the skew map stay. The cage is sampled by triangle index and
// barycentrics, so it stays only for an identical mesh; the low poly's base colours are
// read again from the new mesh.
next.bake_meshes = self.bake_meshes.clone();
next.bake_meshes.low_base_color = Default::default();
if next.bake_meshes.cage.is_some() && *next.mesh != *self.mesh {
next.bake_meshes.cage = None;
next.log.push("the cage mesh was dropped: the low-poly mesh changed".into());
}
if self.doc.bake_paint.keys().any(|(_, target)| *target == texturecraft_core::BakePaintTarget::Skew) && self.source.uvs != next.source.uvs {
next.log.push("the skew map is laid over the old UV layout; check it in Bake mode".into());
}
next.modified = true;
next.project_id = self.project_id;
let preserved = preserve_strokes.then(|| crate::preserve::preserve_strokes(self, &mut next));
@@ -621,6 +653,8 @@ use unsupported as save_copy;
#[cfg(target_arch = "wasm32")]
use unsupported as reimport;
#[cfg(target_arch = "wasm32")]
use unsupported as change_mesh;
#[cfg(target_arch = "wasm32")]
use unsupported as export_textures;
#[cfg(target_arch = "wasm32")]
use unsupported as export_mesh;
@@ -764,6 +798,82 @@ f 1/1 2/2 3/3
let _ = std::fs::remove_dir_all(&dir);
}
/// A project built on one mesh moves to another mesh file with its layers intact, even when
/// it carries its own copy of the mesh (a plain reimport would only re-read that copy).
#[test]
fn change_mesh_swaps_the_mesh_and_keeps_the_layers() {
let dir = std::env::temp_dir().join(format!("tc_change_mesh_{}", std::process::id()));
std::fs::create_dir_all(&dir).unwrap();
let quad = dir.join("quad.obj");
std::fs::write(&quad, "v 0 0 0\nv 1 0 0\nv 1 1 0\nv 0 1 0\nvt 0 0\nvt 1 0\nvt 1 1\nvt 0 1\nf 1/1 2/2 3/3 4/4\n").unwrap();
let tri = dir.join("tri.obj");
std::fs::write(&tri, "v 0 0 0\nv 1 0 0\nv 0 1 0\nvt 0 0\nvt 1 0\nvt 0 1\nf 1/1 2/2 3/3\n").unwrap();
let mut s = Session::from_mesh_bytes("quad.obj", &std::fs::read(&quad).unwrap(), 128, "quad").unwrap();
crate::execute(&mut s, "layer.add.fill", &json!({"color": [1.0, 0.0, 0.0]})).unwrap();
let layers = s.doc.project.layers.len();
assert!(crate::execute(&mut s, "file.changeMesh", &json!({})).is_err(), "a path is required");
crate::execute(&mut s, "file.changeMesh", &json!({"path": tri.display().to_string()})).unwrap();
assert_eq!(s.mesh.triangle_count(), 1, "the new mesh is in use");
assert_eq!(s.doc.project.mesh_file, "tri.obj");
assert_eq!(s.doc.project.layers.len(), layers, "the layers stay");
std::fs::remove_dir_all(&dir).ok();
}
/// Open A, change to B, edit B on disk: Reimport mesh (also after save and reopen) must read B,
/// not A. A failed change leaves the remembered path alone.
#[test]
fn change_mesh_remembers_the_new_file_for_reimport() {
let dir = std::env::temp_dir().join(format!("tc_change_mesh_path_{}", std::process::id()));
std::fs::create_dir_all(&dir).unwrap();
let obj = |x: f32| format!("v 0 0 0\nv {x} 0 0\nv 0 1 0\nvt 0 0\nvt 1 0\nvt 0 1\nf 1/1 2/2 3/3\n");
let (a, b) = (dir.join("a.obj"), dir.join("b.obj"));
std::fs::write(&a, obj(1.0)).unwrap();
std::fs::write(&b, obj(2.0)).unwrap();
let width = |s: &Session| s.mesh.positions.iter().map(|p| p.x).fold(0.0_f32, f32::max);
let mut s = Session::new_project("t", primitives::material_ball(), "builtin:material_ball", None, 128).unwrap();
crate::execute(&mut s, "file.new", &json!({"mesh": a.display().to_string(), "resolution": 128})).unwrap();
let a_abs = s.remembered_mesh_path().map(str::to_string).unwrap();
// A failed change (unreadable file) keeps A.
let missing = dir.join("missing.obj");
assert!(crate::execute(&mut s, "file.changeMesh", &json!({"path": missing.display().to_string()})).is_err());
assert_eq!(s.remembered_mesh_path(), Some(a_abs.as_str()));
crate::execute(&mut s, "file.changeMesh", &json!({"path": b.display().to_string()})).unwrap();
assert_eq!(width(&s), 2.0);
let b_abs = s.remembered_mesh_path().map(str::to_string).expect("B is remembered");
assert_ne!(a_abs, b_abs);
// The remembered path survives save and reopen.
let mut reopened = Session::from_project_bytes(&s.to_project_bytes().unwrap()).unwrap();
assert_eq!(reopened.remembered_mesh_path(), Some(b_abs.as_str()));
// Edit B, then Reimport from the remembered path: B's edits arrive, not A.
std::fs::write(&b, obj(3.0)).unwrap();
let remembered = reopened.remembered_mesh_path().map(str::to_string).unwrap();
crate::execute(&mut reopened, "file.reimportMesh", &json!({"path": remembered})).unwrap();
assert_eq!(width(&reopened), 3.0);
std::fs::remove_dir_all(&dir).ok();
}
#[test]
fn change_mesh_resets_base_colours_and_drops_a_cage_of_another_mesh() {
let dir = std::env::temp_dir().join(format!("tc_change_mesh_cage_{}", std::process::id()));
std::fs::create_dir_all(&dir).unwrap();
let a = dir.join("a.obj");
std::fs::write(&a, "v 0 0 0\nv 1 0 0\nv 0 1 0\nvt 0 0\nvt 1 0\nvt 0 1\nf 1/1 2/2 3/3\n").unwrap();
// Same triangle count, other vertices.
let b = dir.join("b.obj");
std::fs::write(&b, "v 0 0 0\nv 2 0 0\nv 0 2 0\nvt 0 0\nvt 1 0\nvt 0 1\nf 1/1 2/2 3/3\n").unwrap();
let mut s = Session::from_mesh_bytes("a.obj", &std::fs::read(&a).unwrap(), 128, "a").unwrap();
let cage = crate::bake::BakeMesh { name: "cage".into(), bytes: Default::default(), mesh: s.mesh.clone(), base_color: Vec::new() };
s.bake_meshes.cage = Some(cage);
let _ = s.bake_meshes.low_base_color.set(Err("old".into()));
// The same mesh again keeps the cage but not the cached colours.
crate::execute(&mut s, "file.changeMesh", &json!({"path": a.display().to_string()})).unwrap();
assert!(s.bake_meshes.cage.is_some());
assert!(s.bake_meshes.low_base_color.get().is_none(), "the colours are read again");
crate::execute(&mut s, "file.changeMesh", &json!({"path": b.display().to_string()})).unwrap();
assert!(s.bake_meshes.cage.is_none(), "the cage was made for another mesh");
std::fs::remove_dir_all(&dir).ok();
}
#[test]
fn unnamed_parts_keep_their_names_and_masks_through_save_and_reopen() {
// A GLB quad whose mesh and node have no name: its one part is named after the file.
+10 -3
View File
@@ -69,9 +69,16 @@ fn effect_json(session: &Session, effect: &Effect, content: bool) -> Value {
out
}
/// A generator's settings, with its curvature mode and detail size weights when it has them.
/// A generator's settings: global adjustments, then its resolution, replaced inputs and curvature detail when it has them.
fn generator_json(generator: &Generator) -> Value {
let mut out = json!({ "type": format!("{:?}", generator.kind), "level": generator.level, "softness": generator.softness, "noise": generator.noise_amount, "offset": generator.offset, "invert": generator.invert });
let mut out = json!({ "type": format!("{:?}", generator.kind), "level": generator.level, "softness": generator.softness, "noise": generator.noise_amount, "offset": generator.offset, "invert": generator.invert, "blur": generator.global.blur, "balance": generator.global.balance, "contrast": generator.global.contrast });
if !generator.resolution.is_default() {
out["resolution"] =
json!({ "mode": format!("{:?}", generator.resolution.mode), "custom": generator.resolution.custom, "factor": generator.resolution.factor });
}
if !generator.inputs.is_empty() {
out["inputs"] = generator.inputs.iter().map(|(map, source)| (map.id().to_string(), source_json(source))).collect::<serde_json::Map<_, _>>().into();
}
if let Some(detail) = &generator.detail {
out["mode"] = json!(format!("{:?}", detail.mode));
out["sizes"] = json!(detail.weights);
@@ -105,7 +112,7 @@ fn layer_json(s: &Session, l: &Layer, depth: usize) -> Value {
v["geometryMask"] = json!(parts);
}
if matches!(l.kind, LayerKind::Paint) {
// Sorted: the store is a hash map, and inspect output must be stable.
// Sort the hash map entries for stable inspection output
let mut painted: Vec<(&str, usize)> =
s.doc.pixels.layers.iter().filter(|((id, _), _)| *id == l.id).map(|((_, c), img)| (c.id(), img.allocated_count())).collect();
painted.sort_unstable();
+105 -10
View File
@@ -56,7 +56,7 @@ pub fn specs() -> Vec<CommandSpec> {
"Save MaterialCraft package",
[],
None,
"{layer?, path} — writes the MaterialCraft package (.mcraft) behind a material layer, to open in MaterialCraft",
"{layer?, path} — writes the MaterialCraft source (.mcraft or .sbs) behind a material layer",
has_layer,
save_source
),
@@ -178,7 +178,9 @@ fn save_source(s: &mut Session, p: &Value) -> Result<Value> {
const CMD: &str = "material.link.saveSource";
let id = layer_param(s, CMD, p)?;
let path = strp(p, "path").ok_or_else(|| bad(CMD, "`path` is required"))?;
let path = if path.to_ascii_lowercase().ends_with(&format!(".{MCRAFT_EXT}")) { path.to_string() } else { format!("{path}.{MCRAFT_EXT}") };
let link = link_of(s, CMD, id)?;
let ext = source_extension(&link.package);
let path = if path.to_ascii_lowercase().ends_with(&format!(".{ext}")) { path.to_string() } else { format!("{path}.{ext}") };
let bytes = s.link_package(id)?;
texturecraft_formats::write_atomic(std::path::Path::new(&path), &bytes).map_err(|e| bad(CMD, e.to_string()))?;
Ok(json!({"path": path}))
@@ -195,6 +197,10 @@ fn save_source(_: &mut Session, _: &Value) -> Result<Value> {
pub struct LinkJob {
pub layer: LayerId,
pub package: Arc<Vec<u8>>,
/// The source package extension (`mcraft` or `sbs`).
pub source_ext: &'static str,
/// The named graph in a linked material; direct package imports use its default.
pub graph: Option<String>,
/// Pixels across (the texture set's resolution).
pub size: u32,
/// Every parameter's value, by id, in MaterialCraft's typed form.
@@ -226,7 +232,7 @@ fn quiet(program: &std::path::Path) -> std::process::Command {
c
}
/// Open `package` (a `.mcraft` file) in the MaterialCraft app (`$MATERIALCRAFT`, next to this
/// Open `package` (a `.mcraft` or `.sbs` file) in the MaterialCraft app (`$MATERIALCRAFT`, next to this
/// program, or on `PATH`).
#[cfg(not(target_arch = "wasm32"))]
pub fn open_in_materialcraft(package: &std::path::Path) -> Result<()> {
@@ -236,11 +242,21 @@ pub fn open_in_materialcraft(package: &std::path::Path) -> Result<()> {
})
}
/// Source file extensions are chosen from the linked resource name, never an untrusted path.
pub fn source_extension(name: &str) -> &'static str {
if name.to_ascii_lowercase().ends_with(".sbs") { "sbs" } else { MCRAFT_EXT }
}
impl LinkJob {
/// Cook through `materialcraft-cli` (`$MATERIALCRAFT_CLI`, next to this program, or on
/// `PATH`); returns `.mcmat` bytes. Blocks for the cook (about a second at 2K).
#[cfg(not(target_arch = "wasm32"))]
pub fn run(&self) -> Result<Vec<u8>> {
self.run_with_cli(&materialcraft_tool("materialcraft-cli", "MATERIALCRAFT_CLI"))
}
#[cfg(not(target_arch = "wasm32"))]
fn run_with_cli(&self, cli: &std::path::Path) -> Result<Vec<u8>> {
let other = |e: String| EngineError::Other(e);
let n = NEXT_JOB.fetch_add(1, std::sync::atomic::Ordering::Relaxed);
let dir = std::env::temp_dir().join(format!("texturecraft-link-{}-{n}", std::process::id()));
@@ -252,15 +268,27 @@ impl LinkJob {
std::fs::write(&p, bytes).map_err(|e| other(format!("{name}: {e}")))?;
utf8(&p)
};
let src = write("source.mcraft", &self.package)?;
let ext = if self.source_ext == "sbs" { "sbs" } else { MCRAFT_EXT };
let src = write(&format!("source.{ext}"), &self.package)?;
let mut inputs = Map::new();
for (i, (id, png)) in self.inputs.iter().enumerate() {
inputs.insert(id.clone(), json!(write(&format!("input{i}.png"), png)?));
}
let out = dir.join(format!("out.{MCMAT_EXT}"));
let params = json!({"path": utf8(&out)?, "size": self.size, "values": self.values, "inputs": inputs});
let cli = materialcraft_tool("materialcraft-cli", "MATERIALCRAFT_CLI");
let run = quiet(&cli).arg("run").arg(&src).arg("file.exportMaterial").arg(params.to_string()).output().map_err(|e| {
let mut command = quiet(cli);
if let Some(graph) = &self.graph {
// Opening the source starts on its first graph; select the graph saved in the link.
let script = json!({"open": src, "steps": [
{"id": "graph.open", "params": {"graph": graph}},
{"id": "file.exportMaterial", "params": params},
]});
let script_path = write("cook.json", script.to_string().as_bytes())?;
command.arg("batch").arg(script_path);
} else {
command.arg("run").arg(&src).arg("file.exportMaterial").arg(params.to_string());
}
let run = command.output().map_err(|e| {
other(format!(
"MaterialCraft's command line ({}) did not start: {e}. Install MaterialCraft next to TextureCraft or set MATERIALCRAFT_CLI",
cli.display()
@@ -301,7 +329,15 @@ impl Session {
let bytes = if is_mcraft(bytes) {
let ts = self.ts();
let size = self.doc.project.texture_set(ts)?.resolution;
let job = LinkJob { layer: LayerId(0), package: Arc::new(bytes.to_vec()), size, values: Map::new(), inputs: Vec::new() };
let job = LinkJob {
layer: LayerId(0),
package: Arc::new(bytes.to_vec()),
source_ext: MCRAFT_EXT,
graph: None,
size,
values: Map::new(),
inputs: Vec::new(),
};
cooked = job.run()?;
cooked.as_slice()
} else {
@@ -316,7 +352,7 @@ impl Session {
let (id, names) = self.edit(&label, |s| {
let ts = s.ts();
let stem = texturecraft_formats::sanitize_resource_name(&m.manifest.name);
let package = unique(s, &format!("{stem}.{MCRAFT_EXT}"));
let package = unique(s, &format!("{stem}.{}", source_extension(&m.manifest.source)));
s.doc.resources.insert(package.clone(), Arc::new(m.source.clone()));
let link = MaterialLink {
name: m.manifest.name.clone(),
@@ -345,7 +381,7 @@ impl Session {
Ok(id)
}
/// The `.mcraft` package behind linked layer `id`.
/// The source package behind linked layer `id`.
pub fn link_package(&self, id: LayerId) -> Result<Arc<Vec<u8>>> {
let link = link_of(self, "material.link", id)?;
self.doc.resources.get(&link.package).cloned().ok_or_else(|| EngineError::Other(format!("the package of {} is missing", link.name)))
@@ -376,7 +412,15 @@ impl Session {
// UDIM tiles share one cook at the texture set's base resolution
let size = self.doc.project.texture_set(texture_set)?.resolution;
Ok(LinkJob { layer: id, package: self.link_package(id)?, size, values, inputs })
Ok(LinkJob {
layer: id,
package: self.link_package(id)?,
source_ext: source_extension(&link.package),
graph: Some(link.graph.clone()),
size,
values,
inputs,
})
}
/// Swap in maps a [`LinkJob`] cooked (`.mcmat` bytes) and the values they were cooked with.
@@ -456,3 +500,54 @@ fn put_maps(s: &mut Session, stem: &str, maps: &[(Channel, Vec<u8>, texturecraft
}
names
}
#[cfg(all(test, unix))]
mod subprocess_tests {
use super::*;
use std::os::unix::fs::PermissionsExt;
#[test]
fn cook_uses_the_saved_graph_and_source_type_without_global_environment() {
let id = NEXT_JOB.fetch_add(1, std::sync::atomic::Ordering::Relaxed);
let dir = std::env::temp_dir().join(format!("texturecraft-cook-test-{}-{id}", std::process::id()));
std::fs::create_dir_all(&dir).unwrap();
let cli = dir.join("materialcraft-cli");
let script = r#"#!/bin/sh
set -eu
case "$1" in
batch)
grep -F '"graph":"Second"' "$2" >/dev/null
grep -F '"id":"file.exportMaterial"' "$2" >/dev/null
test -f "$(dirname "$2")/source.sbs"
test -f "$(dirname "$2")/input0.png"
cp "$(dirname "$0")/result.mcmat" "$(dirname "$2")/out.mcmat"
;;
run)
test "$(basename "$2")" = "source.mcraft"
cp "$(dirname "$0")/result.mcmat" "$(dirname "$2")/out.mcmat"
;;
*) exit 1 ;;
esac
"#;
std::fs::write(&cli, script).unwrap();
std::fs::set_permissions(&cli, std::fs::Permissions::from_mode(0o700)).unwrap();
std::fs::write(dir.join("result.mcmat"), b"cooked").unwrap();
let mut job = LinkJob {
layer: LayerId(1),
package: Arc::new(b"source".to_vec()),
source_ext: "sbs",
graph: Some("Second".into()),
size: 64,
values: Map::new(),
inputs: vec![("curvature".into(), b"png".to_vec())],
};
assert_eq!(job.run_with_cli(&cli).unwrap(), b"cooked");
job.graph = None;
job.source_ext = "mcraft";
assert_eq!(job.run_with_cli(&cli).unwrap(), b"cooked");
job.graph = Some("wrong".into());
assert!(job.run_with_cli(&cli).is_err());
assert!(job.run_with_cli(&dir.join("missing")).is_err());
let _ = std::fs::remove_dir_all(dir);
}
}
+89 -8
View File
@@ -2,8 +2,8 @@
use serde_json::{Value, json};
use texturecraft_core::{
BlendMode, Channel, CompareOp, CurvatureDetail, CurvatureMode, Effect, EffectKind, Filter, Generator, GeneratorKind, LayerId, Levels, Mask, MaskBackground,
Procedural, ProceduralKind, Project, Source,
BakedMap, BlendMode, Channel, CompareOp, CurvatureDetail, CurvatureMode, Effect, EffectKind, Filter, Generator, GeneratorKind, LayerId, Levels, Mask,
MaskBackground, OutputResolution, Procedural, ProceduralKind, Project, ResolutionMode, Source,
};
use crate::commands::{CommandSpec, always, bad, blend_param, boolp, channel_param, color_param, f32p, has_layer, layer_param, strp, u64p};
@@ -49,7 +49,7 @@ pub fn specs() -> Vec<CommandSpec> {
"Add generator",
["Layers", "Effects"],
None,
"{layer?, name?, generator?: edgeWear|dirt|thinAreas|curvature|ambientOcclusion|position|direction, level?, softness?, noise?, offset?: -1..1 added to the result, invert?, mode?: edges|cavities|both|raw, sizes?: [7 weights 0..1, finest first] (curvature and edgeWear)}",
"{layer?, name?, generator?: edgeWear|dirt|thinAreas|curvature|ambientOcclusion|position|direction, level?, softness?, noise?, offset?: -1..1 added to the result, invert?, blur?: 0..1, balance?: 0..1 (0.5 unchanged), contrast?: 0..1, resolution?: auto|textureSet|uvTile|custom, customResolution?, resolutionFactor?: -3..3 (1/8..x8), mode?: edges|cavities|both|raw, sizes?: [7 weights 0..1, finest first] (curvature and edgeWear)}",
has_layer,
add_generator
),
@@ -94,7 +94,7 @@ pub fn specs() -> Vec<CommandSpec> {
"Edit effect",
[],
None,
"{effect, visible?, blend?, opacity?, name?, filter?: id from filter.list (a filter effect only: swaps its type, keeping position, blend and opacity; its current id edits it in place), level?, softness?, noise?, noiseScale?, offset?, invert?, mode?, sizes?, value?, anchor?, anchorChannel?, inLow?, inHigh?, gamma?, outLow?, outHigh?, tolerance?, colors?: [[r,g,b], ...] (a color selection's ID colors), filter parameters (see effect.add.filter)}",
"{effect, visible?, blend?, opacity?, name?, filter?: id from filter.list (a filter effect only: swaps its type, keeping position, blend and opacity; its current id edits it in place), generator?: kind (a generator effect only: changes kind in place), level?, softness?, noise?, noiseScale?, offset?, invert?, blur?, balance?, contrast?, resolution?, customResolution?, resolutionFactor?, input?: mesh map id + one of inputImage?, inputValue?, inputAnchor?, inputBaked?: true (a generator), mode?, sizes?, value?, anchor?, anchorChannel?, inLow?, inHigh?, gamma?, outLow?, outHigh?, tolerance?, colors?: [[r,g,b], ...] (a color selection's ID colors), filter parameters (see effect.add.filter)}",
has_layer,
set
),
@@ -242,7 +242,7 @@ fn push_effect(s: &mut Session, p: &Value, kind: EffectKind, blend: BlendMode) -
let label = format!("Add {}", kind.name().to_ascii_lowercase());
let eid = with_mask(s, p, "effect.add", &label, |s, id| {
let eid = s.doc.project.alloc_id();
// An instance's content and (unless it has its own) mask belong to its source.
// An instance's content and inherited mask belong to its source
let id = if content { s.doc.project.content_layer(id).map_or(id, |l| l.id) } else { s.doc.project.mask_owner(id) };
let l = s.doc.project.layer_mut(id)?;
let bg = if matches!(kind, EffectKind::Generator(_) | EffectKind::Fill { .. }) { MaskBackground::Black } else { MaskBackground::White };
@@ -323,13 +323,13 @@ fn generator_from(command: &str, params: &Value, generator: &mut Generator) -> R
generator.softness = softness.clamp(0.0, 1.0);
}
if let Some(noise) = f32p(params, "noise") {
generator.noise_amount = noise.clamp(0.0, 2.0);
generator.noise_amount = noise.clamp(0.0, Generator::MAX_NOISE_AMOUNT);
}
if let Some(offset) = f32p(params, "offset") {
generator.offset = offset.clamp(-1.0, 1.0);
}
if let Some(noise_scale) = f32p(params, "noiseScale") {
generator.noise_scale = noise_scale.clamp(0.01, 1000.0);
generator.noise_scale = noise_scale.clamp(Generator::MIN_NOISE_SCALE, Generator::MAX_NOISE_SCALE);
}
if let Some(seed) = u64p(params, "seed") {
generator.seed = seed as u32;
@@ -340,6 +340,26 @@ fn generator_from(command: &str, params: &Value, generator: &mut Generator) -> R
if let Some(direction) = color_param(command, params, "direction")? {
generator.direction = direction;
}
if let Some(blur) = f32p(params, "blur") {
generator.global.blur = blur.clamp(0.0, 1.0);
}
if let Some(balance) = f32p(params, "balance") {
generator.global.balance = balance.clamp(0.0, 1.0);
}
if let Some(contrast) = f32p(params, "contrast") {
generator.global.contrast = contrast.clamp(0.0, 1.0);
}
if let Some(value) = params.get("resolution") {
let name = value.as_str().ok_or_else(|| bad(command, "`resolution` must be a string"))?;
generator.resolution.mode = ResolutionMode::parse(name).ok_or_else(|| bad(command, format!("unknown resolution `{name}`")))?;
}
if let Some(custom) = u64p(params, "customResolution") {
generator.resolution.custom = custom.clamp(1, u64::from(OutputResolution::MAX_SIZE)) as u32;
}
if let Some(factor) = params.get("resolutionFactor") {
let factor = factor.as_i64().ok_or_else(|| bad(command, "`resolutionFactor` must be a whole number"))?;
generator.resolution.factor = factor.clamp(i64::from(*OutputResolution::FACTORS.start()), i64::from(*OutputResolution::FACTORS.end())) as i8;
}
// A mode or sizes also give a curvature generator saved before detail sizes its detail
let mode = params
@@ -378,6 +398,35 @@ fn size_weights(command: &str, value: &Value) -> Result<[f32; CurvatureDetail::S
Ok(weights)
}
/// The generator input named by `input` and what replaces it (None: its mesh map again), for a generator on layer `owner`.
fn generator_input_param(session: &Session, owner: LayerId, params: &Value) -> Result<Option<(BakedMap, Option<Source>)>> {
const CMD: &str = "effect.set";
let Some(name) = params.get("input") else { return Ok(None) };
let name = name.as_str().ok_or_else(|| bad(CMD, "`input` must be a mesh map id"))?;
let map = BakedMap::parse(name).ok_or_else(|| bad(CMD, format!("unknown input `{name}`")))?;
let image = strp(params, "inputImage");
let value = f32p(params, "inputValue");
let anchor = u64p(params, "inputAnchor");
let baked = boolp(params, "inputBaked") == Some(true);
let source = match (image, value, anchor, baked) {
(Some(image), None, None, false) => {
if !session.images.contains_key(image) {
return Err(bad(CMD, format!("no image resource `{image}`")));
}
Some(Source::Image { name: image.to_string(), normal_format: Default::default() })
}
(None, Some(value), None, false) => Some(Source::Uniform([value.clamp(0.0, 1.0); 3])),
(None, None, Some(anchor), false) => {
let channel = channel_param(CMD, params, "anchorChannel")?.unwrap_or(Channel::Height);
Some(anchor_source(session, CMD, owner, LayerId(anchor), channel)?)
}
(None, None, None, true) => None,
_ => return Err(bad(CMD, "`input` takes exactly one of inputImage, inputValue, inputAnchor or inputBaked")),
};
Ok(Some((map, source)))
}
fn add_generator(session: &mut Session, params: &Value) -> Result<Value> {
let kind = match strp(params, "generator") {
Some(name) => GeneratorKind::parse(name).ok_or_else(|| bad("effect.add.generator", format!("unknown generator `{name}`")))?,
@@ -458,6 +507,13 @@ fn set(session: &mut Session, params: &Value) -> Result<Value> {
const CMD: &str = "effect.set";
let effect = effect_id(session, params, CMD)?;
let blend = blend_param(CMD, params, "blend")?;
let generator_kind = params
.get("generator")
.map(|value| {
let name = value.as_str().ok_or_else(|| bad(CMD, "`generator` must be a string"))?;
GeneratorKind::parse(name).ok_or_else(|| bad(CMD, format!("unknown generator `{name}`")))
})
.transpose()?;
// `anchor` picks a fill's anchor point, `anchorChannel` alone re-targets the current one
let anchor = match session.doc.project.effect(effect) {
@@ -475,6 +531,12 @@ fn set(session: &mut Session, params: &Value) -> Result<Value> {
_ => None,
};
// `input` names a generator input that `inputImage`, `inputValue` or `inputAnchor` replaces, or `inputBaked` puts back
let input = match session.doc.project.effect(effect) {
Some((owner, Effect { kind: EffectKind::Generator(_), .. })) => generator_input_param(session, owner, params)?,
_ => None,
};
// Naming the filter the effect already is edits its parameters like a plain effect.set
let swapped = match strp(params, "filter") {
Some(filter) if crate::filter_lib::find(filter).is_some_and(|def| current_filter_id(session, effect) == Some(def.id)) => None,
@@ -508,7 +570,26 @@ fn set(session: &mut Session, params: &Value) -> Result<Value> {
}
match &mut edited.kind {
EffectKind::Generator(generator) => generator_from(CMD, params, generator)?,
EffectKind::Generator(generator) => {
if let Some(kind) = generator_kind
&& kind != generator.kind
{
generator.kind = kind;
generator.detail = Generator::new(kind).detail;
generator.inputs.retain(|map, _| kind.inputs().contains(map));
}
generator_from(CMD, params, generator)?;
if let Some((map, source)) = input {
if !generator.kind.inputs().contains(&map) {
return Err(bad(CMD, format!("this generator has no `{}` input", map.id())));
}
match source {
Some(source) => generator.inputs.insert(map, source),
None => generator.inputs.remove(&map),
};
}
}
_ if generator_kind.is_some() => return Err(bad(CMD, "`generator` requires a generator effect")),
EffectKind::Levels(levels) => levels_from(params, levels),
// The swapped filter was built with the parameters already
EffectKind::Filter(_) if swaps_filter => {}
+13 -14
View File
@@ -7,7 +7,7 @@ use std::sync::Arc;
use serde_json::Value;
use texturecraft_compose::PixelStore;
use texturecraft_core::{EffectKind, LayerId, LayerKind, Project, Source, TextureSet};
use texturecraft_core::{LayerId, LayerKind, Project, Source, TextureSet};
use crate::commands::{CommandSpec, always, has_layer};
use crate::materials::Place;
@@ -36,27 +36,26 @@ fn fe(e: texturecraft_formats::FormatError) -> EngineError {
EngineError::Other(e.to_string())
}
/// Image resources a layer subtree uses (fill sources and fill effects).
pub(crate) fn images_used(p: &Project, id: LayerId, out: &mut Vec<String>, depth: usize) {
/// Image resources a layer subtree uses (fill sources and mask or content effects).
pub(crate) fn images_used(project: &Project, id: LayerId, out: &mut Vec<String>, depth: usize) {
if depth > texturecraft_core::project::MAX_DEPTH {
return;
}
let Some(l) = p.layers.get(&id) else { return };
if let LayerKind::Fill(f) = &l.kind {
for s in f.sources.values() {
if let Source::Image { name, .. } = s {
let Some(layer) = project.layers.get(&id) else { return };
if let LayerKind::Fill(fill) = &layer.kind {
for source in fill.sources.values() {
if let Source::Image { name, .. } = source {
out.push(name.clone());
}
}
out.extend(f.link.as_ref().map(|link| link.package.clone()));
out.extend(fill.link.as_ref().map(|link| link.package.clone()));
}
for e in l.mask.iter().flat_map(|m| m.effects.iter()) {
if let EffectKind::Fill { source: Source::Image { name, .. }, .. } = &e.kind {
out.push(name.clone());
}
for effect in layer.mask.iter().flat_map(|mask| mask.effects.iter()).chain(&layer.content_effects) {
out.extend(effect.kind.images_read().map(str::to_string));
}
for c in l.children() {
images_used(p, *c, out, depth + 1);
for child in layer.children() {
images_used(project, *child, out, depth + 1);
}
}
+65 -2
View File
@@ -16,8 +16,14 @@ use crate::Session;
const REACH: f32 = 0.05;
/// Re-project the painted pixels of `next` (a session on the reimported mesh holding `old`'s
/// document) from `old`'s UV layout. Returns how many texels found the old surface.
/// document) from `old`'s UV layout. Returns how many texels found the old surface;
/// a texture set where none does keeps its pixels as they are. Nothing is re-projected when the
/// UV layout and topology are unchanged (same triangles, materials and UVs): the pixels already
/// sit where they belong, however far the mesh moved.
pub(crate) fn preserve_strokes(old: &Session, next: &mut Session) -> usize {
if same_layout(&old.mesh, &next.mesh) {
return 0;
}
let reach = REACH * 2.0 * old.mesh.radius().max(next.mesh.radius());
let mut found = 0;
for ts in 0..next.set_count() {
@@ -52,7 +58,12 @@ pub(crate) fn preserve_strokes(old: &Session, next: &mut Session) -> usize {
((tx, ty), src)
})
.collect();
found += table.values().flatten().filter(|p| p[0].is_finite()).count();
let matched = table.values().flatten().filter(|p| p[0].is_finite()).count();
found += matched;
// No old surface within reach anywhere (a moved or unrelated mesh): the paint stays where it is.
if matched == 0 {
continue;
}
let map = |x: f32, y: f32| {
let (xi, yi) = (x as u32, y as u32);
table.get(&(xi / TILE, yi / TILE)).and_then(|t| t.get(((yi % TILE) * TILE + xi % TILE) as usize)).filter(|p| p[0].is_finite()).map(|p| (p[0], p[1]))
@@ -63,6 +74,12 @@ pub(crate) fn preserve_strokes(old: &Session, next: &mut Session) -> usize {
found
}
/// Same index buffer, same UVs per vertex and the same material ranges.
fn same_layout(a: &texturecraft_geom::Mesh, b: &texturecraft_geom::Mesh) -> bool {
let ranges = |m: &texturecraft_geom::Mesh| m.submeshes.iter().map(|s| (s.material, s.start, s.count)).collect::<Vec<_>>();
a.indices == b.indices && a.uvs == b.uvs && ranges(a) == ranges(b)
}
#[cfg(test)]
mod tests {
use super::*;
@@ -104,4 +121,50 @@ mod tests {
}
assert!(right > 10_000 && wrong == 0, "{right} right, {wrong} wrong");
}
#[test]
fn a_mesh_with_no_surface_in_reach_keeps_the_paint_where_it_is() {
let mut s = Session::new_project("p", primitives::builtin("plane").unwrap(), "builtin:plane", None, 128).unwrap();
let id = s.doc.project.texture_sets[0].stack[0];
let img = s.doc.pixels.layer_mut(id, Channel::BaseColor, (128, 128));
for x in 0..64 {
img.set(x, 40, &[65535, 0, 0, 65535]);
}
// The same plane far away and with mirrored UVs (so the layout differs and the unchanged-layout
// shortcut is not taken): nothing of the old surface is within reach.
let mut mesh = (*s.mesh).clone();
for p in &mut mesh.positions {
p.x += 100.0;
}
for uv in &mut mesh.uvs {
*uv = Vec2::new(1.0 - uv.x, uv.y);
}
let mut next = Session::new(s.doc.clone(), mesh, None).unwrap();
assert_eq!(preserve_strokes(&s, &mut next), 0);
let img = next.doc.pixels.layer(id, Channel::BaseColor).unwrap();
assert_eq!(img.get(10, 40)[3], 65535, "the painted texel is still there");
}
#[test]
fn a_translated_mesh_with_the_same_uvs_keeps_every_pixel() {
let mut s = Session::new_project("p", primitives::builtin("plane").unwrap(), "builtin:plane", None, 128).unwrap();
let id = s.doc.project.texture_sets[0].stack[0];
let img = s.doc.pixels.layer_mut(id, Channel::BaseColor, (128, 128));
for x in 0..128 {
img.set(x, 40, &[65535, 0, 0, 65535]);
}
// Slid along its own surface by a fraction of the plane: half of it still overlaps the old one.
let mut mesh = (*s.mesh).clone();
let shift = mesh.radius() * 0.5;
for p in &mut mesh.positions {
p.x += shift;
}
let mut next = Session::new(s.doc.clone(), mesh, None).unwrap();
assert_eq!(preserve_strokes(&s, &mut next), 0);
let img = next.doc.pixels.layer(id, Channel::BaseColor).unwrap();
for x in 0..128 {
assert_eq!(img.get(x, 40)[3], 65535, "texel {x} of the painted row moved");
assert_eq!(img.get(x, 41)[3], 0, "texel {x} of the next row got paint");
}
}
}
+1
View File
@@ -595,6 +595,7 @@ impl Session {
|| layer.mask.iter().flat_map(|mask| &mask.effects).chain(&layer.content_effects).any(|effect| match &effect.kind {
EffectKind::Fill { source, .. } => uses_source(source),
EffectKind::Material(fill) => uses_fill(fill),
EffectKind::Generator(generator) => generator.inputs.values().any(uses_source),
_ => false,
})
})
+39
View File
@@ -612,3 +612,42 @@ fn a_failed_multi_set_bake_restores_settings_pixels_and_history() {
assert_eq!(session.doc.baked, original.baked);
assert_eq!(session.history_labels(), history);
}
/// `file.changeMesh` swaps the mesh under a baked project: the high poly and the skew map stay,
/// the project counts as changed, and image resources are decoded in the new session.
#[test]
fn changing_the_mesh_keeps_the_bake_setup_and_marks_the_project_changed() {
let mut s = plane_session();
let plane = s.mesh.as_ref().clone();
let high = temp_file("change_high.obj", &obj(&plane, 0.002, f32::MAX, [1.0; 3]));
execute(&mut s, "bake.highPoly.add", &json!({ "path": high })).unwrap();
execute(&mut s, "bake.skew.set", &json!({ "value": 1.0 })).unwrap();
// 1x1 PNG as an image resource.
let png = [
0x89, 0x50, 0x4e, 0x47, 0x0d, 0x0a, 0x1a, 0x0a, 0x00, 0x00, 0x00, 0x0d, 0x49, 0x48, 0x44, 0x52, 0x00, 0x00, 0x00, 0x01, 0x00, 0x00, 0x00, 0x01, 0x08,
0x06, 0x00, 0x00, 0x00, 0x1f, 0x15, 0xc4, 0x89, 0x00, 0x00, 0x00, 0x0d, 0x49, 0x44, 0x41, 0x54, 0x78, 0x9c, 0x63, 0xf8, 0xcf, 0xc0, 0xf0, 0x1f, 0x00,
0x05, 0x00, 0x01, 0xff, 0x89, 0x99, 0x3d, 0x1d, 0x00, 0x00, 0x00, 0x00, 0x49, 0x45, 0x4e, 0x44, 0xae, 0x42, 0x60, 0x82,
];
s.import_resource_bytes("dot.png", png.to_vec()).unwrap();
s.modified = false;
let mesh_id = s.mesh_id;
let mut low = String::new();
for p in &plane.positions {
low += &format!("v {} {} {}\n", p.x, p.y, p.z);
}
for uv in &plane.uvs {
low += &format!("vt {} {}\n", uv.x, 1.0 - uv.y);
}
for t in plane.indices.as_chunks::<3>().0 {
low += &format!("f {a}/{a} {b}/{b} {c}/{c}\n", a = t[0] + 1, b = t[1] + 1, c = t[2] + 1);
}
let low = temp_file("change_low.obj", &low);
execute(&mut s, "file.changeMesh", &json!({ "path": low })).unwrap();
assert_ne!(s.mesh_id, mesh_id, "the session is on a new mesh");
assert_eq!(s.bake_meshes.high.len(), 1, "the high poly stays");
assert!(s.doc.bake_paint.keys().any(|(_, target)| *target == texturecraft_engine::core::BakePaintTarget::Skew), "the skew map stays");
assert!(s.modified, "the project differs from the saved one");
assert_eq!(s.images.len(), 1, "image resources are decoded in the new session");
}
+132
View File
@@ -0,0 +1,132 @@
//! Generator inputs that read an anchor point or an image, through engine commands.
use serde_json::{Value, json};
use std::sync::Arc;
use texturecraft_engine::core::{BakedMap, Channel, EffectKind, Source};
use texturecraft_engine::geom::primitives;
use texturecraft_engine::{Session, execute};
/// The texture set's texels per side.
const RESOLUTION: u32 = 256;
fn session() -> Session {
let mut session = Session::new_project("t", primitives::sphere(1.0, 48, 24), "builtin:sphere", None, RESOLUTION).unwrap();
session.viewport = texturecraft_engine::geom::glam::Vec2::new(400.0, 400.0);
session.camera.yaw = 0.0;
session.camera.pitch = 0.0;
session.update();
session
}
/// Composited value of `channel` under the viewport center.
fn center(session: &mut Session, channel: Channel) -> [f32; 3] {
session.update();
let hit = session.pick(session.viewport * 0.5, session.viewport).unwrap();
let texels = RESOLUTION as f32;
session.caches[0].composite.value(channel, (hit.uv.x * texels) as u32, (hit.uv.y * texels) as u32)
}
fn id(value: Value, key: &str) -> u64 {
value[key].as_u64().unwrap()
}
/// A low fill (height 0.8) with an anchor, then a white fill whose black mask holds an AO generator reading it: (anchor, low layer, generator).
fn anchored_generator(session: &mut Session) -> (u64, u64, u64) {
let low = id(execute(session, "layer.add.fill", &json!({"height": 0.8})).unwrap(), "layer");
let anchor = id(execute(session, "effect.add.anchor", &json!({"name": "Height"})).unwrap(), "effect");
execute(session, "layer.add.fill", &json!({"color": [1.0, 1.0, 1.0]})).unwrap();
execute(session, "mask.add.black", &Value::Null).unwrap();
let generator = id(execute(session, "effect.add.generator", &json!({"generator": "ambientOcclusion", "level": 0.5, "softness": 0.5})).unwrap(), "effect");
execute(session, "effect.set", &json!({"effect": generator, "input": "ambientOcclusion", "inputAnchor": anchor, "anchorChannel": "height"})).unwrap();
(anchor, low, generator)
}
#[test]
fn a_generator_input_reads_the_anchor_points_value() {
let mut session = session();
anchored_generator(&mut session);
// The low fill's gray, then white through the mask: an occlusion of 0.8 masks most of it, the channel default (0) none
let base = center(&mut session, Channel::BaseColor)[0];
assert!(base > 0.9, "the generator reads the anchor's height, not the default: {base}");
}
#[test]
fn a_generator_reading_an_anchor_cannot_be_pasted_below_it() {
let mut session = session();
let (_, low, generator) = anchored_generator(&mut session);
execute(&mut session, "effect.copy", &json!({"effect": generator})).unwrap();
let pasted = execute(&mut session, "effect.paste", &json!({"layer": low, "target": "mask"}));
assert!(pasted.is_err(), "the anchor point is on that layer, not below it");
}
#[test]
fn removing_unused_resources_keeps_an_image_read_by_a_generator_input() {
let mut session = session();
let image = image::RgbaImage::from_pixel(4, 4, image::Rgba([128, 128, 128, 255]));
let mut bytes = Vec::new();
image.write_to(&mut std::io::Cursor::new(&mut bytes), image::ImageFormat::Png).unwrap();
let name = session.import_resource_bytes("occlusion.png", bytes).unwrap();
execute(&mut session, "layer.add.fill", &Value::Null).unwrap();
execute(&mut session, "mask.add.black", &Value::Null).unwrap();
let generator = id(execute(&mut session, "effect.add.generator", &json!({"generator": "dirt"})).unwrap(), "effect");
execute(&mut session, "effect.set", &json!({"effect": generator, "input": "ambientOcclusion", "inputImage": name})).unwrap();
execute(&mut session, "file.removeUnused", &Value::Null).unwrap();
assert!(session.doc.resources.contains_key(&name), "the image is still read by the generator input");
}
#[test]
fn removing_unused_resources_keeps_an_image_read_by_a_content_effect() {
let mut session = session();
let image = image::RgbaImage::from_pixel(4, 4, image::Rgba([128, 128, 128, 255]));
let mut bytes = Vec::new();
image.write_to(&mut std::io::Cursor::new(&mut bytes), image::ImageFormat::Png).unwrap();
let name = session.import_resource_bytes("content.png", bytes).unwrap();
execute(&mut session, "layer.add.fill", &Value::Null).unwrap();
let effect = id(execute(&mut session, "effect.add.fill", &json!({"target": "content"})).unwrap(), "effect");
execute(&mut session, "layer.fill.set", &json!({"effect": effect, "channel": "baseColor", "image": name})).unwrap();
execute(&mut session, "file.removeUnused", &Value::Null).unwrap();
assert!(session.doc.resources.contains_key(&name), "the content effect still reads the image");
}
#[test]
fn generator_input_rejects_a_resource_that_is_not_an_image() {
let mut session = session();
session.doc.resources.insert("linked.mcmat".into(), Arc::new(vec![1, 2, 3]));
execute(&mut session, "layer.add.fill", &Value::Null).unwrap();
execute(&mut session, "mask.add.black", &Value::Null).unwrap();
let generator = id(execute(&mut session, "effect.add.generator", &json!({"generator": "dirt"})).unwrap(), "effect");
let result = execute(&mut session, "effect.set", &json!({"effect": generator, "input": "ambientOcclusion", "inputImage": "linked.mcmat"}));
assert!(result.is_err(), "a package resource has no image pixels for the generator to sample");
}
#[test]
fn importing_a_missing_generator_input_invalidates_the_composite() {
let mut session = session();
execute(&mut session, "layer.add.fill", &json!({"color": [1.0, 1.0, 1.0]})).unwrap();
execute(&mut session, "mask.add.black", &Value::Null).unwrap();
let effect = id(execute(&mut session, "effect.add.generator", &json!({"generator": "ambientOcclusion"})).unwrap(), "effect");
session
.edit("Reference an absent image", |session| {
let effect = session.doc.project.effect_mut(texturecraft_engine::core::LayerId(effect)).unwrap();
let EffectKind::Generator(generator) = &mut effect.kind else { panic!("expected generator") };
generator.inputs.insert(BakedMap::AmbientOcclusion, Source::image("later.png"));
Ok(())
})
.unwrap();
let before = center(&mut session, Channel::BaseColor)[0];
let image = image::RgbaImage::from_pixel(4, 4, image::Rgba([0, 0, 0, 255]));
let mut bytes = Vec::new();
image.write_to(&mut std::io::Cursor::new(&mut bytes), image::ImageFormat::Png).unwrap();
session.import_resource_bytes("later.png", bytes).unwrap();
let after = center(&mut session, Channel::BaseColor)[0];
assert!((after - before).abs() > 0.2, "the new image must update the generator's composited mask: {before} -> {after}");
}
+1
View File
@@ -10,6 +10,7 @@ mod content_effects;
mod export_colour_space;
mod filter_swap;
mod filters;
mod generator_inputs;
mod high_poly_missed;
mod instances;
mod materialcraft_link;
+44 -6
View File
@@ -21,9 +21,14 @@ fn session() -> Session {
/// A `.mcmat` as MaterialCraft writes it: uniform maps, one float input `wear` cooked at `wear`.
fn mcmat(roughness: f32, wear: f32) -> Vec<u8> {
mcmat_version(roughness, wear, 1)
}
fn mcmat_version(roughness: f32, wear: f32, version: u32) -> Vec<u8> {
let source = if version == 2 { "source.sbs" } else { "source.mcraft" };
let gray = |v: f32| mesh_map_png(4, 1, &[v; 16]).unwrap();
let manifest = json!({
"format": "craft-material", "version": 1, "name": "Brick wall", "graph": "Brick_wall", "size": [4, 4],
"format": "craft-material", "version": version, "name": "Brick wall", "graph": "Brick_wall", "size": [4, 4],
"maps": [
{"usage": "baseColor", "file": "maps/baseColor.png", "colorSpace": "srgb"},
{"usage": "roughness", "file": "maps/roughness.png", "colorSpace": "linear"},
@@ -42,7 +47,7 @@ fn mcmat(roughness: f32, wear: f32) -> Vec<u8> {
{"identifier": "bentNormal", "kind": "color"}
],
"presets": [{"name": "Worn", "values": {"wear": {"t": "float", "v": 1.0}, "note": {"t": "text", "v": "x"}}}],
"source": "source.mcraft"
"source": source
});
let mut z = zip::ZipWriter::new(std::io::Cursor::new(Vec::new()));
let o = zip::write::SimpleFileOptions::default();
@@ -51,7 +56,7 @@ fn mcmat(roughness: f32, wear: f32) -> Vec<u8> {
("maps/baseColor.png", mesh_map_png(4, 3, &[0.5; 48]).unwrap()),
("maps/roughness.png", gray(roughness)),
("maps/ambientOcclusion.png", gray(1.0)),
("source.mcraft", b"package bytes".to_vec()),
(source, b"package bytes".to_vec()),
] {
z.start_file(name, o).unwrap();
z.write_all(&bytes).unwrap();
@@ -81,6 +86,24 @@ fn map_name(s: &Session, id: LayerId, c: Channel) -> String {
}
}
#[test]
fn version_two_preserves_the_sbs_source_for_future_cooks() {
let mut session = session();
let id = session.add_linked_material_bytes_at(&mcmat_version(0.25, 0.5, 2), Place::Selection).unwrap();
let linked = link(&session, id);
assert!(linked.package.ends_with(".sbs"));
let job = session.link_job(id, &serde_json::Map::new()).unwrap();
assert_eq!(job.source_ext, "sbs");
assert_eq!(job.graph.as_deref(), Some("Brick_wall"));
assert_eq!(job.package.as_slice(), b"package bytes");
let base = std::env::temp_dir().join(format!("texturecraft-sbs-source-{}", std::process::id()));
let saved = execute(&mut session, "material.link.saveSource", &json!({"layer": id.0, "path": base.to_str().unwrap()})).unwrap();
let path = saved["path"].as_str().unwrap();
assert!(path.ends_with(".sbs"));
assert_eq!(std::fs::read(path).unwrap(), b"package bytes");
let _ = std::fs::remove_file(path);
}
#[test]
fn imports_as_a_linked_fill_with_its_maps() {
let mut s = session();
@@ -199,7 +222,7 @@ fn cooks_through_materialcraft_cli_when_available() {
let dir = std::env::temp_dir().join(format!("tc-mc-link-{}", std::process::id()));
std::fs::create_dir_all(&dir).unwrap();
let pkg = dir.join("bricks.mcraft");
let ok = std::process::Command::new(&cli).args(["new", "bricks"]).arg(&pkg).args(["--size", "64"]).status().unwrap();
let ok = std::process::Command::new(&cli).args(["new", "pbr"]).arg(&pkg).args(["--size", "64"]).status().unwrap();
assert!(ok.success());
let exposed = dir.join("exposed.mcraft");
let ok = std::process::Command::new(&cli)
@@ -217,9 +240,24 @@ fn cooks_through_materialcraft_cli_when_available() {
assert_eq!(link(&s, id).size, 128, "cooked at the texture set's resolution");
assert!(link(&s, id).params.iter().any(|p| p.id == "wear"));
execute(&mut s, "material.link.set", &json!({"layer": id.0, "id": "wear", "value": 0.8})).unwrap();
assert_eq!(link(&s, id).params.iter().find(|p| p.id == "wear").unwrap().value, json!({"t": "float", "v": 0.8}));
let out = dir.join("back.mcraft");
let wear = link(&s, id).params.iter().find(|p| p.id == "wear").unwrap().value["v"].as_f64().unwrap();
assert!((wear - 0.8).abs() < 1e-6);
let out = dir.join("back.sbs");
execute(&mut s, "material.link.saveSource", &json!({"layer": id.0, "path": out.to_str().unwrap()})).unwrap();
assert!(std::fs::metadata(&out).unwrap().len() > 0);
// The portable material can name a graph other than the first in the embedded source.
let multi = dir.join("multi.mcraft");
let ok = std::process::Command::new(&cli).arg("run").arg(&exposed).arg("graph.duplicate").arg("{}").arg("-o").arg(&multi).status().unwrap();
assert!(ok.success());
let portable = dir.join("second.mcmat");
let params = json!({"graph": 1, "size": 64, "path": portable.to_str().unwrap()});
let ok = std::process::Command::new(&cli).arg("run").arg(&multi).arg("file.exportMaterial").arg(params.to_string()).status().unwrap();
assert!(ok.success());
let second = s.add_linked_material_bytes_at(&std::fs::read(&portable).unwrap(), Place::Selection).unwrap();
let expected_graph = link(&s, second).graph;
let job = s.link_job(second, &serde_json::Map::new()).unwrap();
let result = texturecraft_engine::formats::mcmat::read_mcmat(&job.run().unwrap()).unwrap();
assert_eq!(result.manifest.graph, expected_graph);
let _ = std::fs::remove_dir_all(&dir);
}
+66
View File
@@ -586,6 +586,72 @@ fn curvature_generators_take_a_mode_and_detail_sizes() {
assert_eq!(execute(&mut state, "project.inspect", &Value::Null).unwrap().to_string(), inspect, "failed commands leave the project unchanged");
}
#[test]
fn generators_take_blur_balance_and_contrast() {
let mut state = session();
execute(&mut state, "layer.add.fill", &json!({})).unwrap();
execute(&mut state, "mask.add.black", &Value::Null).unwrap();
let added = execute(&mut state, "effect.add.generator", &json!({"generator": "dirt", "blur": 0.25})).unwrap();
let effect = added["effect"].clone();
execute(&mut state, "effect.set", &json!({"effect": effect, "balance": 0.75, "contrast": 2.0})).unwrap();
let inspect = execute(&mut state, "project.inspect", &Value::Null).unwrap().to_string();
assert!(inspect.contains(r#""blur":0.25"#) && inspect.contains(r#""balance":0.75"#), "{inspect}");
assert!(inspect.contains(r#""contrast":1.0"#), "contrast is clamped to 0..1: {inspect}");
execute(&mut state, "effect.set", &json!({"effect": effect, "resolution": "custom", "customResolution": 512, "resolutionFactor": -9})).unwrap();
let inspect = execute(&mut state, "project.inspect", &Value::Null).unwrap().to_string();
assert!(inspect.contains(r#""resolution":{"custom":512,"factor":-3,"mode":"Custom"}"#), "the factor is clamped to 1/8: {inspect}");
assert!(execute(&mut state, "effect.set", &json!({"effect": effect, "resolution": "huge"})).is_err(), "unknown resolutions are rejected");
}
#[test]
fn a_generator_input_reads_a_uniform_value_or_its_mesh_map_again() {
let mut state = session();
execute(&mut state, "layer.add.fill", &json!({})).unwrap();
execute(&mut state, "mask.add.black", &Value::Null).unwrap();
let effect = execute(&mut state, "effect.add.generator", &json!({"generator": "dirt"})).unwrap()["effect"].clone();
execute(&mut state, "effect.set", &json!({"effect": effect, "input": "ambientOcclusion", "inputValue": 0.25})).unwrap();
let inspect = execute(&mut state, "project.inspect", &Value::Null).unwrap().to_string();
assert!(inspect.contains(r#""inputs":{"ambientOcclusion":{"uniform":[0.25,0.25,0.25]}}"#), "{inspect}");
let wrong_input = execute(&mut state, "effect.set", &json!({"effect": effect, "input": "curvature", "inputValue": 0.5}));
assert!(wrong_input.is_err(), "dirt reads ambient occlusion, not curvature");
let missing_image = execute(&mut state, "effect.set", &json!({"effect": effect, "input": "ambientOcclusion", "inputImage": "nothing.png"}));
assert!(missing_image.is_err(), "the image must be a resource of the project");
let two_sources = execute(&mut state, "effect.set", &json!({"effect": effect, "input": "ambientOcclusion", "inputValue": 0.5, "inputBaked": true}));
assert!(two_sources.is_err(), "an input takes one source");
execute(&mut state, "effect.set", &json!({"effect": effect, "input": "ambientOcclusion", "inputBaked": true})).unwrap();
let inspect = execute(&mut state, "project.inspect", &Value::Null).unwrap().to_string();
assert!(!inspect.contains(r#""inputs""#), "the mesh map is read again: {inspect}");
}
#[test]
fn changing_generator_kind_keeps_the_effect_identity_and_settings() {
let mut state = session();
execute(&mut state, "layer.add.fill", &json!({})).unwrap();
execute(&mut state, "mask.add.black", &Value::Null).unwrap();
let effect = execute(&mut state, "effect.add.generator", &json!({"generator": "dirt"})).unwrap()["effect"].as_u64().unwrap();
execute(&mut state, "effect.set", &json!({"effect": effect, "name": "Keep me", "opacity": 0.4, "level": 0.2})).unwrap();
execute(&mut state, "effect.set", &json!({"effect": effect, "input": "ambientOcclusion", "inputValue": 0.25})).unwrap();
let later = execute(&mut state, "effect.add.generator", &json!({"generator": "position"})).unwrap()["effect"].as_u64().unwrap();
execute(&mut state, "effect.set", &json!({"effect": effect, "generator": "ambientOcclusion"})).unwrap();
let (owner, edited) = state.doc.project.effect(texturecraft_core::LayerId(effect)).unwrap();
assert!(matches!(&edited.kind, texturecraft_core::EffectKind::Generator(generator)
if generator.kind == texturecraft_core::GeneratorKind::AmbientOcclusion
&& generator.level == 0.2
&& matches!(generator.inputs.get(&texturecraft_core::BakedMap::AmbientOcclusion), Some(texturecraft_core::Source::Uniform([0.25, 0.25, 0.25])))));
assert_eq!(edited.name, "Keep me");
assert_eq!(edited.opacity, 0.4);
let layer = state.doc.project.layer(owner).unwrap();
let ids: Vec<u64> = layer.mask.as_ref().unwrap().effects.iter().map(|item| item.id.0).collect();
assert_eq!(ids, vec![effect, later]);
}
#[test]
fn unparseable_color_param_returns_error() {
let mut s = session();
+5
View File
@@ -9,6 +9,11 @@ license.workspace = true
workspace = true
[dependencies]
craft-materialx = { workspace = true }
craft-mesh = { workspace = true }
craft-mcmat = { workspace = true }
craft-tcraft = { workspace = true }
craft-zip = { workspace = true }
texturecraft-core = { workspace = true }
texturecraft-texel = { workspace = true }
texturecraft-geom = { workspace = true }
+20 -123
View File
@@ -1,20 +1,7 @@
//! MaterialX documents for exported texture sets, written from the ASWF MaterialX specification
//! (version 1.39) and the OpenPBR Surface specification. Pure Rust: no MaterialX library is
//! linked, and nothing is read from any other application.
//! TextureCraft's MaterialX export adapter.
//!
//! [`write`] takes a material's name and the texture files an export produced, each tagged with
//! the OpenPBR input it feeds, and gives the text of a `.mtlx` file: an `open_pbr_surface` shader
//! whose inputs read `tiledimage` nodes, wrapped in a `surfacematerial`. The inputs are the ones
//! the built-in "OpenPBR (separate maps)" export preset writes ([`INPUTS`]); `height` becomes a
//! `displacement` shader on the material and `geometry_normal` goes through a `normalmap` node
//! (OpenGL, +Y up, which is what that node expects).
//!
//! Colour textures (base, fuzz and emission colour) are tagged with the colour space they were
//! exported in ([`colorspace_name`]); every data map is left untagged (linear). UDIM sets write the `<UDIM>` filename token MaterialX defines.
//! Texture file names are relative to the document.
use std::collections::HashSet;
use std::fmt::Write as _;
//! The shared `craft-materialx` crate owns the MaterialX document writer. This module maps the
//! built-in preset's map names and TextureCraft color spaces to that format-level API.
use texturecraft_texel::ColorSpace;
@@ -51,7 +38,6 @@ pub const INPUTS: &[(&str, Kind)] = &[
("height", Kind::Height),
];
/// The file-name prefix of the built-in OpenPBR preset's maps.
const PREFIX: &str = "$mesh_$textureSet_";
/// One exported texture: the OpenPBR input it feeds and the file (relative to the `.mtlx`).
@@ -59,14 +45,11 @@ const PREFIX: &str = "$mesh_$textureSet_";
pub struct Texture {
pub input: String,
pub file: String,
/// The MaterialX colour space of the file's values (`srgb_texture`, `lin_rec709`, ...);
/// used for colour inputs only, data maps are always linear.
/// The MaterialX colour space of the file's values; used for color inputs only.
pub colorspace: &'static str,
}
/// The MaterialX colour space of colour maps written in `space`. MaterialX 1.39 defines no
/// ACES2065-1 (AP0) space: it gets `lin_ap0_scene`, its name in later versions of the
/// specification, which 1.39 readers may not know.
/// The MaterialX colour space of colour maps written in `space`.
pub fn colorspace_name(space: ColorSpace) -> &'static str {
match space {
ColorSpace::Srgb => "srgb_texture",
@@ -76,116 +59,28 @@ pub fn colorspace_name(space: ColorSpace) -> &'static str {
}
}
/// The OpenPBR input a preset map's file template feeds (`$mesh_$textureSet_base_color` →
/// `base_color`), or None for templates this module has no place for.
/// The OpenPBR input a preset map's file template feeds, or None for unsupported templates.
pub fn input_of_template(template: &str) -> Option<&'static str> {
let suffix = template.strip_prefix(PREFIX)?;
INPUTS.iter().find(|(n, _)| *n == suffix).map(|(n, _)| *n)
}
fn kind_of(input: &str) -> Option<Kind> {
INPUTS.iter().find(|(n, _)| *n == input).map(|(_, k)| *k)
INPUTS.iter().find(|(name, _)| *name == suffix).map(|(name, _)| *name)
}
/// A MaterialX name: letters, digits and underscores, not starting with a digit.
pub fn node_name(s: &str) -> String {
let mut out: String = s.chars().map(|c| if c.is_ascii_alphanumeric() || c == '_' { c } else { '_' }).collect();
pub fn node_name(name: &str) -> String {
let mut out: String = name.chars().map(|c| if c.is_ascii_alphanumeric() || c == '_' { c } else { '_' }).collect();
if out.is_empty() || out.starts_with(|c: char| c.is_ascii_digit()) {
out.insert(0, '_');
}
out
}
fn esc(s: &str) -> String {
let mut out = String::with_capacity(s.len());
for c in s.chars() {
match c {
'&' => out.push_str("&amp;"),
'<' => out.push_str("&lt;"),
'>' => out.push_str("&gt;"),
'"' => out.push_str("&quot;"),
'\'' => out.push_str("&apos;"),
c if c.is_control() => out.push(' '),
c => out.push(c),
}
}
out
}
fn image_name(input: &str) -> String {
format!("image_{}", node_name(input))
}
/// The text of a MaterialX document for `name` with the given textures. `physical_size_cm` goes
/// into the material's `doc` attribute. Inputs this module has no place for are skipped, and so
/// are repeats of one input (the first wins).
/// The text of a MaterialX OpenPBR document for `name` and the given texture files.
pub fn write(name: &str, textures: &[Texture], physical_size_cm: Option<[f32; 2]>) -> String {
let base = node_name(name);
let mut seen = HashSet::new();
let tex: Vec<(&Texture, Kind)> = textures.iter().filter_map(|t| kind_of(&t.input).map(|k| (t, k))).filter(|(t, _)| seen.insert(t.input.as_str())).collect();
let has = |i: &str| tex.iter().any(|(t, _)| t.input == i);
let mut x = String::new();
let _ = writeln!(x, "<?xml version=\"1.0\"?>");
let _ = writeln!(x, "<materialx version=\"1.39\" colorspace=\"lin_rec709\">");
let shader = format!("OPBR_{base}");
let _ = writeln!(x, " <open_pbr_surface name=\"{}\" type=\"surfaceshader\">", esc(&shader));
for (t, kind) in &tex {
let (ty, node) = match kind {
Kind::Color => ("color3", image_name(&t.input)),
Kind::Float => ("float", image_name(&t.input)),
Kind::Normal => ("vector3", "normalmap".to_owned()),
Kind::Height => continue,
};
let _ = writeln!(x, " <input name=\"{}\" type=\"{ty}\" nodename=\"{node}\" />", t.input);
}
if has("emission_color") {
let _ = writeln!(x, " <input name=\"emission_luminance\" type=\"float\" value=\"1\" />");
}
let _ = writeln!(x, " </open_pbr_surface>");
for (t, kind) in &tex {
let (ty, space) = match kind {
Kind::Color => ("color3", Some(t.colorspace)),
Kind::Normal => ("vector3", None),
Kind::Float | Kind::Height => ("float", None),
};
let node = image_name(&t.input);
let _ = writeln!(x, " <tiledimage name=\"{node}\" type=\"{ty}\">");
match space {
Some(space) => {
let _ = writeln!(x, " <input name=\"file\" type=\"filename\" value=\"{}\" colorspace=\"{space}\" />", esc(&t.file));
}
None => {
let _ = writeln!(x, " <input name=\"file\" type=\"filename\" value=\"{}\" />", esc(&t.file));
}
}
let _ = writeln!(x, " </tiledimage>");
}
if has("geometry_normal") {
let _ = writeln!(x, " <normalmap name=\"normalmap\" type=\"vector3\">");
let _ = writeln!(x, " <input name=\"in\" type=\"vector3\" nodename=\"{}\" />", image_name("geometry_normal"));
let _ = writeln!(x, " </normalmap>");
}
if has("height") {
let _ = writeln!(x, " <displacement name=\"DISP_{base}\" type=\"displacementshader\">");
let _ = writeln!(x, " <input name=\"displacement\" type=\"float\" nodename=\"{}\" />", image_name("height"));
let _ = writeln!(x, " <input name=\"scale\" type=\"float\" value=\"1\" />");
let _ = writeln!(x, " </displacement>");
}
let doc = match physical_size_cm {
Some([w, h]) if w.is_finite() && h.is_finite() => format!(" doc=\"Tiles every {w} x {h} cm\""),
_ => String::new(),
};
let _ = writeln!(x, " <surfacematerial name=\"{}\" type=\"material\"{doc}>", esc(&base));
let _ = writeln!(x, " <input name=\"surfaceshader\" type=\"surfaceshader\" nodename=\"{}\" />", esc(&shader));
if has("height") {
let _ = writeln!(x, " <input name=\"displacementshader\" type=\"displacementshader\" nodename=\"DISP_{base}\" />");
}
let _ = writeln!(x, " </surfacematerial>");
let _ = writeln!(x, "</materialx>");
x
let textures: Vec<craft_materialx::Texture> = textures
.iter()
.map(|texture| craft_materialx::Texture { input: texture.input.clone(), file: texture.file.clone(), colorspace: texture.colorspace.to_owned() })
.collect();
craft_materialx::write_open_pbr(name, &textures, physical_size_cm)
}
#[cfg(test)]
@@ -247,7 +142,7 @@ mod tests {
assert!(x.contains(want), "missing {want}\n{x}");
}
// Data textures carry no colour space, and height is not an OpenPBR input.
assert!(x.contains("value=\"stone_specular_roughness.png\" />"));
assert!(x.contains("value=\"stone_specular_roughness.png\"/>"));
assert!(!x.contains("name=\"height\""));
}
@@ -265,7 +160,7 @@ mod tests {
fn colour_inputs_carry_their_files_space_and_data_inputs_none() {
let lin = |input: &str, file: &str| Texture { colorspace: "lin_rec709", ..tex(input, file) };
let x = write("m", &[lin("base_color", "c.exr"), lin("specular_roughness", "r.exr")], None);
assert!(x.contains("value=\"c.exr\" colorspace=\"lin_rec709\"") && x.contains("value=\"r.exr\" />"), "{x}");
assert!(x.contains("value=\"c.exr\" colorspace=\"lin_rec709\"") && x.contains("value=\"r.exr\"/>"), "{x}");
}
#[test]
@@ -292,7 +187,9 @@ mod tests {
assert_eq!(node_name(""), "_");
let x = write("a<b>&\"c", &[tex("base_color", "x\"&<'>.<UDIM>.png")], Some([f32::NAN, 1.0]));
assert!(balanced(&x.replace("&lt;UDIM&gt;", "UDIM")), "{x}");
assert!(x.contains("value=\"x&quot;&amp;&lt;&apos;&gt;.&lt;UDIM&gt;.png\""));
let doc = craft_materialx::Document::parse(x.as_bytes()).unwrap();
let material = doc.read_material(None).unwrap();
assert!(material.inputs.iter().any(|(input, value)| input == "base_color" && value == &craft_materialx::Value::Image("x\"&<'>.<UDIM>.png".into())));
assert!(!x.contains("doc="), "a non-finite size is left out");
assert!(x.contains("OPBR_a_b___c"));
}
+90 -350
View File
@@ -1,41 +1,16 @@
//! Reading a MaterialX (`.mtlx`) material into TextureCraft's channels, written from the ASWF
//! MaterialX specification (1.39) and the OpenPBR Surface and glTF PBR node definitions. Pure
//! Rust: no MaterialX library is linked.
//! MaterialX material import adapted to TextureCraft's channel model.
//!
//! [`read_materialx`] finds a `surfacematerial`, follows its `surfaceshader` to an
//! `open_pbr_surface`, `standard_surface` or `gltf_pbr` node, and turns each input TextureCraft
//! has a channel for into a literal value or an image file:
//!
//! - a literal `value` becomes a constant (`color3` values tagged `srgb_texture` are converted
//! to linear; a colour given for a scalar channel is averaged);
//! - an input wired to a `tiledimage` or `image` node (directly or through a `nodegraph`
//! output) becomes that node's `file` (with `fileprefix` applied); `normalmap`, `convert` and
//! `constant` nodes in between are passed through;
//! - the material's `displacementshader` becomes the height channel;
//! - `uvtiling` of the first tiled image is returned as the UV tiling.
//!
//! Anything else (maths nodes, procedural patterns, other shaders) is skipped with a warning
//! rather than guessed at. Emission follows the specifications' defaults: OpenPBR emits nothing
//! unless `emission_luminance` is above 0, and `standard_surface` unless `emission` is.
//!
//! The reader takes untrusted bytes: the document size, nesting and element count are capped, a
//! wiring loop stops at a depth limit, and every failure is an error, never a panic.
//! XML parsing, nodegraph traversal and shader input resolution live in `craft-materialx`.
//! This module maps those format-level values to TextureCraft's channels and color handling.
use std::collections::HashMap;
use quick_xml::events::{BytesStart, Event};
use texturecraft_core::Channel;
use texturecraft_core::{Channel, ChannelKind};
use texturecraft_texel::srgb_to_linear;
use crate::{FormatError, Result, malformed};
const KIND: &str = "MaterialX document";
/// Largest document read, in bytes.
pub const MAX_BYTES: usize = 16 << 20;
const MAX_DEPTH: usize = 64;
const MAX_ELEMENTS: usize = 200_000;
/// Longest chain of nodes followed from one shader input.
const MAX_HOPS: usize = 16;
pub const MAX_BYTES: usize = craft_materialx::MAX_BYTES;
/// What one channel is set from.
#[derive(Clone, Debug, PartialEq)]
@@ -58,259 +33,40 @@ pub struct Material {
pub warnings: Vec<String>,
}
// ---------------------------------------------------------------------------------------------
// XML.
#[derive(Default)]
struct El {
name: String,
attrs: Vec<(String, String)>,
children: Vec<El>,
fn channel(shader: craft_materialx::Shader, input: &str) -> Option<Channel> {
use craft_materialx::Shader::{GltfPbr, OpenPbr, StandardSurface};
Some(match (shader, input) {
(OpenPbr, "base_color") | (StandardSurface, "base_color") | (GltfPbr, "base_color") => Channel::BaseColor,
(OpenPbr, "base_metalness") | (StandardSurface, "metalness") | (GltfPbr, "metallic") => Channel::Metallic,
(OpenPbr, "specular_roughness") | (StandardSurface, "specular_roughness") | (GltfPbr, "roughness") => Channel::Roughness,
(OpenPbr, "geometry_normal") | (StandardSurface, "normal") | (GltfPbr, "normal") => Channel::Normal,
(OpenPbr, "geometry_opacity") | (StandardSurface, "opacity") | (GltfPbr, "alpha") => Channel::Opacity,
(OpenPbr, "emission_color") | (StandardSurface, "emission_color") | (GltfPbr, "emission") => Channel::Emissive,
(OpenPbr, "coat_weight") | (StandardSurface, "coat") | (GltfPbr, "clearcoat") => Channel::CoatWeight,
(OpenPbr, "coat_roughness") | (StandardSurface, "coat_roughness") | (GltfPbr, "clearcoat_roughness") => Channel::CoatRoughness,
(OpenPbr, "geometry_coat_normal") | (StandardSurface, "coat_normal") | (GltfPbr, "clearcoat_normal") => Channel::CoatNormal,
(OpenPbr, "fuzz_weight") | (StandardSurface, "sheen") => Channel::SheenWeight,
(OpenPbr, "fuzz_color") | (StandardSurface, "sheen_color") | (GltfPbr, "sheen_color") => Channel::SheenColor,
(OpenPbr, "fuzz_roughness") | (StandardSurface, "sheen_roughness") | (GltfPbr, "sheen_roughness") => Channel::SheenRoughness,
(OpenPbr, "specular_roughness_anisotropy") | (StandardSurface, "specular_anisotropy") => Channel::AnisotropyLevel,
(OpenPbr, "transmission_weight") | (StandardSurface, "transmission") | (GltfPbr, "transmission") => Channel::Transmission,
(OpenPbr, "subsurface_weight") | (StandardSurface, "subsurface") => Channel::ScatterWeight,
(GltfPbr, "occlusion") => Channel::AmbientOcclusion,
_ => return None,
})
}
impl El {
fn attr(&self, k: &str) -> Option<&str> {
self.attrs.iter().find(|(n, _)| n == k).map(|(_, v)| v.as_str())
fn constant(channel: Channel, values: &[f32], colorspace: Option<&str>) -> [f32; 3] {
let mut values = values.to_vec();
if let Some(space) = colorspace
&& (space.starts_with("srgb") || space.starts_with("g22") || space.starts_with("g18"))
&& values.len() >= 3
{
values.iter_mut().take(3).for_each(|c| *c = srgb_to_linear(*c));
}
/// The child element named `name` (the `name` attribute: inputs and nodes are looked up by it).
fn input(&self, name: &str) -> Option<&El> {
self.children.iter().find(|c| c.attr("name") == Some(name))
}
}
fn element(e: &BytesStart) -> El {
let text = |b: &[u8]| String::from_utf8_lossy(b).into_owned();
let attrs = e
.attributes()
.with_checks(false)
.flatten()
.map(|a| {
(text(a.key.local_name().as_ref()), a.normalized_value(quick_xml::XmlVersion::Implicit1_0).map_or_else(|_| text(&a.value), |v| v.into_owned()))
})
.collect();
El { name: text(e.local_name().as_ref()), attrs, children: Vec::new() }
}
fn parse_xml(bytes: &[u8]) -> Result<El> {
let mut reader = quick_xml::Reader::from_reader(bytes);
let mut stack = vec![El::default()];
let mut count = 0usize;
loop {
let event = reader.read_event().map_err(|e| malformed(KIND, e))?;
if matches!(event, Event::Start(_) | Event::Empty(_)) {
count += 1;
if count > MAX_ELEMENTS || stack.len() > MAX_DEPTH {
return Err(FormatError::TooLarge(format!(
"the MaterialX document has more than {MAX_ELEMENTS} elements or is nested deeper than {MAX_DEPTH}"
)));
}
}
match event {
Event::Start(e) => stack.push(element(&e)),
Event::Empty(e) => {
if let Some(parent) = stack.last_mut() {
parent.children.push(element(&e));
}
}
Event::End(_) => {
let el = stack.pop().filter(|_| !stack.is_empty()).ok_or_else(|| malformed(KIND, "unbalanced end tag"))?;
if let Some(parent) = stack.last_mut() {
parent.children.push(el);
}
}
Event::Eof => break,
_ => {}
}
}
match (stack.pop(), stack.is_empty()) {
(Some(root), true) => Ok(root),
_ => Err(malformed(KIND, "unclosed elements at the end of the document")),
}
}
// ---------------------------------------------------------------------------------------------
// Shader input tables: (shader input, channel). `kind` says how to read the value.
#[derive(Clone, Copy, PartialEq)]
enum Shader {
OpenPbr,
Standard,
Gltf,
}
const OPEN_PBR: &[(&str, Channel)] = &[
("base_color", Channel::BaseColor),
("base_metalness", Channel::Metallic),
("specular_roughness", Channel::Roughness),
("geometry_normal", Channel::Normal),
("geometry_opacity", Channel::Opacity),
("emission_color", Channel::Emissive),
("coat_weight", Channel::CoatWeight),
("coat_roughness", Channel::CoatRoughness),
("geometry_coat_normal", Channel::CoatNormal),
("fuzz_weight", Channel::SheenWeight),
("fuzz_color", Channel::SheenColor),
("fuzz_roughness", Channel::SheenRoughness),
("specular_roughness_anisotropy", Channel::AnisotropyLevel),
("transmission_weight", Channel::Transmission),
("subsurface_weight", Channel::ScatterWeight),
];
const STANDARD: &[(&str, Channel)] = &[
("base_color", Channel::BaseColor),
("metalness", Channel::Metallic),
("specular_roughness", Channel::Roughness),
("normal", Channel::Normal),
("opacity", Channel::Opacity),
("emission_color", Channel::Emissive),
("coat", Channel::CoatWeight),
("coat_roughness", Channel::CoatRoughness),
("coat_normal", Channel::CoatNormal),
("sheen", Channel::SheenWeight),
("sheen_color", Channel::SheenColor),
("sheen_roughness", Channel::SheenRoughness),
("specular_anisotropy", Channel::AnisotropyLevel),
("transmission", Channel::Transmission),
("subsurface", Channel::ScatterWeight),
];
const GLTF: &[(&str, Channel)] = &[
("base_color", Channel::BaseColor),
("metallic", Channel::Metallic),
("roughness", Channel::Roughness),
("normal", Channel::Normal),
("alpha", Channel::Opacity),
("emission", Channel::Emissive),
("occlusion", Channel::AmbientOcclusion),
("clearcoat", Channel::CoatWeight),
("clearcoat_roughness", Channel::CoatRoughness),
("clearcoat_normal", Channel::CoatNormal),
("sheen_color", Channel::SheenColor),
("sheen_roughness", Channel::SheenRoughness),
("transmission", Channel::Transmission),
];
// ---------------------------------------------------------------------------------------------
// Resolving what feeds an input.
struct Doc<'a> {
root: &'a El,
/// Every node by name: the document's own, and each nodegraph's (qualified `graph/node`).
nodes: HashMap<String, &'a El>,
/// Each nodegraph's outputs: `graph/output` to the node name inside (qualified).
outputs: HashMap<String, String>,
tiling: Option<[f32; 2]>,
warnings: Vec<String>,
}
enum Found {
Constant(Vec<f32>),
Image(String),
None,
}
fn numbers(text: &str) -> Option<Vec<f32>> {
let v: Option<Vec<f32>> = text.split(',').map(|p| p.trim().parse::<f32>().ok().filter(|f| f.is_finite())).collect();
v.filter(|v| !v.is_empty() && v.len() <= 4)
}
impl<'a> Doc<'a> {
fn new(root: &'a El) -> Doc<'a> {
let mut nodes = HashMap::new();
let mut outputs = HashMap::new();
for c in &root.children {
match (c.name.as_str(), c.attr("name")) {
("nodegraph", Some(g)) => {
for n in &c.children {
let Some(name) = n.attr("name") else { continue };
if n.name == "output" {
if let Some(from) = n.attr("nodename") {
outputs.insert(format!("{g}/{name}"), format!("{g}/{from}"));
}
} else {
nodes.insert(format!("{g}/{name}"), n);
}
}
}
(_, Some(name)) => {
nodes.insert(name.to_owned(), c);
}
_ => {}
}
}
Doc { root, nodes, outputs, tiling: None, warnings: Vec::new() }
}
/// What `input` (an `<input>` element of a node) resolves to; `scope` is the nodegraph the
/// node lives in, if any.
fn resolve(&mut self, input: &El, scope: Option<&str>, hops: usize) -> Found {
if hops > MAX_HOPS {
self.warnings.push("a node chain is longer than 16 nodes (or loops); skipped".into());
return Found::None;
}
if let Some(v) = input.attr("value") {
return numbers(v).map_or(Found::None, |n| Found::Constant(self.tag(input, n)));
}
let target = match (input.attr("nodegraph"), input.attr("output"), input.attr("nodename")) {
(Some(g), out, _) => {
let out = out.map(str::to_owned).or_else(|| self.outputs.keys().find_map(|k| k.strip_prefix(&format!("{g}/")).map(str::to_owned)));
out.and_then(|o| self.outputs.get(&format!("{g}/{o}")).cloned())
}
(None, _, Some(n)) => {
Some(scope.map_or_else(|| n.to_owned(), |g| format!("{g}/{n}"))).filter(|q| self.nodes.contains_key(q)).or_else(|| Some(n.to_owned()))
}
_ => None,
};
let Some(node) = target.as_deref().and_then(|t| self.nodes.get(t).copied()) else { return Found::None };
let scope = target.as_deref().and_then(|t| t.split_once('/')).map(|(g, _)| g.to_owned());
let scope = scope.as_deref();
match node.name.as_str() {
"tiledimage" | "image" => {
let Some(file) = node.input("file").and_then(|f| f.attr("value")) else {
self.warnings.push(format!("image node {:?} has no file", node.attr("name").unwrap_or("")));
return Found::None;
};
let prefix =
[node.input("file").and_then(|f| f.attr("fileprefix")), node.attr("fileprefix"), self.root.attr("fileprefix")].into_iter().flatten().next();
if self.tiling.is_none()
&& let Some(t) =
node.input("uvtiling").and_then(|t| t.attr("value")).and_then(numbers).filter(|t| t.len() == 2 && t.iter().all(|v| *v > 0.0))
{
// The range a fill's UV scale accepts (`layer.fill.projection`).
self.tiling = Some([t[0].clamp(0.001, 1000.0), t[1].clamp(0.001, 1000.0)]);
}
Found::Image(format!("{}{file}", prefix.unwrap_or("")))
}
"normalmap" | "convert" => match node.input("in") {
Some(i) => self.resolve(i, scope, hops + 1),
None => Found::None,
},
"constant" => match node.input("value") {
Some(v) => self.resolve(v, scope, hops + 1),
None => Found::None,
},
other => {
self.warnings.push(format!("a {other} node ({:?}) is not supported; its input was skipped", node.attr("name").unwrap_or("")));
Found::None
}
}
}
/// Literal values tagged with an sRGB colour space are converted to linear.
fn tag(&self, input: &El, mut n: Vec<f32>) -> Vec<f32> {
let space = input.attr("colorspace").or_else(|| self.root.attr("colorspace")).unwrap_or("");
if input.attr("colorspace").is_some() && (space.starts_with("srgb") || space.starts_with("g22") || space.starts_with("g18")) && n.len() >= 3 {
n.iter_mut().take(3).for_each(|c| *c = srgb_to_linear(*c));
}
n
}
}
fn to_constant(channel: Channel, n: &[f32]) -> [f32; 3] {
match (channel.kind(), n) {
match (channel.kind(), values.as_slice()) {
(_, [a]) => [*a; 3],
(texturecraft_core::ChannelKind::Color, [r, g, b, ..]) => [*r, *g, *b],
(ChannelKind::Color, [r, g, b, ..]) => [*r, *g, *b],
(_, [r, g, b, ..]) => {
let mean = (r + g + b) / 3.0;
[mean; 3]
@@ -319,9 +75,11 @@ fn to_constant(channel: Channel, n: &[f32]) -> [f32; 3] {
}
}
/// The literal number of `input`, if it is one.
fn literal(shader: &El, name: &str) -> Option<f32> {
shader.input(name).and_then(|i| i.attr("value")).and_then(numbers).and_then(|n| n.first().copied())
fn app_value(channel: Channel, value: craft_materialx::Value) -> Value {
match value {
craft_materialx::Value::Constant { values, colorspace } => Value::Constant(constant(channel, &values, colorspace.as_deref())),
craft_materialx::Value::Image(file) => Value::Image(file),
}
}
/// Read the material called `material` (default: the first) from a `.mtlx` document.
@@ -330,79 +88,30 @@ pub fn read_materialx(bytes: &[u8], material: Option<&str>) -> Result<Material>
}
fn read_inner(bytes: &[u8], material: Option<&str>) -> Result<Material> {
if bytes.len() > MAX_BYTES {
return Err(FormatError::TooLarge(format!("the MaterialX document is over {} MiB", MAX_BYTES >> 20)));
}
let top = parse_xml(bytes)?;
let root = top.children.iter().find(|c| c.name == "materialx").ok_or_else(|| malformed(KIND, "no <materialx> element"))?;
let mut doc = Doc::new(root);
let materials: Vec<&El> = root.children.iter().filter(|c| c.name == "surfacematerial").collect();
let mat = match material {
Some(name) => materials
.iter()
.copied()
.find(|m| m.attr("name") == Some(name))
.ok_or_else(|| FormatError::Invalid(format!("no material named {name:?} (found: {})", names(&materials))))?,
None => materials.first().copied().ok_or_else(|| FormatError::Unsupported("the document has no surfacematerial".into()))?,
};
let mut out = Material { name: mat.attr("name").unwrap_or("Material").to_owned(), channels: Vec::new(), uv_tiling: [1.0, 1.0], warnings: Vec::new() };
let shader = mat
.input("surfaceshader")
.and_then(|i| i.attr("nodename"))
.and_then(|n| doc.nodes.get(n).copied())
.ok_or_else(|| malformed(KIND, "the material has no surface shader"))?;
let (kind, table) = match shader.name.as_str() {
"open_pbr_surface" => (Shader::OpenPbr, OPEN_PBR),
"standard_surface" => (Shader::Standard, STANDARD),
"gltf_pbr" => (Shader::Gltf, GLTF),
other => return Err(FormatError::Unsupported(format!("the surface shader is a {other}; open_pbr_surface, standard_surface and gltf_pbr are read"))),
};
// Emission is off by default in OpenPBR and standard_surface.
let emits = match kind {
Shader::OpenPbr => {
shader.input("emission_luminance").is_some_and(|i| i.attr("value").is_none() || literal(shader, "emission_luminance").is_some_and(|v| v > 0.0))
}
Shader::Standard => shader.input("emission").is_some_and(|i| i.attr("value").is_none() || literal(shader, "emission").is_some_and(|v| v > 0.0)),
Shader::Gltf => true,
};
let weight = match kind {
Shader::OpenPbr => literal(shader, "base_weight"),
Shader::Standard => literal(shader, "base"),
Shader::Gltf => None,
};
if weight.is_some_and(|w| (w - 1.0).abs() > 1e-6) {
doc.warnings.push("the base weight isn't 1; it was ignored".into());
}
for &(input, channel) in table {
let Some(el) = shader.input(input) else { continue };
if channel == Channel::Emissive && !emits && kind != Shader::Gltf {
doc.warnings.push(format!("{input} was skipped: the shader's emission is 0"));
continue;
}
match doc.resolve(el, None, 0) {
Found::Constant(n) => out.channels.push((channel, Value::Constant(to_constant(channel, &n)))),
Found::Image(f) => out.channels.push((channel, Value::Image(f))),
Found::None => {}
let document = craft_materialx::Document::parse(bytes).map_err(map_error)?;
let shared = document.read_material(material).map_err(map_error)?;
let mut channels = Vec::new();
for (input, value) in shared.inputs {
if let Some(channel) = channel(shared.shader, &input) {
channels.push((channel, app_value(channel, value)));
}
}
// The displacement shader's `displacement` input is the height.
if let Some(d) = mat.input("displacementshader").and_then(|i| i.attr("nodename")).and_then(|n| doc.nodes.get(n).copied())
&& let Some(i) = d.input("displacement")
{
match doc.resolve(i, None, 0) {
Found::Constant(n) => out.channels.push((Channel::Height, Value::Constant(to_constant(Channel::Height, &n)))),
Found::Image(f) => out.channels.push((Channel::Height, Value::Image(f))),
Found::None => {}
}
if let Some(value) = shared.displacement {
channels.push((Channel::Height, app_value(Channel::Height, value)));
}
out.uv_tiling = doc.tiling.unwrap_or([1.0, 1.0]);
out.warnings = doc.warnings;
Ok(out)
Ok(Material { name: shared.name, channels, uv_tiling: shared.uv_tiling, warnings: shared.warnings })
}
fn names(materials: &[&El]) -> String {
let n: Vec<&str> = materials.iter().filter_map(|m| m.attr("name")).collect();
if n.is_empty() { "none".into() } else { n.join(", ") }
fn map_error(error: craft_materialx::Error) -> FormatError {
use craft_materialx::Error;
match error {
Error::Xml(xml) if xml.is_limit() => FormatError::TooLarge(xml.to_string()),
Error::MissingMaterial(name) => FormatError::Invalid(format!("no material named {name:?}")),
Error::Unsupported(message) => FormatError::Unsupported(message),
Error::Malformed(message) => malformed(KIND, message),
Error::Root => malformed(KIND, "no <materialx> element"),
Error::Xml(other) => malformed(KIND, other),
}
}
#[cfg(test)]
@@ -439,6 +148,19 @@ mod tests {
m.channels.iter().find(|(ch, _)| *ch == c).map(|(_, v)| v)
}
#[test]
fn displacement_only_image_supplies_uv_tiling() {
let xml = br#"<materialx>
<open_pbr_surface name="S"><input name="base_color" value="0.3,0.4,0.5"/></open_pbr_surface>
<tiledimage name="H"><input name="file" value="height.png"/><input name="uvtiling" value="4,2"/></tiledimage>
<displacement name="D"><input name="displacement" nodename="H"/></displacement>
<surfacematerial name="M"><input name="surfaceshader" nodename="S"/><input name="displacementshader" nodename="D"/></surfacematerial>
</materialx>"#;
let material = read_materialx(xml, None).unwrap();
assert_eq!(get(&material, Channel::Height), Some(&Value::Image("height.png".into())));
assert_eq!(material.uv_tiling, [4.0, 2.0]);
}
#[test]
fn open_pbr_inputs_become_channels() {
let m = read_materialx(OPENPBR.as_bytes(), None).unwrap();
@@ -456,6 +178,24 @@ mod tests {
assert_eq!(read_materialx(extreme.as_bytes(), None).unwrap().uv_tiling, [1000.0, 0.001], "clamped like a fill's UV scale");
}
#[test]
fn nodegraph_input_without_output_uses_the_first_output() {
let xml = r#"<materialx version="1.38">
<nodegraph name="NG">
<tiledimage name="a" type="color3"><input name="file" type="filename" value="first.png" /></tiledimage>
<tiledimage name="b" type="color3"><input name="file" type="filename" value="second.png" /></tiledimage>
<output name="o1" type="color3" nodename="a" />
<output name="o2" type="color3" nodename="b" />
</nodegraph>
<standard_surface name="S" type="surfaceshader"><input name="base_color" type="color3" nodegraph="NG" /></standard_surface>
<surfacematerial name="M" type="material"><input name="surfaceshader" type="surfaceshader" nodename="S" /></surfacematerial>
</materialx>"#;
for _ in 0..50 {
let material = read_materialx(xml.as_bytes(), None).unwrap();
assert_eq!(get(&material, Channel::BaseColor), Some(&Value::Image("first.png".into())));
}
}
#[test]
fn emission_is_off_unless_the_shader_emits() {
let x = OPENPBR.replace(r#"<input name="emission_luminance" type="float" value="2" />"#, "");
+82 -85
View File
@@ -1,11 +1,11 @@
//! MaterialCraft portable materials (`.mcmat`, read only): a zip with `material.json` (the
//! manifest: maps by usage, exposed parameters, image inputs, presets), `maps/<usage>.png`
//! (8-bit sRGB for color usages, 16-bit linear otherwise; OpenGL normals) and the source
//! `.mcraft` package. TextureCraft keeps its own reader (the apps share the format, not code).
//! (8-bit sRGB for color usages, 16-bit linear otherwise; OpenGL normals) and the
//! source package. The shared reader handles the portable container and manifest.
//!
//! Also the 16-bit PNG encoder that hands baked mesh maps to MaterialCraft as graph inputs.
use std::io::{Cursor, Read};
use std::io::Cursor;
use serde::Deserialize;
use texturecraft_core::{LinkParam, LinkPreset};
@@ -16,8 +16,7 @@ use crate::{FormatError, Result};
pub const MCMAT_EXT: &str = "mcmat";
/// MaterialCraft's package extension.
pub const MCRAFT_EXT: &str = "mcraft";
const FORMAT: &str = "craft-material";
const VERSION: u32 = 1;
const VERSION: u32 = 2;
/// Largest entry read (maps are at most 8192² × 16 bits, compressed).
const MAX_ENTRY: u64 = 512 << 20;
/// Most map entries one manifest may name (a material has at most nine usages).
@@ -70,68 +69,76 @@ fn malformed(msg: impl Into<String>) -> FormatError {
FormatError::Malformed { kind: KIND, msg: msg.into() }
}
fn read_entry(name: &str, entry: impl Read, total_bytes: &mut u64) -> Result<Vec<u8>> {
// Earlier maps remain live while the next entry is read
let remaining_bytes = MAX_TOTAL.saturating_sub(*total_bytes);
let entry_limit = MAX_ENTRY.min(remaining_bytes);
let mut bytes = Vec::new();
entry.take(entry_limit + 1).read_to_end(&mut bytes).map_err(|error| malformed(format!("{name}: {error}")))?;
if bytes.len() as u64 > MAX_ENTRY {
return Err(FormatError::TooLarge(name.to_string()));
fn shared_error(error: craft_mcmat::Error) -> FormatError {
match error {
craft_mcmat::Error::Version(version) => FormatError::Unsupported(format!("{KIND} version {version} (this version reads up to {VERSION})")),
craft_mcmat::Error::Limit(message) => malformed(message),
craft_mcmat::Error::Archive(ref archive) if archive.is_limit() => FormatError::TooLarge(error.to_string()),
other => malformed(other.to_string()),
}
let next_total = total_bytes.saturating_add(bytes.len() as u64);
if next_total > MAX_TOTAL {
return Err(FormatError::TooLarge(format!("{KIND} payload (over {MAX_TOTAL} bytes)")));
}
// Keep spare read capacity from accumulating across retained map entries
bytes.shrink_to_fit();
*total_bytes = next_total;
Ok(bytes)
}
/// Read `.mcmat` bytes.
/// Read `.mcmat` bytes within TextureCraft's existing per-entry and total payload limits.
pub fn read_mcmat(bytes: &[u8]) -> Result<PortableMaterial> {
let mut archive = zip::ZipArchive::new(Cursor::new(bytes)).map_err(|error| malformed(error.to_string()))?;
let mut total_bytes = 0u64;
let mut read = |name: &str| -> Result<Vec<u8>> {
let entry = archive.by_name(name).map_err(|_| malformed(format!("{name} is missing")))?;
read_entry(name, entry, &mut total_bytes)
let limits = craft_mcmat::Limits {
min_version: 0,
max_version: VERSION,
max_entries: 100_000,
max_maps: MAX_MAPS,
max_manifest_bytes: MAX_ENTRY,
max_entry_bytes: MAX_ENTRY,
max_total_bytes: MAX_TOTAL,
};
let manifest: Manifest = serde_json::from_slice(&read("material.json")?).map_err(|error| malformed(format!("material.json: {error}")))?;
if manifest.format != FORMAT {
return Err(malformed(format!("format `{}`", manifest.format)));
}
if manifest.version > VERSION {
return Err(FormatError::Unsupported(format!("{KIND} version {} (this version reads up to {VERSION})", manifest.version)));
}
if manifest.maps.len() > MAX_MAPS {
return Err(malformed(format!("{} maps, over the {MAX_MAPS} map limit", manifest.maps.len())));
}
let maps = manifest.maps.iter().map(|map| Ok((map.usage.clone(), read(&map.file)?))).collect::<Result<Vec<_>>>()?;
let source = read(&manifest.source)?;
let mut archive = craft_mcmat::Material::open(bytes, limits).map_err(shared_error)?;
// Consume the JSON values rather than cloning the entire untrusted manifest into a second tree.
let parameters = std::mem::take(&mut archive.manifest.parameters)
.into_iter()
.map(serde_json::from_value)
.collect::<std::result::Result<_, _>>()
.map_err(|e| malformed(format!("material.json: {e}")))?;
let inputs = std::mem::take(&mut archive.manifest.inputs)
.into_iter()
.map(serde_json::from_value)
.collect::<std::result::Result<_, _>>()
.map_err(|e| malformed(format!("material.json: {e}")))?;
let presets = std::mem::take(&mut archive.manifest.presets)
.into_iter()
.map(serde_json::from_value)
.collect::<std::result::Result<_, _>>()
.map_err(|e| malformed(format!("material.json: {e}")))?;
let shared = &archive.manifest;
let manifest = Manifest {
format: shared.format.clone(),
version: shared.version,
name: shared.name.clone(),
graph: shared.graph.clone(),
size: shared.size,
maps: shared.maps.iter().map(|m| MapEntry { usage: m.usage.clone(), file: m.file.clone() }).collect(),
parameters,
inputs,
presets,
source: shared.source.clone(),
};
let maps = manifest.maps.iter().map(|map| Ok((map.usage.clone(), archive.read(&map.file).map_err(shared_error)?))).collect::<Result<Vec<_>>>()?;
let source = archive.read_source().map_err(shared_error)?;
Ok(PortableMaterial { manifest, maps, source })
}
/// Whether `bytes` are a zip holding `entry` (`material.json`: a portable material,
/// `package.json`: a MaterialCraft package).
fn zip_has(bytes: &[u8], entry: &str) -> bool {
zip::ZipArchive::new(Cursor::new(bytes)).is_ok_and(|mut z| z.by_name(entry).is_ok())
}
/// Whether `bytes` contain a portable material manifest within the ZIP entry limit.
pub fn is_mcmat(bytes: &[u8]) -> bool {
zip_has(bytes, "material.json")
craft_mcmat::is_material(bytes, 100_000)
}
pub fn is_mcraft(bytes: &[u8]) -> bool {
zip_has(bytes, "package.json")
let Ok(mut archive) = craft_zip::Archive::open(bytes, craft_zip::Limits { max_entries: 100_000, max_total_bytes: 0 }) else { return false };
// A portable material may itself contain source.sbs, so it is not a source archive.
if archive.has_duplicate_names() || archive.contains("material.json") {
return false;
}
if archive.contains("package.json") {
return true;
}
(0..archive.len()).any(|i| archive.entry_name(i).ok().flatten().is_some_and(|name| !name.contains('/') && name.to_ascii_lowercase().ends_with(".sbs")))
}
/// A baked mesh map (`components` floats per texel, 0..1, rows top first) as a 16-bit PNG
@@ -161,13 +168,14 @@ mod tests {
/// A `.mcmat` as MaterialCraft writes it (see its `formats/src/material.rs`).
pub(crate) fn sample(version: u32) -> Vec<u8> {
let source = if version >= 2 { "source.sbs" } else { "source.mcraft" };
let manifest = serde_json::json!({
"format": "craft-material", "version": version, "name": "Brick wall", "graph": "Brick_wall", "size": [4, 4],
"maps": [{"usage": "baseColor", "file": "maps/baseColor.png", "colorSpace": "srgb"}],
"parameters": [{"id": "wear", "label": "Wear", "default": {"t": "float", "v": 0.5}, "min": 0.0, "max": 1.0, "value": {"t": "float", "v": 0.25}}],
"inputs": [{"identifier": "curvature", "kind": "gray"}],
"presets": [{"name": "Worn", "values": {"wear": {"t": "float", "v": 1.0}}}],
"source": "source.mcraft", "futureField": true
"source": source, "futureField": true
});
let mut z = zip::ZipWriter::new(Cursor::new(Vec::new()));
let o = zip::write::SimpleFileOptions::default();
@@ -175,7 +183,7 @@ mod tests {
z.write_all(manifest.to_string().as_bytes()).unwrap();
z.start_file("maps/baseColor.png", o).unwrap();
z.write_all(&mesh_map_png(4, 3, &[0.5; 48]).unwrap()).unwrap();
z.start_file("source.mcraft", o).unwrap();
z.start_file(source, o).unwrap();
z.write_all(b"pkg").unwrap();
z.finish().unwrap().into_inner()
}
@@ -195,15 +203,29 @@ mod tests {
assert_eq!(material.maps[0].0, "baseColor");
assert_eq!(crate::decode_image(&material.maps[0].1).unwrap().width, 4);
assert_eq!(material.source, b"pkg");
assert!(matches!(read_mcmat(&sample(2)), Err(FormatError::Unsupported(_))));
let current = read_mcmat(&sample(2)).unwrap();
assert_eq!(current.manifest.source, "source.sbs");
assert_eq!(current.source, b"pkg");
assert!(matches!(read_mcmat(&sample(3)), Err(FormatError::Unsupported(_))));
assert!(read_mcmat(b"junk").is_err());
}
#[test]
fn recognizes_both_generations_of_source_archive_without_confusing_portable_materials() {
for entry in ["package.json", "package.sbs"] {
let mut zip = zip::ZipWriter::new(Cursor::new(Vec::new()));
zip.start_file(entry, zip::write::SimpleFileOptions::default()).unwrap();
zip.write_all(b"source").unwrap();
let bytes = zip.finish().unwrap().into_inner();
assert!(is_mcraft(&bytes), "{entry}");
}
assert!(!is_mcraft(&sample(2)), "a portable material contains source.sbs too");
}
#[test]
fn an_unbounded_map_list_is_refused() {
let maps: Vec<_> = (0..=MAX_MAPS).map(|_| serde_json::json!({"usage": "baseColor", "file": "maps/baseColor.png"})).collect();
let manifest =
serde_json::json!({"format": FORMAT, "version": VERSION, "name": "n", "graph": "g", "size": [4, 4], "maps": maps, "source": "source.mcraft"});
let manifest = serde_json::json!({"format": craft_mcmat::FORMAT, "version": VERSION, "name": "n", "graph": "g", "size": [4, 4], "maps": maps, "source": "source.mcraft"});
let mut archive = zip::ZipWriter::new(Cursor::new(Vec::new()));
let options = zip::write::SimpleFileOptions::default();
archive.start_file("material.json", options).unwrap();
@@ -218,31 +240,6 @@ mod tests {
assert!(matches!(result, Err(FormatError::Malformed { .. })));
}
#[test]
fn entry_read_stops_at_the_remaining_payload_budget() {
let payload = vec![7u8; 1024];
let mut input = Cursor::new(&payload);
let mut total_bytes = MAX_TOTAL - 8;
let result = read_entry("maps/extra.png", &mut input, &mut total_bytes);
assert!(matches!(result, Err(FormatError::TooLarge(_))));
assert_eq!(input.position(), 9, "only one byte beyond the remaining budget is needed to reject the entry");
assert_eq!(total_bytes, MAX_TOTAL - 8, "a rejected entry does not consume the payload budget");
}
#[test]
fn payload_budget_accepts_the_exact_limit_and_empty_entries() {
let mut total_bytes = MAX_TOTAL - 4;
let bytes = read_entry("map.png", Cursor::new([1, 2, 3, 4]), &mut total_bytes).unwrap();
assert_eq!(bytes, [1, 2, 3, 4]);
assert_eq!(total_bytes, MAX_TOTAL);
assert!(read_entry("empty.mcraft", Cursor::new([]), &mut total_bytes).unwrap().is_empty());
assert!(matches!(read_entry("extra.png", Cursor::new([1]), &mut total_bytes), Err(FormatError::TooLarge(_))));
}
#[test]
fn mesh_maps_encode_as_16_bit() {
let png = mesh_map_png(2, 1, &[0.0, 0.25, 0.5, 1.0]).unwrap();
+4 -4
View File
@@ -28,9 +28,9 @@ fn parse(bytes: &[u8]) -> Result<(gltf::Document, Option<Vec<u8>>)> {
let (json, blob) = if bytes.starts_with(b"glTF") {
let mut glb = gltf::Glb::from_slice(bytes).map_err(|e| malformed(KIND, e))?;
let blob = glb.bin.take().map(std::borrow::Cow::into_owned);
(glb.json.into_owned(), blob)
(glb.json, blob)
} else {
(bytes.to_vec(), None)
(std::borrow::Cow::Borrowed(bytes), None)
};
let mut value: serde_json::Value = serde_json::from_slice(&json).map_err(|e| malformed(KIND, e))?;
if let Some(scenes) = value.get_mut("scenes").and_then(serde_json::Value::as_array_mut) {
@@ -40,8 +40,8 @@ fn parse(bytes: &[u8]) -> Result<(gltf::Document, Option<Vec<u8>>)> {
}
}
}
let json = serde_json::to_vec(&value).map_err(|e| malformed(KIND, e))?;
let root = gltf::json::Root::from_slice(&json).map_err(|e| malformed(KIND, e))?;
// Consume the DOM directly rather than serialising it back to a second full-size buffer.
let root: gltf::json::Root = serde_json::from_value(value).map_err(|e| malformed(KIND, e))?;
let document = gltf::Document::from_json(root).map_err(|e| malformed(KIND, e))?;
Ok((document, blob))
}
+8 -3
View File
@@ -1,5 +1,7 @@
//! Wavefront OBJ (via `tobj`): polygons fan-triangulated, one vertex per unique v/vt/vn.
use std::io::{BufReader, Read};
use texturecraft_geom::glam::{Vec2, Vec3, Vec4};
use super::{RawMesh, check_triangles, check_vertices};
@@ -27,12 +29,15 @@ fn read_inner(bytes: &[u8]) -> Result<RawMesh> {
}
let library: String = names.iter().map(|name| format!("newmtl {name}\n")).collect();
let source = format!("mtllib texturecraft-usemtl.mtl\n{text}");
let prefix = "mtllib texturecraft-usemtl.mtl\n";
// Feed the prefix and the borrowed (or lossily converted) body as one reader: neither a
// whole-file copy nor an extra string is needed before tobj parses it.
let mut source = BufReader::new(prefix.as_bytes().chain(text.as_bytes()));
// Polygons stay whole so the wireframe can show them; `RawMesh::polygon` triangulates
let options = tobj::LoadOptions { single_index: true, triangulate: false, ignore_points: true, ignore_lines: true };
let (models, materials) =
tobj::load_obj_buf(&mut source.as_bytes(), &options, |_| tobj::load_mtl_buf(&mut library.as_bytes())).map_err(|e| malformed(KIND, e))?;
let (models, materials) = tobj::load_obj_buf(&mut source, &options, |_| tobj::load_mtl_buf(&mut library.as_bytes())).map_err(|e| malformed(KIND, e))?;
let materials = materials.unwrap_or_default();
let mut raw = RawMesh::default();
+59 -62
View File
@@ -1,78 +1,75 @@
//! STL (binary and ascii). Facets keep their own corners, so shading is flat; there are no UVs.
//! STL (binary and ASCII), read by the shared bounded mesh importer.
use texturecraft_geom::glam::Vec3;
use texturecraft_geom::glam::{Vec3, Vec4};
use super::{RawMesh, check_triangles};
use crate::{Result, malformed};
use super::{MAX_VERTICES, RawMesh, check_triangles};
use crate::{FormatError, Result};
const KIND: &str = "STL";
pub(crate) fn read(bytes: &[u8]) -> Result<RawMesh> {
let count = bytes.get(80..84).map(|b| u32::from_le_bytes([b[0], b[1], b[2], b[3]]) as usize);
let binary_len = count.and_then(|c| c.checked_mul(50)).and_then(|n| n.checked_add(84));
let looks_ascii = bytes.iter().position(|b| !b.is_ascii_whitespace()).and_then(|i| bytes.get(i..i + 5)) == Some(b"solid".as_slice());
let tris = match (count, binary_len) {
// Exact size wins: many binary files also start with "solid".
(Some(c), Some(len)) if len == bytes.len() => binary(bytes, c)?,
_ if looks_ascii => ascii(bytes)?,
(Some(c), Some(len)) if len < bytes.len() => binary(bytes, c)?,
_ => return Err(malformed(KIND, "neither a complete binary STL nor an ascii STL")),
};
let scene = craft_mesh::stl::read(bytes, &stl_limits()).map_err(|e| FormatError::Invalid(e.to_string()))?;
let mut raw = RawMesh::default();
check_triangles(0, tris.len())?;
let mut normals = Vec::with_capacity(tris.len() * 3);
for t in &tris {
let n = (t[1] - t[0]).cross(t[2] - t[0]).try_normalize().unwrap_or(Vec3::Y);
raw.positions.extend_from_slice(t);
normals.extend_from_slice(&[n; 3]);
raw.warnings = scene.warnings;
let mut tri_count = 0;
let mut vertex_colors = Vec::new();
let has_colors = !scene.materials.is_empty();
for mesh in scene.meshes {
// The shared model groups colored facets into parts. Position indices still reflect
// source order, so merge the parts back into STL order for TextureCraft's raw mesh.
let mut triangles = Vec::new();
for part in mesh.parts {
let material = part.material.and_then(|i| scene.materials.get(i));
let color = material.map(|m| Vec4::from_array(m.base_color));
for tri in part.triangles() {
let first_position = tri.iter().map(|c| c.position).min().unwrap_or(u32::MAX);
triangles.push((first_position, tri, color));
}
}
triangles.sort_by_key(|(first_position, _, _)| *first_position);
for (_, tri, color) in triangles {
check_triangles(tri_count, 1)?;
tri_count += 1;
let mut points = [Vec3::ZERO; 3];
for (i, corner) in tri.into_iter().enumerate() {
let p = mesh.positions.get(corner.position as usize).ok_or_else(|| FormatError::Invalid(format!("{KIND}: position index out of range")))?;
points[i] = Vec3::new(p[0] as f32, p[1] as f32, p[2] as f32);
}
// Recompute per-facet normals as TextureCraft's old importer did; stored STL
// normals are often zero or disagree with the vertex winding.
let normal = (points[1] - points[0]).cross(points[2] - points[0]).try_normalize().unwrap_or(Vec3::Y);
raw.positions.extend_from_slice(&points);
raw.normals.get_or_insert_with(Vec::new).extend_from_slice(&[normal; 3]);
if has_colors {
// The shared reader normalizes STL's color extensions to linear RGBA.
// Uncolored facets alongside colored ones receive its neutral gray material.
let color = color.unwrap_or(Vec4::new(0.6, 0.6, 0.6, 1.0));
vertex_colors.extend_from_slice(&[color; 3]);
}
}
}
if raw.positions.is_empty() {
return Err(crate::malformed(KIND, "no facets"));
}
if has_colors {
raw.colors = Some(vertex_colors);
}
raw.normals = Some(normals);
raw.groups.push(("Default".into(), String::new(), (0..raw.positions.len() as u32).collect()));
Ok(raw)
}
fn binary(bytes: &[u8], count: usize) -> Result<Vec<[Vec3; 3]>> {
check_triangles(0, count)?;
let mut out = Vec::with_capacity(count);
for i in 0..count {
let f = |k: usize| -> Result<f32> {
let o = 84 + i * 50 + 12 + k * 4;
let b = bytes.get(o..o + 4).ok_or_else(|| malformed(KIND, "truncated facet"))?;
Ok(f32::from_le_bytes([b[0], b[1], b[2], b[3]]))
};
let v = |c: usize| -> Result<Vec3> { Ok(Vec3::new(f(c * 3)?, f(c * 3 + 1)?, f(c * 3 + 2)?)) };
out.push([v(0)?, v(1)?, v(2)?]);
}
Ok(out)
/// STL stores three positions per facet; retain the app's established triangle capacity.
fn stl_limits() -> craft_mesh::Limits {
craft_mesh::Limits { max_vertices: MAX_VERTICES, ..craft_mesh::Limits::default() }
}
fn ascii(bytes: &[u8]) -> Result<Vec<[Vec3; 3]>> {
let text = std::str::from_utf8(bytes).map_err(|_| malformed(KIND, "ascii STL is not text"))?;
let mut out = Vec::new();
let mut facet: Vec<Vec3> = Vec::new();
let mut words = text.split_whitespace();
while let Some(w) = words.next() {
match w {
"vertex" => {
let mut c = [0.0f32; 3];
for v in &mut c {
let tok = words.next().ok_or_else(|| malformed(KIND, "truncated vertex"))?;
*v = tok.parse().map_err(|_| malformed(KIND, format!("bad number \"{tok}\"")))?;
}
facet.push(Vec3::from(c));
}
"endfacet" => {
for i in 1..facet.len().saturating_sub(1) {
check_triangles(out.len(), 1)?;
out.push([facet[0], facet[i], facet[i + 1]]);
}
facet.clear();
}
_ => {}
}
#[cfg(test)]
mod tests {
#[test]
fn shared_reader_accepts_the_app_vertex_limit() {
let limits = super::stl_limits();
assert_eq!(limits.max_vertices, super::MAX_VERTICES);
assert_eq!(limits.max_triangles, texturecraft_geom::MAX_TRIANGLES);
}
if out.is_empty() {
return Err(malformed(KIND, "no facets"));
}
Ok(out)
}
+37
View File
@@ -414,6 +414,43 @@ fn stl_ascii_and_binary() {
assert_eq!(import_mesh_bytes("c.stl", &b).unwrap().mesh.triangle_count(), 2);
}
#[test]
fn stl_shared_reader_keeps_flat_normals_and_surfaces_shared_repairs_and_colors() {
let mut bytes = stl_binary();
// VisCAM/SolidView: bit 15 marks a facet color; red occupies bits 10..14.
bytes[132..134].copy_from_slice(&0xfc00u16.to_le_bytes());
// A third facet repeats that color after an uncolored facet. The shared reader groups its
// parts by color, so the adapter must restore the source facet order.
bytes.extend([0.0f32; 3].iter().flat_map(|v| v.to_le_bytes()));
for v in [[0.0f32, 0.0, 1.0], [1.0, 0.0, 1.0], [1.0, 1.0, 1.0]] {
bytes.extend(v.iter().flat_map(|x| x.to_le_bytes()));
}
bytes.extend(0xfc00u16.to_le_bytes());
// Some exporters leave the header count at zero despite having facets.
bytes[80..84].copy_from_slice(&0u32.to_le_bytes());
let imported = import_mesh_bytes("colored.stl", &bytes).unwrap();
assert_eq!(imported.mesh.triangle_count(), 3);
assert_eq!(imported.mesh.submeshes.len(), 1);
assert_eq!(imported.mesh.submeshes[0].name, "colored");
assert_eq!(
imported.mesh.positions,
vec![
Vec3::ZERO,
Vec3::X,
Vec3::new(1.0, 1.0, 0.0),
Vec3::ZERO,
Vec3::new(1.0, 1.0, 0.0),
Vec3::Y,
Vec3::Z,
Vec3::new(1.0, 0.0, 1.0),
Vec3::new(1.0, 1.0, 1.0)
]
);
assert_eq!(imported.mesh.normals, vec![Vec3::Z; 9]);
assert!(imported.mesh.colors.iter().any(|c| c.x > 0.99 && c.y < 0.01 && c.z < 0.01));
assert!(imported.report.warnings.iter().any(|w| w.contains("counts no facets")));
}
/// Every prefix and some corruptions of a valid file: errors, never panics (and never an
/// error from the panic guard, which would mean a parser panicked).
pub(crate) fn hammer(name: &str, good: &[u8]) {
@@ -13,14 +13,18 @@ impl LoadBudget {
self.limit_bytes - self.used_bytes
}
pub(super) fn exceeded_message(&self) -> String {
format!(
"project file decompresses to more than {} bytes ({:.2} GiB); increase Max project size on open in Settings > Project to open larger files",
self.limit_bytes,
self.limit_bytes as f64 / (1u64 << 30) as f64,
)
}
/// Reserve bytes before retaining decoded data so entries share one allocation budget.
pub(super) fn take(&mut self, bytes: u64) -> Result<(), String> {
if bytes > self.remaining() {
return Err(format!(
"project file decompresses to more than {} bytes ({:.2} GiB); increase Max project size on open in Settings > Project to open larger files",
self.limit_bytes,
self.limit_bytes as f64 / (1u64 << 30) as f64,
));
return Err(self.exceeded_message());
}
self.used_bytes += bytes;
@@ -1,81 +0,0 @@
use std::cell::Cell;
use std::io::{self, Read, Seek, SeekFrom};
/// Restrict ZIP indexing to a bounded tail and read allowance before enabling payload access.
pub(super) struct MetadataReader<'a, R> {
reader: R,
metadata_only: &'a Cell<bool>,
metadata_start: u64,
remaining_bytes: u64,
position: u64,
}
impl<'a, R: Read + Seek> MetadataReader<'a, R> {
pub(super) fn new(mut reader: R, metadata_only: &'a Cell<bool>, metadata_bytes: u64) -> io::Result<Self> {
let end = reader.seek(SeekFrom::End(0))?;
Ok(Self { reader, metadata_only, metadata_start: end.saturating_sub(metadata_bytes), remaining_bytes: metadata_bytes.saturating_mul(2), position: end })
}
}
impl<R: Read> Read for MetadataReader<'_, R> {
fn read(&mut self, bytes: &mut [u8]) -> io::Result<usize> {
if bytes.is_empty() {
return Ok(0);
}
let metadata_only = self.metadata_only.get();
if metadata_only && (self.position < self.metadata_start || self.remaining_bytes == 0) {
return Err(io::Error::new(io::ErrorKind::InvalidData, "project ZIP metadata exceeds the indexing limit"));
}
let length = if metadata_only { bytes.len().min(usize::try_from(self.remaining_bytes).unwrap_or(usize::MAX)) } else { bytes.len() };
let read = self.reader.read(bytes.get_mut(..length).unwrap_or_default())?;
self.position = self.position.saturating_add(read as u64);
if metadata_only {
self.remaining_bytes -= read as u64;
}
Ok(read)
}
}
impl<R: Seek> Seek for MetadataReader<'_, R> {
fn seek(&mut self, position: SeekFrom) -> io::Result<u64> {
self.position = self.reader.seek(position)?;
Ok(self.position)
}
}
#[cfg(test)]
mod tests {
use super::*;
use std::io::Cursor;
#[test]
fn indexing_cannot_read_payloads_outside_the_metadata_window() {
let metadata_only = Cell::new(true);
let mut reader = MetadataReader::new(Cursor::new(vec![7; 100]), &metadata_only, 8).unwrap();
reader.seek(SeekFrom::Start(91)).unwrap();
assert!(reader.read(&mut [0; 1]).is_err());
reader.seek(SeekFrom::Start(92)).unwrap();
reader.read_exact(&mut [0; 8]).unwrap();
metadata_only.set(false);
reader.seek(SeekFrom::Start(0)).unwrap();
reader.read_exact(&mut [0; 100]).unwrap();
}
#[test]
fn repeated_metadata_scans_share_one_read_allowance() {
let metadata_only = Cell::new(true);
let mut reader = MetadataReader::new(Cursor::new(vec![7; 8]), &metadata_only, 8).unwrap();
for _ in 0..2 {
reader.seek(SeekFrom::Start(0)).unwrap();
reader.read_exact(&mut [0; 8]).unwrap();
}
reader.seek(SeekFrom::Start(0)).unwrap();
assert!(reader.read(&mut [0; 1]).is_err());
}
}
+53 -152
View File
@@ -18,7 +18,6 @@
//! count of 0, followed by `width × height × components` f32 LE. Pixels of a UV-tiled texture
//! set cover its whole atlas (`resolution` per tile, see `TileGrid`).
use std::cell::Cell;
use std::collections::{BTreeMap, HashSet};
use std::io::{Cursor, Read, Seek, Write};
use std::sync::Arc;
@@ -31,21 +30,21 @@ use zip::{CompressionMethod, ZipArchive, ZipWriter};
use self::entries::Entry;
use self::load_budget::LoadBudget;
use self::metadata_reader::MetadataReader;
use crate::{FormatError, MAX_IMAGE_SIZE, Result, malformed};
mod entries;
mod load_budget;
mod metadata_reader;
mod project_open_limit;
#[cfg(not(target_arch = "wasm32"))]
pub use entries::{DEFAULT_RAM_PERCENT, DEFAULT_RESERVED_CORES, available_save_resources, save_ram_budget, set_save_resources};
pub use project_open_limit::{DEFAULT_PROJECT_OPEN_LIMIT_GIB, project_open_limit_gib, set_project_open_limit_gib};
const KIND: &str = "project file";
#[cfg(test)]
const MAGIC: &[u8; 4] = b"TCTX";
/// Version of the `.bin` layout.
#[cfg(test)]
const BIN_VERSION: u32 = 1;
#[cfg(test)]
const BIN_HEADER_BYTES: usize = 24;
const MAX_JSON: u64 = 256 << 20;
const MAX_THUMBNAIL: u64 = 64 << 20;
@@ -124,6 +123,7 @@ fn zip_err(e: zip::result::ZipError) -> FormatError {
}
}
#[cfg(test)]
fn header(w: u32, h: u32, comps: usize, count: usize) -> Vec<u8> {
let mut b = MAGIC.to_vec();
for v in [BIN_VERSION, w, h, comps as u32, count as u32] {
@@ -132,19 +132,18 @@ fn header(w: u32, h: u32, comps: usize, count: usize) -> Vec<u8> {
b
}
fn write_tiles(w: &mut impl Write, img: &TileImage) -> std::io::Result<()> {
w.write_all(&header(img.width(), img.height(), img.comps(), img.allocated_count()))?;
let mut buf = Vec::with_capacity(TILE_AREA * img.comps() * 2 + 8);
for (tx, ty) in img.allocated() {
buf.clear();
buf.extend_from_slice(&tx.to_le_bytes());
buf.extend_from_slice(&ty.to_le_bytes());
for v in img.tile(tx, ty).unwrap_or_default() {
buf.extend_from_slice(&v.to_le_bytes());
}
w.write_all(&buf)?;
fn codec_write_error(error: craft_tcraft::Error) -> std::io::Error {
match error {
craft_tcraft::Error::Io(error) => error,
other => std::io::Error::other(other),
}
Ok(())
}
fn write_tiles(w: &mut impl Write, img: &TileImage) -> std::io::Result<()> {
let layout = craft_tcraft::Layout { width: img.width(), height: img.height(), components: img.comps() };
let count = u32::try_from(img.allocated_count()).map_err(std::io::Error::other)?;
let tiles = img.allocated().map(|(x, y)| (x, y, img.tile(x, y).unwrap_or_default()));
craft_tcraft::write_tiles(w, layout, count, tiles).map_err(codec_write_error)
}
/// Keep `[a-z0-9]`, at most 8 characters (the mesh entry's extension).
@@ -169,18 +168,12 @@ fn unique_entry_name(dir: &str, name: &str, used: &mut HashSet<String>) -> Strin
entry
}
/// Floats converted to bytes at a time when a baked map streams into the compressor.
#[cfg(test)]
const BAKED_CHUNK: usize = 1 << 16;
fn write_baked(w: &mut dyn Write, res: u32, h: u32, comps: usize, data: &[f32]) -> std::io::Result<()> {
w.write_all(&header(res, h, comps, 0))?;
let mut buf = Vec::with_capacity(BAKED_CHUNK * 4);
for chunk in data.chunks(BAKED_CHUNK) {
buf.clear();
buf.extend(chunk.iter().flat_map(|v| v.to_le_bytes()));
w.write_all(&buf)?;
}
Ok(())
let layout = craft_tcraft::Layout { width: res, height: h, components: comps };
craft_tcraft::write_baked(w, layout, data).map_err(codec_write_error)
}
/// The zip entries of a project file, in file order. Bodies run later, possibly on other threads.
@@ -304,110 +297,34 @@ fn read_all(reader: &mut impl Read, cap: u64, budget: &mut LoadBudget, what: &st
Ok(out)
}
/// Decode bounded chunks so a false header cannot allocate an entire missing map.
fn read_f32s(reader: &mut impl Read, count: usize, what: &str) -> Result<Vec<f32>> {
let mut values = Vec::new();
let mut bytes = vec![0u8; BAKED_CHUNK.min(count) * 4];
let mut remaining = count;
while remaining > 0 {
let chunk_values = BAKED_CHUNK.min(remaining);
let chunk = bytes.get_mut(..chunk_values * 4).ok_or_else(|| malformed(KIND, format!("{what}: invalid float chunk")))?;
read_exact(reader, chunk, what)?;
values.try_reserve(chunk_values).map_err(|_| FormatError::TooLarge(format!("{what}: not enough memory for {count} values")))?;
values.extend(chunk.as_chunks::<4>().0.iter().map(|bytes| f32::from_le_bytes(*bytes)));
remaining -= chunk_values;
}
Ok(values)
}
fn read_exact(r: &mut impl Read, buf: &mut [u8], what: &str) -> Result<()> {
r.read_exact(buf).map_err(|e| malformed(KIND, format!("{what}: {e}")))
}
fn u32_at(b: &[u8], i: usize) -> u32 {
b.get(i * 4..i * 4 + 4).map(|s| u32::from_le_bytes([s[0], s[1], s[2], s[3]])).unwrap_or(0)
}
/// Read and check a `.bin` header: returns (width, height, comps, count).
fn read_header(r: &mut impl Read, what: &str) -> Result<(u32, u32, usize, usize)> {
let mut h = [0u8; BIN_HEADER_BYTES];
read_exact(r, &mut h, what)?;
if h.get(..4) != Some(MAGIC.as_slice()) {
return Err(malformed(KIND, format!("{what}: bad magic")));
}
let v = u32_at(&h, 1);
if v > BIN_VERSION {
return Err(FormatError::NewerVersion { found: v, supported: BIN_VERSION });
}
Ok((u32_at(&h, 2), u32_at(&h, 3), u32_at(&h, 4) as usize, u32_at(&h, 5) as usize))
}
/// Error unless the entry has no bytes left (also makes the zip reader verify the CRC).
fn expect_end(r: &mut impl Read, what: &str) -> Result<()> {
let mut b = [0u8; 1];
match r.read(&mut b) {
Ok(0) => Ok(()),
Ok(_) => Err(malformed(KIND, format!("{what}: trailing data"))),
Err(e) => Err(malformed(KIND, format!("{what}: {e}"))),
}
/// Transfer the bytes charged by the shared codec to this project's one load budget.
fn codec_result<T>(result: std::result::Result<T, craft_tcraft::Error>, shared: &craft_zip::Budget, budget: &mut LoadBudget, what: &str) -> Result<T> {
budget.take(shared.used()).map_err(FormatError::TooLarge)?;
result.map_err(|error| match error {
craft_tcraft::Error::Budget(_) => FormatError::TooLarge(budget.exceeded_message()),
craft_tcraft::Error::Limit(message) => FormatError::TooLarge(format!("{what}: {message}")),
craft_tcraft::Error::NewerVersion(found) => FormatError::NewerVersion { found, supported: craft_tcraft::VERSION },
other => malformed(KIND, format!("{what}: {other}")),
})
}
fn read_tiles(reader: &mut impl Read, size: (u32, u32), components: usize, budget: &mut LoadBudget, what: &str) -> Result<TileImage> {
budget.take(BIN_HEADER_BYTES as u64).map_err(FormatError::TooLarge)?;
let (width, height, stored_components, count) = read_header(reader, what)?;
if (width, height) != size || stored_components != components {
return Err(malformed(
KIND,
format!("{what}: {width}×{height}×{stored_components} does not match the texture set ({}×{}×{components})", size.0, size.1),
));
}
let mut image = TileImage::new(width, height, components);
if count > (image.tiles_x() as usize) * (image.tiles_y() as usize) {
return Err(malformed(KIND, format!("{what}: {count} tiles is more than the image holds")));
}
let mut bytes = vec![0u8; TILE_AREA * components * 2];
let mut position_bytes = [0u8; 8];
for _ in 0..count {
budget.take((position_bytes.len() + bytes.len()) as u64).map_err(FormatError::TooLarge)?;
read_exact(reader, &mut position_bytes, what)?;
let (tx, ty) = (u32_at(&position_bytes, 0), u32_at(&position_bytes, 1));
if tx >= image.tiles_x() || ty >= image.tiles_y() || image.is_allocated(tx, ty) {
return Err(malformed(KIND, format!("{what}: bad or repeated tile ({tx}, {ty})")));
}
read_exact(reader, &mut bytes, what)?;
let data: Vec<u16> = bytes.as_chunks::<2>().0.iter().map(|b| u16::from_le_bytes(*b)).collect();
image.set_tile(tx, ty, Some(Arc::new(data)));
}
expect_end(reader, what)?;
Ok(image)
let layout = craft_tcraft::Layout { width: size.0, height: size.1, components };
let mut shared = craft_zip::Budget::new("project", budget.remaining());
let mut image = None;
let result = craft_tcraft::read_tiles(reader, layout, MAX_TEXELS, &mut shared, |x, y, values| {
image.get_or_insert_with(|| TileImage::new(size.0, size.1, components)).set_tile(x, y, Some(Arc::new(values)));
Ok(())
});
codec_result(result, &shared, budget, what)?;
Ok(image.unwrap_or_else(|| TileImage::new(size.0, size.1, components)))
}
/// A baked map: (width, height, data).
fn read_baked(reader: &mut impl Read, declared_bytes: u64, components: usize, budget: &mut LoadBudget, what: &str) -> Result<(u32, u32, Vec<f32>)> {
budget.take(BIN_HEADER_BYTES as u64).map_err(FormatError::TooLarge)?;
let (width, height, stored_components, _) = read_header(reader, what)?;
if width == 0 || height == 0 || u64::from(width) * u64::from(height) > MAX_TEXELS || stored_components != components {
return Err(malformed(KIND, format!("{what}: bad size {width}×{height}×{stored_components}")));
}
let value_count = u64::from(width) * u64::from(height) * components as u64;
let payload_bytes = value_count * 4;
if declared_bytes != BIN_HEADER_BYTES as u64 + payload_bytes {
return Err(malformed(KIND, format!("{what}: {declared_bytes} bytes for a {width}×{height}×{components} map")));
}
budget.take(payload_bytes).map_err(FormatError::TooLarge)?;
let value_count = usize::try_from(value_count).map_err(|_| FormatError::TooLarge(format!("{what}: too many values for this platform")))?;
let data = read_f32s(reader, value_count, what)?;
expect_end(reader, what)?;
Ok((width, height, data))
let mut shared = craft_zip::Budget::new("project", budget.remaining());
let result = craft_tcraft::read_baked(reader, declared_bytes, components, MAX_TEXELS, &mut shared);
let (layout, values) = codec_result(result, &shared, budget, what)?;
Ok((layout.width, layout.height, values))
}
/// Texture set holding a paint layer, a content effect or a mask effect id.
@@ -422,47 +339,31 @@ fn load<R: Read + Seek>(reader: R) -> Result<ProjectFile> {
}
fn check_archive<R: Read + Seek>(zip: &mut ZipArchive<R>, limit_bytes: u64) -> Result<()> {
if zip.len() > MAX_ENTRIES {
return Err(FormatError::TooLarge(format!("project file has more than {MAX_ENTRIES} entries")));
}
// Count every declared payload, including ignored entries, before any decompression
let mut declared_budget = LoadBudget::new(limit_bytes);
for index in 0..zip.len() {
let entry = zip.by_index_raw(index).map_err(zip_err)?;
declared_budget.take(entry.size()).map_err(FormatError::TooLarge)?;
}
// Shared compressed ranges can amplify one payload into many apparent files
if zip.has_overlapping_entries().map_err(zip_err)? {
return Err(malformed(KIND, "overlapping ZIP entries are not supported"));
}
Ok(())
craft_zip::inspect_seekable(zip, MAX_ENTRIES, limit_bytes).map_err(|error| match error {
craft_zip::InspectError::TooManyEntries { .. } => FormatError::TooLarge(format!("project file has more than {MAX_ENTRIES} entries")),
craft_zip::InspectError::DeclaredBytesExceeded { .. } => FormatError::TooLarge(LoadBudget::new(limit_bytes).exceeded_message()),
craft_zip::InspectError::OverlappingEntries => malformed(KIND, "overlapping ZIP entries are not supported"),
craft_zip::InspectError::Zip(error) => zip_err(error),
})
}
fn open_archive<'a, R: Read + Seek>(reader: R, metadata_only: &'a Cell<bool>, metadata_bytes: u64) -> Result<ZipArchive<MetadataReader<'a, R>>> {
let reader = MetadataReader::new(reader, metadata_only, metadata_bytes)?;
fn open_archive<R: Read + Seek>(reader: R, metadata_bytes: u64) -> Result<ZipArchive<craft_zip::MetadataReader<R>>> {
let (reader, indexing) = craft_zip::MetadataReader::new(reader, metadata_bytes)?;
// Project archives start at byte zero; avoid scanning payloads to guess an embedded ZIP offset
let config = zip::read::Config { archive_offset: zip::read::ArchiveOffset::Known(0) };
let archive = ZipArchive::with_config(config, reader).map_err(zip_err)?;
metadata_only.set(false);
indexing.finish();
Ok(archive)
}
fn load_with_budget<R: Read + Seek>(reader: R, mut budget: LoadBudget) -> Result<ProjectFile> {
let metadata_only = Cell::new(true);
let mut zip = open_archive(reader, &metadata_only, MAX_ZIP_METADATA_BYTES)?;
let mut zip = open_archive(reader, MAX_ZIP_METADATA_BYTES)?;
check_archive(&mut zip, budget.remaining())?;
let json = read_all(&mut zip.by_name("project.json").map_err(zip_err)?, MAX_JSON, &mut budget, "project.json")?;
#[derive(serde::Deserialize)]
struct Version {
format_version: u32,
}
let v: Version = serde_json::from_slice(&json).map_err(|e| malformed(KIND, format!("project.json: {e}")))?;
if v.format_version > FORMAT_VERSION {
return Err(FormatError::NewerVersion { found: v.format_version, supported: FORMAT_VERSION });
let version = craft_tcraft::project_version(&json).map_err(|e| malformed(KIND, format!("project.json: {e}")))?;
if version > FORMAT_VERSION {
return Err(FormatError::NewerVersion { found: version, supported: FORMAT_VERSION });
}
let (project, mut recovered) = recovery::read_project(&json).map_err(|e| malformed(KIND, format!("project.json: {e}")))?;
+19 -11
View File
@@ -82,6 +82,15 @@ fn round_trip_is_identical_and_deterministic() {
assert_same(&builtin, &load_project_bytes(&save_project_bytes(&builtin).unwrap()).unwrap());
}
#[test]
fn shared_project_schema_round_trips_the_app_document() {
let project = sample().pf.project;
let original = serde_json::to_value(&project).unwrap();
let document: craft_tcraft::ProjectDocument = serde_json::from_value(original.clone()).unwrap();
assert_eq!(document.format_version, project.format_version);
assert_eq!(serde_json::to_value(document).unwrap(), original);
}
#[test]
fn legacy_bakes_load_as_is_without_layout_conversion() {
let mut sample = sample();
@@ -803,13 +812,17 @@ fn baked_dimensions_must_match_the_entry_before_reserving_payload_bytes() {
#[test]
fn streamed_float_chunks_preserve_bits_across_the_chunk_boundary() {
let values: Vec<u32> = (0..BAKED_CHUNK + 3).map(|index| (index as u32).wrapping_mul(0x9e3779b9)).collect();
let bytes: Vec<u8> = values.iter().flat_map(|bits| bits.to_le_bytes()).collect();
let mut bytes = header(values.len() as u32, 1, 1, 0);
bytes.extend(values.iter().flat_map(|bits| bits.to_le_bytes()));
let declared = bytes.len() as u64;
let mut reader = Cursor::new(bytes);
let mut budget = LoadBudget::new(declared);
let decoded = read_f32s(&mut reader, values.len(), "baked map").unwrap();
let (_, _, decoded) = read_baked(&mut reader, declared, 1, &mut budget, "baked map").unwrap();
assert_eq!(decoded.into_iter().map(f32::to_bits).collect::<Vec<_>>(), values);
assert_eq!(reader.position(), (values.len() * 4) as u64);
assert_eq!(reader.position(), declared);
assert_eq!(budget.remaining(), 0);
}
#[test]
@@ -818,23 +831,19 @@ fn archive_indexing_does_not_scan_large_payloads_and_rejects_large_metadata() {
writer.start_file("resource", SimpleFileOptions::default().compression_method(CompressionMethod::Stored)).unwrap();
writer.write_all(&vec![7; 1 << 20]).unwrap();
let bytes = writer.finish().unwrap().into_inner();
let metadata_only = Cell::new(true);
let mut archive = open_archive(Cursor::new(bytes), &metadata_only, 4096).unwrap();
let mut archive = open_archive(Cursor::new(bytes), 4096).unwrap();
let mut first_byte = [0; 1];
archive.by_index(0).unwrap().read_exact(&mut first_byte).unwrap();
assert_eq!(first_byte, [7]);
assert!(!metadata_only.get());
let mut writer = ZipWriter::new(Cursor::new(Vec::new()));
writer.start_file("a".repeat(5000), SimpleFileOptions::default()).unwrap();
writer.write_all(&[7]).unwrap();
let bytes = writer.finish().unwrap().into_inner();
let metadata_only = Cell::new(true);
assert!(open_archive(Cursor::new(bytes), &metadata_only, 4096).is_err());
assert!(metadata_only.get(), "failed indexing must not enable payload access");
assert!(open_archive(Cursor::new(bytes), 4096).is_err());
}
#[test]
@@ -845,9 +854,8 @@ fn zip64_entry_counts_remain_supported_and_bounded() {
writer.start_file(format!("e{index}"), SimpleFileOptions::default().compression_method(CompressionMethod::Stored)).unwrap();
}
let bytes = writer.finish().unwrap().into_inner();
let metadata_only = Cell::new(true);
let mut archive = open_archive(Cursor::new(bytes), &metadata_only, MAX_ZIP_METADATA_BYTES).unwrap();
let mut archive = open_archive(Cursor::new(bytes), MAX_ZIP_METADATA_BYTES).unwrap();
let result = check_archive(&mut archive, 0);
assert_eq!(archive.len(), count);
+2
View File
@@ -5,4 +5,6 @@ pub struct BakeJob {
pub queue: Vec<usize>,
pub current: Option<RunningBake>,
pub total: usize,
/// The mesh the job was started on: a result for another mesh (changed or reimported meanwhile) is not applied.
pub mesh_id: u64,
}
+529 -410
View File
File diff suppressed because it is too large. Load diff
+394
View File
@@ -0,0 +1,394 @@
//! A generator effect's properties, laid out like the reference app's: attributes, resolution, parameters, image inputs.
use egui::{RichText, Ui};
use egui_phosphor::regular as ic;
use serde_json::{Value, json};
use texturecraft_engine::core::{BakedMap, CurvatureDetail, CurvatureMode, Generator, GeneratorKind, LayerId, OutputResolution, ResolutionMode, Source};
use crate::TextureCraftApp;
use crate::dock::{anchor_label, anchors_below, image_drop, image_menu, mesh_map_color};
use crate::i18n::{baked_map_label, tr, trf};
use crate::theme::{Tokens, caption};
use crate::widgets::{combo, section, slider_edit};
/// Random seeds stay below this, short enough to read and type.
const SEED_RANGE: u32 = 10_000;
/// Knuth's multiplicative hash constant: spreads the clock's nanoseconds over the seed range.
const SEED_MIX: u32 = 2_654_435_761;
/// Font size of the notes under a control.
const NOTE_FONT_SIZE: f32 = 10.5;
/// Edge of the picture beside each image input, its corner rounding and the size of an icon drawn in it.
const INPUT_TILE_SIZE: f32 = 32.0;
const INPUT_TILE_ROUNDING: f32 = 2.0;
const INPUT_TILE_ICON_SIZE: f32 = 16.0;
/// Width of the names in the Attributes section, so their values line up.
const ATTRIBUTE_KEY_WIDTH: f32 = 80.0;
/// The settings of generator effect `id`.
pub(crate) fn generator_properties(app: &mut TextureCraftApp, ui: &mut Ui, layer: LayerId, id: u64, generator: &Generator) {
let tokens = Tokens::get(ui.ctx());
ui.label(caption(tr("Generator")));
egui::ComboBox::from_id_salt("gen_kind").selected_text(tr(generator.kind.label())).show_ui(ui, |ui| {
for kind in GeneratorKind::ALL {
if ui.selectable_label(kind == generator.kind, tr(kind.label())).clicked() && kind != generator.kind {
app.run("effect.set", json!({"effect": id, "generator": format!("{kind:?}")}));
}
}
});
section(ui, "generator_attributes", tr("Attributes"), false, |ui| attributes(ui, generator.kind));
section(ui, "generator_resolution", tr("Resolution"), false, |ui| resolution(app, ui, id, generator.resolution));
section(ui, "generator_parameters", tr("Parameters"), true, |ui| {
global_adjustments(app, ui, id, generator);
ramp_parameters(app, ui, id, generator);
if matches!(generator.kind, GeneratorKind::Curvature | GeneratorKind::EdgeWear) {
curvature_detail_properties(app, ui, id, generator.detail.as_ref());
}
ui.horizontal(|ui| {
ui.with_layout(egui::Layout::right_to_left(egui::Align::Center), |ui| {
if ui.button(tr("Restore defaults")).clicked() {
app.run("effect.set", defaults_of(id, generator.kind));
}
});
});
});
if !generator.kind.inputs().is_empty() {
section(ui, "generator_inputs", tr("Image inputs"), true, |ui| {
for map in generator.kind.inputs() {
input_slot(app, ui, (layer, id), *map, generator.inputs.get(map), generator.detail.is_some());
}
});
}
if !app.session.doc.baked.contains_key(&app.session.ts()) {
ui.label(
RichText::new(format!("{} {}", ic::WARNING, tr("Bake mesh maps (F8) for curvature, AO and thickness based generators."))).color(tokens.warning),
);
}
}
/// What a generator kind makes, its category and its tags (read only).
fn attributes(ui: &mut Ui, kind: GeneratorKind) {
let tokens = Tokens::get(ui.ctx());
let (description, tags) = match kind {
GeneratorKind::EdgeWear => (
tr("Convex edges from the curvature map, broken up by noise: worn paint and polished edges."),
[tr("mask"), tr("generator"), tr("grayscale"), tr("curvature")],
),
GeneratorKind::Dirt => (
tr("Crevices and occluded areas from the ambient occlusion map: dirt and grime."),
[tr("mask"), tr("generator"), tr("grayscale"), tr("ambient occlusion")],
),
GeneratorKind::ThinAreas => (tr("Thin parts of the mesh from the thickness map."), [tr("mask"), tr("generator"), tr("grayscale"), tr("thickness")]),
GeneratorKind::Curvature => (
tr("Convex edges, cavities or both from the curvature map, at several detail sizes."),
[tr("mask"), tr("generator"), tr("grayscale"), tr("curvature")],
),
GeneratorKind::AmbientOcclusion => {
(tr("Occluded areas from the ambient occlusion map."), [tr("mask"), tr("generator"), tr("grayscale"), tr("ambient occlusion")])
}
GeneratorKind::Position => (tr("A gradient along a world direction across the mesh."), [tr("mask"), tr("generator"), tr("grayscale"), tr("position")]),
GeneratorKind::Direction => (tr("Surfaces facing a direction, as if lit from it."), [tr("mask"), tr("generator"), tr("grayscale"), tr("normal")]),
};
// Wrapped rows: a long line must not widen the panel past its edge
let tags = tags.join(", ");
for (key, value) in [(tr("Description"), description), (tr("Category"), tr("Generators")), (tr("Tags"), tags.as_str())] {
ui.horizontal_top(|ui| {
ui.add_sized([ATTRIBUTE_KEY_WIDTH, 0.0], egui::Label::new(RichText::new(key).color(tokens.text_dim)));
ui.add(egui::Label::new(value).wrap());
});
}
}
/// What the generator's output resolution is based on, the factor applied to it, and the size it comes to.
fn resolution(app: &mut TextureCraftApp, ui: &mut Ui, id: u64, resolution: OutputResolution) {
let tokens = Tokens::get(ui.ctx());
combo(ui, tr("Resolution"), tr(resolution.mode.label()), |ui| {
for mode in ResolutionMode::ALL {
if ui.selectable_label(mode == resolution.mode, tr(mode.label())).clicked() {
app.run("effect.set", json!({"effect": id, "resolution": format!("{mode:?}")}));
}
}
})
.on_hover_text(tr("Auto and UV tile use the UV tile's resolution, Texture set the texture set's, Custom a size of its own."));
if resolution.mode == ResolutionMode::Custom {
combo(ui, tr("Size"), format!("{0} × {0}", resolution.custom), |ui| {
for size in OutputResolution::CUSTOM_SIZES {
if ui.selectable_label(size == resolution.custom, format!("{size} × {size}")).clicked() {
app.run("effect.set", json!({"effect": id, "customResolution": size}));
}
}
});
}
combo(ui, tr("Factor"), factor_label(resolution.factor), |ui| {
for factor in OutputResolution::FACTORS {
if ui.selectable_label(factor == resolution.factor, factor_label(factor)).clicked() {
app.run("effect.set", json!({"effect": id, "resolutionFactor": factor}));
}
}
})
.on_hover_text(tr("Scales the base resolution: below 1 the generator is computed coarser and smoothed back up."));
let Ok(texture_set) = app.session.doc.project.texture_set(app.session.ts()) else { return };
let (smallest, largest) = texture_set
.uv_tiles
.iter()
.map(|&udim| resolution.output_size(texture_set.tile_resolution(udim), texture_set.resolution))
.fold((u32::MAX, 0), |(smallest, largest), size| (smallest.min(size), largest.max(size)));
let (smallest, largest) = if largest == 0 {
let size = resolution.output_size(texture_set.resolution, texture_set.resolution);
(size, size)
} else {
(smallest, largest)
};
let size_label = if smallest == largest { format!("{smallest} × {smallest}") } else { format!("{smallest}–{largest} × {smallest}–{largest}") };
ui.horizontal(|ui| {
ui.label(RichText::new(tr("Output size")).color(tokens.text_dim));
ui.with_layout(egui::Layout::right_to_left(egui::Align::Center), |ui| ui.label(size_label));
})
.response
.on_hover_text(tr("An output finer than a UV tile gives the same result as that tile's resolution."));
}
/// The most powers of two a resolution factor scales by, either way.
const LARGEST_FACTOR_STEPS: u8 = OutputResolution::FACTORS.end().unsigned_abs();
/// "Same as context", or the fraction or multiple a resolution factor stands for.
fn factor_label(factor: i8) -> String {
match factor {
0 => tr("Same as context").to_string(),
negative if negative < 0 => format!("1/{}", 1u32 << negative.unsigned_abs().min(LARGEST_FACTOR_STEPS)),
positive => format!("×{}", 1u32 << positive.unsigned_abs().min(LARGEST_FACTOR_STEPS)),
}
}
/// Global invert, blur, balance and contrast: what every generator applies to its finished value.
fn global_adjustments(app: &mut TextureCraftApp, ui: &mut Ui, id: u64, generator: &Generator) {
let (mut invert, mut global) = (generator.invert, generator.global);
let invert_edit = ui.checkbox(&mut invert, tr("Global invert")).changed().then_some(false);
let blur_edit = slider_edit(ui, tr("Global blur"), &mut global.blur, 0.0..=1.0, 2);
let balance_edit = slider_edit(ui, tr("Global balance"), &mut global.balance, 0.0..=1.0, 2);
let contrast_edit = slider_edit(ui, tr("Global contrast"), &mut global.contrast, 0.0..=1.0, 2);
if let Some(merge) = invert_edit.or(blur_edit).or(balance_edit).or(contrast_edit) {
app.run(
"effect.set",
json!({"effect": id, "invert": invert, "blur": global.blur, "balance": global.balance, "contrast": global.contrast, "merge": merge}),
);
}
}
/// Where the generator's ramp starts, how soft it is, the noise breaking it up, its offset and its seed.
fn ramp_parameters(app: &mut TextureCraftApp, ui: &mut Ui, id: u64, generator: &Generator) {
let (mut level, mut softness, mut noise, mut noise_scale, mut offset) =
(generator.level, generator.softness, generator.noise_amount, generator.noise_scale, generator.offset);
let level_edit = slider_edit(ui, tr("Level"), &mut level, 0.0..=1.0, 2);
let softness_edit = slider_edit(ui, tr("Softness"), &mut softness, 0.0..=1.0, 2);
let noise_edit = slider_edit(ui, tr("Noise amount"), &mut noise, 0.0..=2.0, 2);
let noise_scale_edit = slider_edit(ui, tr("Noise scale"), &mut noise_scale, 0.1..=64.0, 1);
let offset_edit = slider_edit(ui, tr("Offset"), &mut offset, -1.0..=1.0, 2);
if let Some(merge) = level_edit.or(softness_edit).or(noise_edit).or(noise_scale_edit).or(offset_edit) {
app.run(
"effect.set",
json!({"effect": id, "level": level, "softness": softness, "noise": noise, "noiseScale": noise_scale, "offset": offset, "merge": merge}),
);
}
seed_row(app, ui, id, generator.seed);
}
/// The seed with a button that picks a new one and a pencil that opens a field to type it, as in the reference.
fn seed_row(app: &mut TextureCraftApp, ui: &mut Ui, id: u64, seed: u32) {
let typing_id = ui.make_persistent_id(("generator_seed_typing", id));
let mut typing = ui.data(|data| data.get_temp::<bool>(typing_id)).unwrap_or(false);
ui.horizontal(|ui| {
ui.label(tr("Seed"));
ui.with_layout(egui::Layout::right_to_left(egui::Align::Center), |ui| {
if ui.selectable_label(typing, ic::PENCIL_SIMPLE).on_hover_text(tr("Type the seed")).clicked() {
typing = !typing;
}
if typing {
let mut typed = seed;
let field = ui.add(egui::DragValue::new(&mut typed).speed(1.0));
if field.changed() {
// The later changes of one drag continue its first undo step
let merge = field.dragged() && !field.drag_started();
app.run("effect.set", json!({"effect": id, "seed": typed, "merge": merge}));
}
} else if ui.button(tr("Random")).on_hover_text(trf("Seed {seed}", &[("seed", &seed)])).clicked() {
app.run("effect.set", json!({"effect": id, "seed": random_seed(seed)}));
}
});
});
ui.data_mut(|data| data.insert_temp(typing_id, typing));
}
/// A seed different from `current`, from the clock.
fn random_seed(current: u32) -> u32 {
let nanos = std::time::SystemTime::now().duration_since(std::time::UNIX_EPOCH).map_or(0, |elapsed| elapsed.subsec_nanos());
let mixed = nanos.wrapping_mul(SEED_MIX) % SEED_RANGE;
if mixed == current { (mixed + 1) % SEED_RANGE } else { mixed }
}
/// The `effect.set` params that put generator effect `id` back to the defaults of its kind.
fn defaults_of(id: u64, kind: GeneratorKind) -> Value {
let defaults = Generator::new(kind);
let mut params = json!({
"effect": id,
"level": defaults.level,
"softness": defaults.softness,
"noise": defaults.noise_amount,
"noiseScale": defaults.noise_scale,
"offset": defaults.offset,
"seed": defaults.seed,
"direction": defaults.direction,
"invert": defaults.invert,
"blur": defaults.global.blur,
"balance": defaults.global.balance,
"contrast": defaults.global.contrast,
"resolution": format!("{:?}", defaults.resolution.mode),
"customResolution": defaults.resolution.custom,
"resolutionFactor": defaults.resolution.factor,
});
if let Some(detail) = defaults.detail {
params["mode"] = json!(format!("{:?}", detail.mode));
params["sizes"] = json!(detail.weights);
}
params
}
/// The curvature mode and detail size weights of generator effect `id` (`detail` None: saved before detail sizes).
fn curvature_detail_properties(app: &mut TextureCraftApp, ui: &mut Ui, id: u64, detail: Option<&CurvatureDetail>) {
let tokens = Tokens::get(ui.ctx());
let shown = detail.cloned().unwrap_or_default();
combo(ui, tr("Mode"), curvature_mode_label(shown.mode), |ui| {
for mode in CurvatureMode::ALL {
if ui.selectable_label(mode == shown.mode, curvature_mode_label(mode)).clicked() {
app.run("effect.set", json!({"effect": id, "mode": format!("{mode:?}")}));
}
}
});
ui.label(caption(tr("Detail sizes")));
let mut weights = shown.weights;
let mut edit = None;
for (weight, size) in weights.iter_mut().zip(CurvatureDetail::SIZES) {
edit = edit.or(slider_edit(ui, &format!("{size} px"), weight, 0.0..=1.0, 2));
}
if let Some(merge) = edit {
app.run("effect.set", json!({"effect": id, "sizes": weights, "merge": merge}));
}
if detail.is_none() {
ui.label(RichText::new(tr("Reads the curvature map as baked: changing the mode or a size turns detail sizes on.")).color(tokens.text_dim));
}
}
/// The translated name of curvature mode `mode`.
fn curvature_mode_label(mode: CurvatureMode) -> &'static str {
match mode {
CurvatureMode::Edges => tr("Edges"),
CurvatureMode::Cavities => tr("Cavities"),
CurvatureMode::Both => tr("Edges and cavities"),
CurvatureMode::Raw => tr("Raw curvature"),
}
}
/// One input of generator effect `id` on `layer`: what it reads (its mesh map unless `source` replaces it), a menu to replace it, and a button to read the mesh map again.
fn input_slot(app: &mut TextureCraftApp, ui: &mut Ui, (layer, id): (LayerId, u64), map: BakedMap, source: Option<&Source>, detail_sizes: bool) {
let tokens = Tokens::get(ui.ctx());
let input = map.id();
let current = match source {
None => trf("Mesh map: {map}", &[("map", &tr(baked_map_label(map)))]),
Some(Source::Image { name, .. }) => trf("Image: {name}", &[("name", name)]),
Some(Source::Uniform(_)) => tr("Uniform value").to_string(),
Some(Source::Anchor { anchor, channel }) => anchor_label(app, *anchor, *channel),
Some(Source::Procedural { .. }) => tr("Procedural").to_string(),
};
let group = ui.group(|ui| {
ui.horizontal(|ui| {
input_tile(app, ui, map, source);
ui.vertical(|ui| {
ui.label(RichText::new(tr(baked_map_label(map))).strong());
ui.label(RichText::new(&current).size(NOTE_FONT_SIZE).color(tokens.text_dim));
});
ui.with_layout(egui::Layout::right_to_left(egui::Align::Center), |ui| {
if source.is_some() && ui.button(ic::X).on_hover_text(tr("Read the mesh map again")).clicked() {
app.run("effect.set", json!({"effect": id, "input": input, "inputBaked": true}));
}
});
});
combo(ui, tr("Source"), current.clone(), |ui| {
let anchors = anchors_below(app, layer);
if ui.selectable_label(source.is_none(), tr("Mesh map")).clicked() {
app.run("effect.set", json!({"effect": id, "input": input, "inputBaked": true}));
}
if ui.selectable_label(matches!(source, Some(Source::Uniform(_))), tr("Uniform value")).clicked() {
app.run("effect.set", json!({"effect": id, "input": input, "inputValue": map.neutral()[0]}));
}
for (anchor, label) in &anchors {
if ui
.selectable_label(
matches!(source, Some(Source::Anchor { anchor: picked, .. }) if picked == anchor),
trf("Anchor: {name}", &[("name", label)]),
)
.clicked()
{
app.run("effect.set", json!({"effect": id, "input": input, "inputAnchor": anchor.0}));
}
}
if let Some(name) = image_menu(app, ui) {
app.run("effect.set", json!({"effect": id, "input": input, "inputImage": name}));
}
});
if let Some(Source::Uniform(value)) = source {
let mut value = value[0];
if let Some(merge) = slider_edit(ui, tr("Value"), &mut value, 0.0..=1.0, 2) {
app.run("effect.set", json!({"effect": id, "input": input, "inputValue": value, "merge": merge}));
}
}
if detail_sizes && map == BakedMap::Curvature && source.is_some_and(|source| !matches!(source, Source::Uniform(_))) {
ui.label(
RichText::new(tr("Detail sizes blur the mesh map, so a replaced curvature input is read at its own size only."))
.size(NOTE_FONT_SIZE)
.color(tokens.text_dim),
);
}
});
if let Some(name) = image_drop(ui, &group.response) {
app.run("effect.set", json!({"effect": id, "input": input, "inputImage": name}));
}
}
/// The picture of what an input reads: the image itself, the uniform value's gray, or the mesh map's swatch (as in the texture set's list).
fn input_tile(app: &mut TextureCraftApp, ui: &mut Ui, map: BakedMap, source: Option<&Source>) {
let tokens = Tokens::get(ui.ctx());
let (rect, _) = ui.allocate_exact_size(egui::vec2(INPUT_TILE_SIZE, INPUT_TILE_SIZE), egui::Sense::hover());
let painter = ui.painter();
let whole = egui::Rect::from_min_max(egui::pos2(0.0, 0.0), egui::pos2(1.0, 1.0));
match source {
Some(Source::Image { name, .. }) => match app.session.images.get(name) {
Some(image) => {
let texture = app.thumbs.image(ui.ctx(), name, image);
painter.image(texture.id(), rect, whole, egui::Color32::WHITE);
}
None => {
painter.rect_filled(rect, INPUT_TILE_ROUNDING, tokens.button);
}
},
Some(Source::Uniform(value)) => {
painter.rect_filled(rect, INPUT_TILE_ROUNDING, egui::Color32::from_gray((value[0].clamp(0.0, 1.0) * 255.0).round() as u8));
}
Some(Source::Anchor { .. } | Source::Procedural { .. }) => {
let glyph = if matches!(source, Some(Source::Anchor { .. })) { ic::ANCHOR } else { ic::MAGIC_WAND };
painter.rect_filled(rect, INPUT_TILE_ROUNDING, tokens.button);
painter.text(rect.center(), egui::Align2::CENTER_CENTER, glyph, egui::FontId::proportional(INPUT_TILE_ICON_SIZE), tokens.text_dim);
}
None => {
let baked = app.session.doc.baked.get(&app.session.ts()).is_some_and(|baked| baked.maps.contains_key(&map));
painter.rect_filled(rect, INPUT_TILE_ROUNDING, if baked { mesh_map_color(map) } else { tokens.button });
}
}
painter.rect_stroke(rect, INPUT_TILE_ROUNDING, egui::Stroke::new(1.0, tokens.button_border), egui::StrokeKind::Outside);
}
+12 -1
View File
@@ -20,6 +20,7 @@ pub mod export_templates;
pub mod file_dialogs;
mod filter_slot;
pub mod fonts;
mod generator_panel;
pub mod gpu;
pub mod i18n;
pub mod id_color_pick;
@@ -327,7 +328,7 @@ impl TextureCraftApp {
}
let total = sets.len();
self.bake = Some(BakeJob { queue: sets, current: None, total });
self.bake = Some(BakeJob { queue: sets, current: None, total, mesh_id: self.session.mesh_id });
}
/// Re-cook MaterialCraft material layer `layer` in the background. While one cook of the layer
@@ -393,6 +394,15 @@ impl TextureCraftApp {
return;
};
if job.mesh_id != self.session.mesh_id {
// The mesh was swapped under the job: stop it and drop its result.
if let Some(running) = &job.current {
running.progress.cancel.store(true, Ordering::Relaxed);
}
self.bake = None;
return;
}
ctx.request_repaint_after(std::time::Duration::from_millis(50));
if let Some(running) = &job.current {
let set_index = running.set_index;
@@ -673,6 +683,7 @@ impl eframe::App for TextureCraftApp {
self.poll_bake(ctx);
self.poll_resize(ctx);
self.poll_link_cooks(ctx);
self.thumbs.sync_images(&self.session.images, self.session.revision);
// The library shelf rescans when the window comes back (MaterialCraft may have sent a material)
let focused = ctx.input(|i| i.viewport().focused).unwrap_or(true);
if focused && !self.focused {
+7 -1
View File
@@ -206,7 +206,13 @@ mod tests {
let mut answers = HashMap::new();
let start = Instant::now();
while answers.len() < requests_sent && start.elapsed() < Duration::from_secs(120) {
// Instrumented orb baking can take several minutes on coverage runners.
let timeout = if std::env::var_os("LLVM_PROFILE_FILE").is_some() || std::env::var("RUSTFLAGS").is_ok_and(|f| f.contains("instrument-coverage")) {
Duration::from_secs(600)
} else {
Duration::from_secs(120)
};
while answers.len() < requests_sent && start.elapsed() < timeout {
answers.extend(worker.poll());
std::thread::sleep(Duration::from_millis(10));
}
+108 -19
View File
@@ -3,8 +3,10 @@
//! Smart masks, smart materials and hover previews use [`PreviewWorker`]
use std::collections::{HashMap, VecDeque};
use std::sync::{Arc, Weak};
use egui::{Color32, ColorImage, Painter, Pos2, Rect, TextureHandle, TextureOptions};
use texturecraft_engine::compose::{ImageRes, ImageStore};
use texturecraft_engine::core::ProceduralKind;
use texturecraft_engine::paint::presets::BrushPreset;
use texturecraft_engine::paint::{BrushAlpha, alphas};
@@ -26,6 +28,8 @@ const PROCEDURAL_PX: usize = 56;
const SWATCH_PX: usize = 64;
/// Image resource preview size in pixels
const IMAGE_PX: usize = 64;
/// Largest stencil preview dimension in pixels
const STENCIL_MAX_SIZE_PX: f32 = 1024.0;
/// Big hover previews kept at most (the least recently shown go first)
const BIG_PREVIEWS_KEPT: usize = 32;
@@ -34,7 +38,8 @@ const BIG_PREVIEWS_KEPT: usize = 32;
pub struct Thumbs {
/// Shelf thumbnails by [`ShelfPreview::key`]
shelf: HashMap<String, TextureHandle>,
images: HashMap<String, TextureHandle>,
images: HashMap<String, (Weak<ImageRes>, TextureHandle)>,
images_revision: Option<u64>,
/// (frame, thumbnails rendered in it)
budget: (u64, usize),
/// Renders the orb thumbnails and the big previews
@@ -49,34 +54,57 @@ pub struct Thumbs {
impl Thumbs {
/// A larger cached texture of an image resource for the stencil overlay (up to 1024 px)
pub fn stencil(&mut self, ctx: &egui::Context, name: &str, img: &texturecraft_engine::compose::ImageRes) -> TextureHandle {
pub fn stencil(&mut self, ctx: &egui::Context, name: &str, image: &Arc<ImageRes>) -> TextureHandle {
let key = format!("stencil:{name}");
if let Some(t) = self.images.get(&key) {
return t.clone();
if let Some((cached_image, texture)) = self.images.get(&key)
&& cached_image.ptr_eq(&Arc::downgrade(image))
{
return texture.clone();
}
let scale = (1024.0 / img.width.max(img.height).max(1) as f32).min(1.0);
let (w, h) = (((img.width as f32 * scale) as usize).max(1), ((img.height as f32 * scale) as usize).max(1));
let mut ci = ColorImage::filled([w, h], Color32::TRANSPARENT);
let scale = (STENCIL_MAX_SIZE_PX / image.width.max(image.height).max(1) as f32).min(1.0);
let (w, h) = (((image.width as f32 * scale) as usize).max(1), ((image.height as f32 * scale) as usize).max(1));
let mut color_image = ColorImage::filled([w, h], Color32::TRANSPARENT);
for y in 0..h {
for x in 0..w {
let s = img.sample((x as f32 + 0.5) / w as f32, (y as f32 + 0.5) / h as f32);
let enc = |v: f32| if img.srgb { (v.clamp(0.0, 1.0) * 255.0) as u8 } else { (linear_to_srgb(v) * 255.0) as u8 };
ci.pixels[y * w + x] = Color32::from_rgba_unmultiplied(enc(s[0]), enc(s[1]), enc(s[2]), (s[3].clamp(0.0, 1.0) * 255.0) as u8);
let sample = image.sample((x as f32 + 0.5) / w as f32, (y as f32 + 0.5) / h as f32);
let encode = |value: f32| {
if image.srgb { (value.clamp(0.0, 1.0) * 255.0) as u8 } else { (linear_to_srgb(value) * 255.0) as u8 }
};
color_image.pixels[y * w + x] =
Color32::from_rgba_unmultiplied(encode(sample[0]), encode(sample[1]), encode(sample[2]), (sample[3].clamp(0.0, 1.0) * 255.0) as u8);
}
}
let t = ctx.load_texture(key.clone(), ci, TextureOptions::LINEAR);
self.images.insert(key, t.clone());
t
let texture = ctx.load_texture(key.clone(), color_image, TextureOptions::LINEAR);
self.images.insert(key, (Arc::downgrade(image), texture.clone()));
texture
}
/// Cached preview of an image resource (64 px, letterboxed)
pub fn image(&mut self, ctx: &egui::Context, name: &str, img: &texturecraft_engine::compose::ImageRes) -> TextureHandle {
if let Some(t) = self.images.get(name) {
return t.clone();
pub fn image(&mut self, ctx: &egui::Context, name: &str, image: &Arc<ImageRes>) -> TextureHandle {
if let Some((cached_image, texture)) = self.images.get(name)
&& cached_image.ptr_eq(&Arc::downgrade(image))
{
return texture.clone();
}
let t = ctx.load_texture(format!("res_{name}"), image_preview(img, IMAGE_PX), TextureOptions::LINEAR);
self.images.insert(name.to_string(), t.clone());
t
let texture = ctx.load_texture(format!("res_{name}"), image_preview(image, IMAGE_PX), TextureOptions::LINEAR);
self.images.insert(name.to_string(), (Arc::downgrade(image), texture.clone()));
texture
}
/// Release previews for deleted or replaced resources after a session change
pub fn sync_images(&mut self, images: &ImageStore, revision: u64) {
if self.images_revision == Some(revision) {
return;
}
self.images_revision = Some(revision);
self.images.retain(|key, (cached_image, _)| {
let name = key.strip_prefix("stencil:").unwrap_or(key);
images.get(name).is_some_and(|image| cached_image.ptr_eq(&Arc::downgrade(image)))
});
}
/// Render within the frame budget; deferred thumbnails request a repaint
@@ -276,3 +304,64 @@ pub fn paint_alpha(p: &Painter, rect: Rect, a: BrushAlpha, hardness: f32) {
}
}
}
#[cfg(test)]
mod tests {
use std::sync::Arc;
use texturecraft_engine::compose::{ImageRes, ImageStore};
use super::Thumbs;
#[test]
fn replacing_an_image_rebuilds_its_preview() {
let context = egui::Context::default();
let mut thumbs = Thumbs::default();
let image = |value| Arc::new(ImageRes { width: 2, height: 2, rgba: vec![[value; 4]; 4], srgb: false });
let first_image = image(0.2);
let replacement_image = image(0.8);
let first = thumbs.image(&context, "sample.png", &first_image);
let second = thumbs.image(&context, "sample.png", &replacement_image);
assert_ne!(first.id(), second.id(), "a replaced resource must update its preview");
}
#[test]
fn removing_resources_releases_their_previews() {
let context = egui::Context::default();
let mut thumbs = Thumbs::default();
let mut images = ImageStore::new();
for index in 0..3 {
let name = format!("image-{index}");
images.insert(name, Arc::new(ImageRes { width: 2, height: 2, rgba: vec![[index as f32; 4]; 4], srgb: false }));
}
for (name, image) in &images {
drop(thumbs.image(&context, name, image));
}
let cached_pixel_bytes = |thumbs: &Thumbs| thumbs.images.values().map(|(_, texture)| texture.size()[0] * texture.size()[1] * 4).sum::<usize>();
let before_count = thumbs.images.len();
let before_pixel_bytes = cached_pixel_bytes(&thumbs);
images.remove("image-0");
images.remove("image-1");
thumbs.sync_images(&images, 1);
let after_count = thumbs.images.len();
let after_pixel_bytes = cached_pixel_bytes(&thumbs);
eprintln!("cached previews: {before_count} -> {after_count}; texture pixel bytes: {before_pixel_bytes} -> {after_pixel_bytes}");
assert_eq!((before_count, after_count), (3, 1));
assert!(after_pixel_bytes < before_pixel_bytes);
assert!(thumbs.images.contains_key("image-2"));
images.insert("image-3".into(), Arc::new(ImageRes { width: 2, height: 2, rgba: vec![[0.7; 4]; 4], srgb: false }));
drop(thumbs.image(&context, "image-3", &images["image-3"]));
thumbs.sync_images(&images, 2);
assert_eq!(thumbs.images.len(), 2);
images.clear();
thumbs.sync_images(&images, 3);
eprintln!("cached previews after clearing resources: {}", thumbs.images.len());
assert!(thumbs.images.is_empty());
}
}
+1 -1
View File
@@ -263,7 +263,7 @@ mod tests {
assert!(!safe_to_close(h.state()), "unsaved changes");
h.state_mut().session.modified = false;
h.state_mut().bake = Some(crate::BakeJob { queue: Vec::new(), current: None, total: 0 });
h.state_mut().bake = Some(crate::BakeJob { queue: Vec::new(), current: None, total: 0, mesh_id: 0 });
assert!(!safe_to_close(h.state()), "a bake");
h.state_mut().bake = None;
+2
View File
@@ -125,9 +125,11 @@ fn a_ready_result_waits_for_the_map_stream_to_close() {
result_sender.send(Ok(output)).unwrap();
let app = harness.state_mut();
app.start_bake(vec![0]);
let mesh_id = app.session.mesh_id;
app.bake = Some(BakeJob {
queue: Vec::new(),
total: 1,
mesh_id,
current: Some(RunningBake {
set_index: 0,
progress: Arc::new(Progress::new()),
+43
View File
@@ -0,0 +1,43 @@
//! A bake job belongs to the mesh it started on: when `file.changeMesh` (or a reimport) swaps
//! the mesh meanwhile, the job is cancelled and its result is dropped.
use std::sync::Arc;
use std::sync::atomic::Ordering;
use egui_kittest::Harness;
use texturecraft_engine::bake::Progress;
use texturecraft_ui_egui::{BakeJob, RunningBake, TextureCraftApp};
/// An app with a running bake job (its worker never answers) started on mesh `mesh_id`.
fn harness_with_job(mesh_id: impl FnOnce(u64) -> u64) -> (Harness<'static, TextureCraftApp>, Arc<Progress>) {
let session = texturecraft_engine::sample_session(256, 64).unwrap();
let mut h = Harness::builder().with_size(egui::vec2(1600.0, 960.0)).build_eframe(|cc| TextureCraftApp::new(cc, session));
h.run_steps(4);
let progress = Arc::new(Progress::new());
let (tx, receiver) = std::sync::mpsc::channel();
let (maps_tx, maps) = std::sync::mpsc::channel();
let id = mesh_id(h.state().session.mesh_id);
// Leak the sender so the channel stays empty instead of closed.
std::mem::forget(tx);
std::mem::forget(maps_tx);
let running =
RunningBake { set_index: 0, progress: progress.clone(), receiver, maps, maps_done: Arc::new(std::sync::atomic::AtomicUsize::new(0)), maps_total: 1 };
h.state_mut().bake = Some(BakeJob { queue: vec![], current: Some(running), total: 1, mesh_id: id });
(h, progress)
}
#[test]
fn a_job_on_a_swapped_mesh_is_cancelled_and_dropped() {
let (mut h, progress) = harness_with_job(|current| current + 1);
h.step();
assert!(h.state().bake.is_none(), "the job is dropped");
assert!(progress.cancel.load(Ordering::Relaxed), "and its worker is told to stop");
}
#[test]
fn a_job_on_the_current_mesh_keeps_running() {
let (mut h, progress) = harness_with_job(|current| current);
h.step();
assert!(h.state().bake.is_some(), "the job stays");
assert!(!progress.cancel.load(Ordering::Relaxed));
}
+95 -24
View File
@@ -1,4 +1,4 @@
//! Effect rows in the layer stack: dragging one reorders its stack.
//! Effect rows in the layer stack: dragging one reorders its stack, and its blend mode and opacity sit at its right.
use egui_kittest::Harness;
use egui_kittest::kittest::Queryable;
@@ -12,16 +12,16 @@ fn id(v: Value, key: &str) -> u64 {
}
/// Drag the row labelled `from` onto the upper (`below` false) or lower half of the row `to`.
fn drag(h: &mut Harness<'_, TextureCraftApp>, from: &str, to: &str, below: bool) {
let start = h.get_by_label(from).rect().center();
let r = h.get_by_label(to).rect();
let end = egui::pos2(r.center().x, if below { r.bottom() - 4.0 } else { r.top() + 4.0 });
h.drag_at(start);
h.run_steps(2);
h.hover_at(end);
h.run_steps(2);
h.drop_at(end);
h.run_steps(3);
fn drag(harness: &mut Harness<'_, TextureCraftApp>, from: &str, to: &str, below: bool) {
let start = harness.get_by_label(from).rect().center();
let row_rect = harness.get_by_label(to).rect();
let end = egui::pos2(row_rect.center().x, if below { row_rect.bottom() - 4.0 } else { row_rect.top() + 4.0 });
harness.drag_at(start);
harness.run_steps(2);
harness.hover_at(end);
harness.run_steps(2);
harness.drop_at(end);
harness.run_steps(3);
}
#[test]
@@ -32,17 +32,88 @@ fn dragging_an_effect_row_reorders_its_stack() {
|name: &str| id(execute(&mut session, "effect.add.filter", &json!({"target": "content", "filter": "invert", "name": name})).unwrap(), "effect");
let (a, b, c) = (add("Effect A"), add("Effect B"), add("Effect C"));
execute(&mut session, "layer.select", &json!({"layer": layer.0})).unwrap();
let mut h = Harness::builder().with_size(egui::vec2(1600.0, 1400.0)).build_eframe(|cc| TextureCraftApp::new(cc, session));
h.run_steps(4);
let order = |h: &Harness<'_, TextureCraftApp>| h.state().session.doc.project.layers[&layer].content_effects.iter().map(|e| e.id.0).collect::<Vec<_>>();
assert_eq!(order(&h), [a, b, c]);
// The rows list the top first: C, B, A. A dropped on C's upper half goes to the top.
drag(&mut h, "Effect A", "Effect C", false);
assert_eq!(order(&h), [b, c, a]);
// A dropped on B's lower half goes back to the bottom.
drag(&mut h, "Effect A", "Effect B", true);
assert_eq!(order(&h), [a, b, c]);
// C dropped on A's upper half lands between A and B.
drag(&mut h, "Effect C", "Effect A", false);
assert_eq!(order(&h), [a, c, b]);
let mut harness = Harness::builder().with_size(egui::vec2(1600.0, 1400.0)).build_eframe(|creation_context| TextureCraftApp::new(creation_context, session));
harness.run_steps(4);
let order =
|harness: &Harness<'_, TextureCraftApp>| harness.state().session.doc.project.layers[&layer].content_effects.iter().map(|e| e.id.0).collect::<Vec<_>>();
assert_eq!(order(&harness), [a, b, c]);
// Rows show C, B, A; dropping A above C moves it to the top
drag(&mut harness, "Effect A", "Effect C", false);
assert_eq!(order(&harness), [b, c, a]);
// Dropping A below B returns it to the bottom
drag(&mut harness, "Effect A", "Effect B", true);
assert_eq!(order(&harness), [a, b, c]);
// Dropping C above A places it between A and B
drag(&mut harness, "Effect C", "Effect A", false);
assert_eq!(order(&harness), [a, c, b]);
}
/// An effect row's blend mode menu and opacity field sit at its right, as on layer rows.
#[test]
fn an_effect_row_sets_its_blend_mode_and_opacity() {
let mut session = texturecraft_engine::sample_session(256, 64).unwrap();
let layer = LayerId(id(execute(&mut session, "layer.add.fill", &Value::Null).unwrap(), "layer"));
let effect = id(execute(&mut session, "effect.add.filter", &json!({"target": "content", "filter": "invert", "name": "Effect A"})).unwrap(), "effect");
execute(&mut session, "layer.select", &json!({"layer": layer.0})).unwrap();
let mut harness = Harness::builder().with_size(egui::vec2(1600.0, 1400.0)).build_eframe(|creation_context| TextureCraftApp::new(creation_context, session));
harness.run_steps(4);
let effect_of = |harness: &Harness<'_, TextureCraftApp>| harness.state().session.doc.project.layers[&layer].content_effects[0].clone();
assert_eq!(effect, effect_of(&harness).id.0);
// From the row's right edge: a 4-point gap, then the 82-point pair of mode menu and opacity field
let row = harness.get_by_label("Effect A").rect();
let pair_right = row.right() - 4.0;
let pair_left = pair_right - 82.0;
let mode_at = egui::pos2(pair_left + 20.0, row.center().y);
harness.drag_at(mode_at);
harness.drop_at(mode_at);
harness.run_steps(2);
harness.get_by_label("Multiply").click();
harness.run_steps(3);
assert_eq!(effect_of(&harness).blend, texturecraft_engine::core::BlendMode::Multiply);
let history = harness.state().session.history_labels().len();
let opacity_at = egui::pos2(pair_right - 20.0, row.center().y);
harness.drag_at(opacity_at);
harness.run_steps(2);
harness.hover_at(opacity_at - egui::vec2(100.0, 0.0));
harness.run_steps(2);
harness.drop_at(opacity_at - egui::vec2(100.0, 0.0));
harness.run_steps(3);
assert!(effect_of(&harness).opacity < 0.9, "dragging the field to the left lowers the opacity: {}", effect_of(&harness).opacity);
assert_eq!(harness.state().session.history_labels().len(), history + 1, "the whole drag is one undo step");
}
/// A drag whose first frame leaves the opacity unchanged still starts its own undo step: undo keeps the blend mode set before it
#[test]
fn an_opacity_drag_starting_without_a_change_is_its_own_undo_step() {
let mut session = texturecraft_engine::sample_session(256, 64).unwrap();
let layer = LayerId(id(execute(&mut session, "layer.add.fill", &Value::Null).unwrap(), "layer"));
let effect = id(execute(&mut session, "effect.add.filter", &json!({"target": "content", "filter": "invert", "name": "Effect A"})).unwrap(), "effect");
execute(&mut session, "effect.set", &json!({"effect": effect, "blend": "Multiply"})).unwrap();
execute(&mut session, "layer.select", &json!({"layer": layer.0})).unwrap();
let mut harness = Harness::builder().with_size(egui::vec2(1600.0, 1400.0)).build_eframe(|creation_context| TextureCraftApp::new(creation_context, session));
harness.run_steps(4);
let effect_of = |harness: &Harness<'_, TextureCraftApp>| harness.state().session.doc.project.layers[&layer].content_effects[0].clone();
let history = harness.state().session.history_labels().len();
let opacity_at = harness.get_by_label("Opacity of Effect A").rect().center();
// Equal right and down movement adds nothing to the value: the drag starts without a change
harness.drag_at(opacity_at);
harness.run_steps(2);
harness.hover_at(opacity_at + egui::vec2(8.0, 8.0));
harness.run_steps(2);
assert_eq!(effect_of(&harness).opacity, 1.0, "the drag started without changing the opacity");
harness.hover_at(opacity_at - egui::vec2(100.0, 0.0));
harness.run_steps(2);
harness.drop_at(opacity_at - egui::vec2(100.0, 0.0));
harness.run_steps(3);
assert!(effect_of(&harness).opacity < 0.9, "the drag lowered the opacity: {}", effect_of(&harness).opacity);
assert_eq!(harness.state().session.history_labels().len(), history + 1, "the drag is one new undo step");
harness.state_mut().session.undo().unwrap();
assert_eq!(effect_of(&harness).opacity, 1.0);
assert_eq!(effect_of(&harness).blend, texturecraft_engine::core::BlendMode::Multiply, "undo leaves the earlier blend change");
}
+118 -116
View File
@@ -1,5 +1,4 @@
//! The sliders of a selected effect (opacity, generator, levels…) apply what they were dragged
//! or clicked to.
//! A selected effect's sliders apply what they are dragged, clicked or typed to (a generator's global balance stands in for them all).
use egui::accesskit::Role;
use egui_kittest::Harness;
@@ -9,79 +8,82 @@ use texturecraft_engine::core::{EffectKind, LayerId};
use texturecraft_ui_egui::TextureCraftApp;
/// The sample session with its first generator effect selected, and that effect's id.
fn harness() -> (Harness<'static, TextureCraftApp>, LayerId) {
fn selected_generator() -> (Harness<'static, TextureCraftApp>, LayerId) {
let mut session = texturecraft_engine::sample_session(256, 64).unwrap();
let (layer, effect) = session
.doc
.project
.layers
.values()
.find_map(|l| {
let mask = l.mask.iter().flat_map(|m| m.effects.iter());
l.content_effects.iter().chain(mask).find(|e| matches!(e.kind, EffectKind::Generator(_))).map(|e| (l.id, e.id))
.find_map(|layer| {
let mask_effects = layer.mask.iter().flat_map(|mask| mask.effects.iter());
layer.content_effects.iter().chain(mask_effects).find(|effect| matches!(effect.kind, EffectKind::Generator(_))).map(|effect| (layer.id, effect.id))
})
.unwrap();
texturecraft_engine::execute(&mut session, "layer.select", &json!({"layer": layer.0, "target": effect.0})).unwrap();
let mut h = Harness::builder().with_size(egui::vec2(1600.0, 1400.0)).build_eframe(|cc| TextureCraftApp::new(cc, session));
h.run_steps(4);
(h, effect)
let mut harness = Harness::builder().with_size(egui::vec2(1600.0, 1400.0)).build_eframe(|creation_context| TextureCraftApp::new(creation_context, session));
harness.run_steps(4);
(harness, effect)
}
fn opacity(h: &Harness<'_, TextureCraftApp>, effect: LayerId) -> f32 {
h.state().session.doc.project.effect(effect).unwrap().1.opacity
fn balance(harness: &Harness<'_, TextureCraftApp>, effect: LayerId) -> f32 {
match &harness.state().session.doc.project.effect(effect).unwrap().1.kind {
EffectKind::Generator(generator) => generator.global.balance,
_ => panic!("a generator"),
}
}
/// The track under the slider labelled `label` (the row below the label).
fn track(h: &Harness<'_, TextureCraftApp>, label: &str) -> egui::Rect {
let l = h.get_by_label(label).rect();
egui::Rect::from_min_max(egui::pos2(l.left() + 6.0, l.bottom() + 6.0), egui::pos2(l.left() + 200.0, l.bottom() + 14.0))
fn track(harness: &Harness<'_, TextureCraftApp>, label: &str) -> egui::Rect {
let label_rect = harness.get_by_label(label).rect();
egui::Rect::from_min_max(egui::pos2(label_rect.left() + 6.0, label_rect.bottom() + 6.0), egui::pos2(label_rect.left() + 200.0, label_rect.bottom() + 14.0))
}
#[test]
fn dragging_the_effect_opacity_applies_it() {
let (mut h, effect) = harness();
assert_eq!(opacity(&h, effect), 1.0);
let t = track(&h, "Opacity");
h.drag_at(egui::pos2(t.right(), t.center().y));
h.run_steps(2);
h.hover_at(egui::pos2(t.left() + 20.0, t.center().y));
h.run_steps(2);
h.drop_at(egui::pos2(t.left() + 20.0, t.center().y));
h.run_steps(3);
assert!(opacity(&h, effect) < 0.5, "the dragged opacity applies: {}", opacity(&h, effect));
fn dragging_a_slider_applies_it() {
let (mut harness, effect) = selected_generator();
assert_eq!(balance(&harness, effect), 0.5);
let track_rect = track(&harness, "Global balance");
harness.drag_at(egui::pos2(track_rect.right(), track_rect.center().y));
harness.run_steps(2);
harness.hover_at(egui::pos2(track_rect.left() + 20.0, track_rect.center().y));
harness.run_steps(2);
harness.drop_at(egui::pos2(track_rect.left() + 20.0, track_rect.center().y));
harness.run_steps(3);
assert!(balance(&harness, effect) < 0.25, "the dragged balance applies: {}", balance(&harness, effect));
}
/// A generator slider applies while it is dragged (the texture follows the pointer), and the
/// whole drag is one undo step.
#[test]
fn dragging_a_generator_slider_applies_live_as_one_undo_step() {
let (mut h, effect) = harness();
let level = |h: &Harness<'_, TextureCraftApp>| match &h.state().session.doc.project.effect(effect).unwrap().1.kind {
EffectKind::Generator(g) => g.level,
let (mut harness, effect) = selected_generator();
let level = |harness: &Harness<'_, TextureCraftApp>| match &harness.state().session.doc.project.effect(effect).unwrap().1.kind {
EffectKind::Generator(generator) => generator.level,
_ => panic!("a generator"),
};
let steps = h.state().session.history_labels().len();
let t = track(&h, "Level");
let at = |x: f32| egui::pos2(t.left() + x, t.center().y);
h.drag_at(at(10.0));
h.run_steps(2);
let steps = harness.state().session.history_labels().len();
let track_rect = track(&harness, "Level");
let point_at = |x: f32| egui::pos2(track_rect.left() + x, track_rect.center().y);
harness.drag_at(point_at(10.0));
harness.run_steps(2);
let mut last = 0.0;
for x in [60.0, 160.0] {
h.hover_at(at(x));
h.run_steps(2);
assert!(level(&h) > last && level(&h) != 0.5, "the level follows the drag before it is released: {last} -> {}", level(&h));
last = level(&h);
harness.hover_at(point_at(x));
harness.run_steps(2);
assert!(level(&harness) > last && level(&harness) != 0.5, "the level follows the drag before it is released: {last} -> {}", level(&harness));
last = level(&harness);
}
h.drop_at(at(160.0));
h.run_steps(3);
assert_eq!(level(&h), last);
assert_eq!(h.state().session.history_labels().len(), steps + 1, "one undo step for the drag");
harness.drop_at(point_at(160.0));
harness.run_steps(3);
assert_eq!(level(&harness), last);
assert_eq!(harness.state().session.history_labels().len(), steps + 1, "one undo step for the drag");
}
/// The combo box in the row of the levels editor's Reset button.
fn channel_picker<'a>(h: &'a Harness<'_, TextureCraftApp>) -> egui_kittest::Node<'a> {
let row = h.get_by_label("Reset").rect().center().y;
h.get_all(by().role(Role::ComboBox)).find(|node| (node.rect().center().y - row).abs() < 4.0).unwrap()
fn channel_picker<'a>(harness: &'a Harness<'_, TextureCraftApp>) -> egui_kittest::Node<'a> {
let row = harness.get_by_label("Reset").rect().center().y;
harness.get_all(by().role(Role::ComboBox)).find(|node| (node.rect().center().y - row).abs() < 4.0).unwrap()
}
/// A content levels effect offers a channel for its histogram; picking one keeps it selected.
@@ -90,102 +92,102 @@ fn content_levels_pick_the_histogram_channel() {
let mut session = texturecraft_engine::sample_session(256, 64).unwrap();
texturecraft_engine::execute(&mut session, "layer.add.fill", &json!({"color": [0.5, 0.2, 0.1], "roughness": 0.6})).unwrap();
texturecraft_engine::execute(&mut session, "effect.add.levels", &json!({"target": "content"})).unwrap();
let mut h = Harness::builder().with_size(egui::vec2(1600.0, 1400.0)).build_eframe(|cc| TextureCraftApp::new(cc, session));
h.run_steps(4);
assert_eq!(channel_picker(&h).value().as_deref(), Some("Base color"), "the layer's first channel");
channel_picker(&h).click();
h.run_steps(2);
h.get_by_label("Roughness").click();
h.run_steps(3);
assert_eq!(channel_picker(&h).value().as_deref(), Some("Roughness"), "the picked channel stays");
let mut harness = Harness::builder().with_size(egui::vec2(1600.0, 1400.0)).build_eframe(|creation_context| TextureCraftApp::new(creation_context, session));
harness.run_steps(4);
assert_eq!(channel_picker(&harness).value().as_deref(), Some("Base color"), "the layer's first channel");
channel_picker(&harness).click();
harness.run_steps(2);
harness.get_by_label("Roughness").click();
harness.run_steps(3);
assert_eq!(channel_picker(&harness).value().as_deref(), Some("Roughness"), "the picked channel stays");
}
#[test]
fn clicking_the_effect_opacity_applies_it() {
let (mut h, effect) = harness();
let t = track(&h, "Opacity");
let at = egui::pos2(t.left() + 20.0, t.center().y);
h.drag_at(at);
h.drop_at(at);
h.run_steps(3);
assert!(opacity(&h, effect) < 0.5, "a click on the track applies: {}", opacity(&h, effect));
fn clicking_a_slider_track_applies_it() {
let (mut harness, effect) = selected_generator();
let track_rect = track(&harness, "Global balance");
let at = egui::pos2(track_rect.left() + 20.0, track_rect.center().y);
harness.drag_at(at);
harness.drop_at(at);
harness.run_steps(3);
assert!(balance(&harness, effect) < 0.25, "a click on the track applies: {}", balance(&harness, effect));
}
/// The number field in the row of the slider labelled `label`.
fn number_field<'a>(h: &'a Harness<'_, TextureCraftApp>, label: &str) -> egui_kittest::Node<'a> {
let row = h.get_by_label(label).rect().center().y;
h.get_all(by().role(Role::TextInput)).find(|n| (n.rect().center().y - row).abs() < 4.0).unwrap()
fn number_field<'a>(harness: &'a Harness<'_, TextureCraftApp>, label: &str) -> egui_kittest::Node<'a> {
let row = harness.get_by_label(label).rect().center().y;
harness.get_all(by().role(Role::TextInput)).find(|node| (node.rect().center().y - row).abs() < 4.0).unwrap()
}
/// Focus the opacity field and press `keys`, then type `text`, one key per frame like a person.
fn type_opacity(h: &mut Harness<'_, TextureCraftApp>, keys: &[egui::Key], text: &str) {
number_field(h, "Opacity").focus();
h.run_steps(2);
for k in keys {
h.key_press(*k);
h.run_steps(1);
/// Focus the balance field and press `keys`, then type `text`, one key per frame like a person.
fn type_balance(harness: &mut Harness<'_, TextureCraftApp>, keys: &[egui::Key], text: &str) {
number_field(harness, "Global balance").focus();
harness.run_steps(2);
for key in keys {
harness.key_press(*key);
harness.run_steps(1);
}
for c in text.chars() {
number_field(h, "Opacity").type_text(&c.to_string());
h.run_steps(1);
for character in text.chars() {
number_field(harness, "Global balance").type_text(&character.to_string());
harness.run_steps(1);
}
}
#[test]
fn a_value_typed_in_the_number_field_applies() {
let (mut h, effect) = harness();
let steps = h.state().session.history_labels().len();
type_opacity(&mut h, &[egui::Key::End, egui::Key::Backspace, egui::Key::Backspace, egui::Key::Backspace, egui::Key::Backspace], "0.25");
h.key_press(egui::Key::Enter);
h.run_steps(3);
assert_eq!(opacity(&h, effect), 0.25);
assert_eq!(h.state().session.history_labels().len(), steps + 1);
let (mut harness, effect) = selected_generator();
let steps = harness.state().session.history_labels().len();
type_balance(&mut harness, &[egui::Key::End, egui::Key::Backspace, egui::Key::Backspace, egui::Key::Backspace, egui::Key::Backspace], "0.25");
harness.key_press(egui::Key::Enter);
harness.run_steps(3);
assert_eq!(balance(&harness, effect), 0.25);
assert_eq!(harness.state().session.history_labels().len(), steps + 1);
}
/// Dragging the track while the number field has focus drops what was typed there: leaving the
/// field afterwards does not undo the drag.
#[test]
fn a_track_drag_drops_text_typed_in_the_number_field() {
let (mut h, effect) = harness();
type_opacity(&mut h, &[egui::Key::End, egui::Key::Backspace], "5");
let t = track(&h, "Opacity");
h.drag_at(egui::pos2(t.right(), t.center().y));
h.run_steps(2);
h.hover_at(egui::pos2(t.left() + 20.0, t.center().y));
h.run_steps(2);
h.drop_at(egui::pos2(t.left() + 20.0, t.center().y));
h.run_steps(2);
let dragged = opacity(&h, effect);
assert!(dragged < 0.5, "the drag applies: {dragged}");
// Leave whatever has focus: a click on empty space.
h.drag_at(egui::pos2(5.0, 1390.0));
h.drop_at(egui::pos2(5.0, 1390.0));
h.key_press(egui::Key::Enter);
h.run_steps(3);
assert_eq!(opacity(&h, effect), dragged, "the text typed before the drag stays dropped");
let (mut harness, effect) = selected_generator();
type_balance(&mut harness, &[egui::Key::End, egui::Key::Backspace], "5");
let track_rect = track(&harness, "Global balance");
harness.drag_at(egui::pos2(track_rect.right(), track_rect.center().y));
harness.run_steps(2);
harness.hover_at(egui::pos2(track_rect.left() + 20.0, track_rect.center().y));
harness.run_steps(2);
harness.drop_at(egui::pos2(track_rect.left() + 20.0, track_rect.center().y));
harness.run_steps(2);
let dragged = balance(&harness, effect);
assert!(dragged < 0.25, "the drag applies: {dragged}");
// Leave whatever has focus: a click on empty space
harness.drag_at(egui::pos2(5.0, 1390.0));
harness.drop_at(egui::pos2(5.0, 1390.0));
harness.key_press(egui::Key::Enter);
harness.run_steps(3);
assert_eq!(balance(&harness, effect), dragged, "the text typed before the drag stays dropped");
}
/// Leaving the number field without typing, or with Escape, keeps the value (not the rounded
/// text the field shows) and makes no undo step.
#[test]
fn leaving_the_number_field_unchanged_keeps_the_value() {
let (mut h, effect) = harness();
texturecraft_engine::execute(&mut h.state_mut().session, "effect.set", &json!({"effect": effect.0, "opacity": 0.333})).unwrap();
h.run_steps(2);
let steps = h.state().session.history_labels().len();
type_opacity(&mut h, &[], "");
h.key_press(egui::Key::Enter);
h.run_steps(3);
assert_eq!(opacity(&h, effect), 0.333, "left without typing");
type_opacity(&mut h, &[egui::Key::End, egui::Key::Backspace], "9");
assert_eq!(number_field(&h, "Opacity").value().as_deref(), Some("0.39"));
assert!(number_field(&h, "Opacity").is_focused());
h.key_press(egui::Key::Escape);
h.run_steps(3);
assert_eq!(opacity(&h, effect), 0.333);
// Typing the value it already has is no edit either.
type_opacity(&mut h, &[egui::Key::End, egui::Key::Backspace, egui::Key::Backspace, egui::Key::Backspace, egui::Key::Backspace], "0.333");
h.key_press(egui::Key::Enter);
h.run_steps(3);
assert_eq!(h.state().session.history_labels().len(), steps);
let (mut harness, effect) = selected_generator();
texturecraft_engine::execute(&mut harness.state_mut().session, "effect.set", &json!({"effect": effect.0, "balance": 0.333})).unwrap();
harness.run_steps(2);
let steps = harness.state().session.history_labels().len();
type_balance(&mut harness, &[], "");
harness.key_press(egui::Key::Enter);
harness.run_steps(3);
assert_eq!(balance(&harness, effect), 0.333, "left without typing");
type_balance(&mut harness, &[egui::Key::End, egui::Key::Backspace], "9");
assert_eq!(number_field(&harness, "Global balance").value().as_deref(), Some("0.39"));
assert!(number_field(&harness, "Global balance").is_focused());
harness.key_press(egui::Key::Escape);
harness.run_steps(3);
assert_eq!(balance(&harness, effect), 0.333);
// Typing the value it already has is no edit either
type_balance(&mut harness, &[egui::Key::End, egui::Key::Backspace, egui::Key::Backspace, egui::Key::Backspace, egui::Key::Backspace], "0.333");
harness.key_press(egui::Key::Enter);
harness.run_steps(3);
assert_eq!(harness.state().session.history_labels().len(), steps);
}
+141
View File
@@ -0,0 +1,141 @@
//! The generator panel: global adjustments, restore defaults and image inputs edit the selected generator.
use egui::Role;
use egui_kittest::Harness;
use egui_kittest::kittest::Queryable;
use serde_json::json;
use texturecraft_engine::core::{BakedMap, EffectKind, Generator, GeneratorKind, LayerId, Source};
use texturecraft_engine::{ViewMode, execute};
use texturecraft_ui_egui::TextureCraftApp;
use texturecraft_ui_egui::docking::Panel;
use texturecraft_ui_egui::theme::Brightness;
/// The sample session with a fill layer whose black mask holds a curvature generator, selected in the properties panel.
fn harness(render: bool) -> (Harness<'static, TextureCraftApp>, LayerId) {
let mut session = texturecraft_engine::sample_session(512, 256).unwrap();
session.active_set = 1;
session.camera.pitch = 0.5;
let layer = execute(&mut session, "layer.add.fill", &json!({"color": [0.8, 0.3, 0.1]})).unwrap()["layer"].as_u64().unwrap();
execute(&mut session, "mask.add.black", &json!({})).unwrap();
let effect = execute(&mut session, "effect.add.generator", &json!({"generator": "curvature"})).unwrap()["effect"].as_u64().unwrap();
session.view = ViewMode::Mask(LayerId(layer));
session.update();
let builder = Harness::builder().with_size(egui::vec2(1600.0, 2400.0));
let builder = if render { builder.wgpu() } else { builder };
let mut harness = builder.build_eframe(|context| TextureCraftApp::new(context, session));
harness.state_mut().ui.dock.close(Panel::Layers);
harness.state_mut().ui.dock.close(Panel::TextureSetSettings);
harness.state_mut().ui.dock.focus(Panel::Properties);
harness.run_steps(6);
(harness, LayerId(effect))
}
fn generator(harness: &Harness<'_, TextureCraftApp>, effect: LayerId) -> Generator {
match &harness.state().session.doc.project.effect(effect).unwrap().1.kind {
EffectKind::Generator(generator) => generator.clone(),
_ => panic!("expected a generator"),
}
}
/// Drags the track under slider `label` to the right.
fn drag_slider(harness: &mut Harness<'_, TextureCraftApp>, label: &str) {
harness.get_by_label(label).scroll_to_me();
harness.run_steps(3);
let rect = harness.get_by_label(label).rect();
let start = egui::pos2(rect.left() + 20.0, rect.bottom() + 10.0);
let end = start + egui::vec2(120.0, 0.0);
harness.drag_at(start);
harness.run_steps(2);
harness.hover_at(end);
harness.run_steps(2);
harness.drop_at(end);
harness.run_steps(3);
}
#[test]
fn global_blur_applies_as_one_undo_step() {
let (mut harness, effect) = harness(false);
let history = harness.state().session.history_labels().len();
drag_slider(&mut harness, "Global blur");
assert!(generator(&harness, effect).global.blur > 0.0);
assert_eq!(harness.state().session.history_labels().len(), history + 1);
harness.state_mut().session.undo().unwrap();
assert_eq!(generator(&harness, effect).global.blur, 0.0);
}
#[test]
fn restore_defaults_puts_the_generator_back_to_its_kind_defaults() {
let (mut harness, effect) = harness(false);
let edits = json!({"effect": effect.0, "level": 0.9, "blur": 0.5, "balance": 0.2, "resolutionFactor": -2, "seed": 99});
execute(&mut harness.state_mut().session, "effect.set", &edits).unwrap();
harness.run_steps(3);
harness.get_by_label("Restore defaults").scroll_to_me();
harness.run_steps(2);
harness.get_by_label("Restore defaults").click();
harness.run_steps(3);
assert_eq!(generator(&harness, effect), Generator::new(GeneratorKind::Curvature));
}
#[test]
fn changing_kind_in_the_panel_preserves_the_effect() {
let (mut harness, effect) = harness(false);
let history = harness.state().session.history_labels().len();
harness.get_all_by_role(Role::ComboBox).find(|node| node.value().as_deref() == Some("Curvature")).unwrap().click();
harness.run_steps(2);
harness.get_by_label("Dirt").click();
harness.run_steps(3);
assert_eq!(generator(&harness, effect).kind, GeneratorKind::Dirt);
assert_eq!(harness.state().session.history_labels().len(), history + 1);
}
#[test]
fn an_input_can_read_a_uniform_value_and_the_mesh_map_again() {
let (mut harness, effect) = harness(false);
harness.get_all_by_role(Role::ComboBox).find(|node| node.value().as_deref() == Some("Mesh map: Curvature")).unwrap().scroll_to_me();
harness.run_steps(3);
harness.get_all_by_role(Role::ComboBox).find(|node| node.value().as_deref() == Some("Mesh map: Curvature")).unwrap().click();
harness.run_steps(2);
harness.get_by_label("Uniform value").click();
harness.run_steps(3);
assert!(matches!(generator(&harness, effect).inputs.get(&BakedMap::Curvature), Some(Source::Uniform(_))));
harness.get_all_by_role(Role::ComboBox).find(|node| node.value().as_deref() == Some("Uniform value")).unwrap().click();
harness.run_steps(2);
harness.get_by_label("Mesh map").click();
harness.run_steps(3);
assert!(generator(&harness, effect).inputs.is_empty());
}
#[test]
#[ignore = "requires a GPU adapter and TC_UI_SNAPSHOTS"]
fn generator_panel_snapshots() {
let directory = std::path::PathBuf::from(std::env::var_os("TC_UI_SNAPSHOTS").expect("set TC_UI_SNAPSHOTS"));
std::fs::create_dir_all(&directory).unwrap();
let (mut harness, effect) = harness(true);
harness.run_steps(12);
harness.render().unwrap().save(directory.join("generator-panel-default.png")).unwrap();
for section in ["Attributes", "Resolution"] {
harness.get_by_label(section).click();
harness.run_steps(3);
}
harness.run_steps(6);
for (brightness, name) in [(Brightness::MediumDark, "medium"), (Brightness::Dark, "dark"), (Brightness::Light, "light")] {
harness.state_mut().ui.prefs.brightness = brightness;
harness.run_steps(3);
harness.render().unwrap().save(directory.join(format!("generator-panel-sections-open-{name}.png"))).unwrap();
}
harness.state_mut().ui.prefs.brightness = Brightness::MediumDark;
let edits = json!({"effect": effect.0, "blur": 0.3, "balance": 0.6, "contrast": 0.4, "resolutionFactor": -2});
execute(&mut harness.state_mut().session, "effect.set", &edits).unwrap();
harness.state_mut().session.update();
harness.run_steps(12);
harness.render().unwrap().save(directory.join("generator-panel-adjusted.png")).unwrap();
// The effect row with its blend mode and opacity, in the layer stack
harness.state_mut().ui.dock.focus(Panel::Layers);
harness.run_steps(12);
harness.render().unwrap().save(directory.join("generator-effect-row.png")).unwrap();
}
+3 -3
View File
@@ -58,9 +58,9 @@ fn mask_and_content_thumbnails_select_their_own_target() {
let at = thumb(&h, "Masked fill", false);
click(&mut h, at);
assert_eq!(h.state().session.target, StackTarget::Content, "the content thumbnail routes back");
// Clicking an effect row still selects that effect.
let r = h.get_by_label("Effect A").rect();
click(&mut h, egui::pos2(r.right() - 40.0, r.center().y));
// Clicking an effect row's name still selects that effect (its right end holds the blend mode and opacity)
let row = h.get_by_label("Effect A").rect();
click(&mut h, row.center());
assert!(matches!(h.state().session.target, StackTarget::Effect(_)));
}
+2
View File
@@ -1,6 +1,7 @@
//! One integration-test executable avoids linking the same dependencies for every feature.
//! Keep feature tests in their own modules; the standalone ui_snapshots.rs target remains available.
mod bake_job_mesh;
mod bake_mode;
mod brush_drag;
mod brush_section_reset;
@@ -14,6 +15,7 @@ mod file_dialogs;
mod fill_channel_image;
mod fill_projection_section;
mod filter_picker;
mod generator_panel;
mod history_panel;
mod layer_clipboard;
mod layer_rename;
+10 -1
View File
@@ -155,6 +155,15 @@ fn high_dpi_smart_material_hover_stays_within_the_renderer_limit() {
check_high_dpi_orb_hover(1, "Steel Painted Worn");
}
// Coverage instrumentation makes the 512px software-rendered preview substantially slower.
fn high_dpi_worker_timeout() -> Duration {
if std::env::var_os("LLVM_PROFILE_FILE").is_some() || std::env::var("RUSTFLAGS").is_ok_and(|f| f.contains("instrument-coverage")) {
Duration::from_secs(600)
} else {
WORKER_TIMEOUT
}
}
fn check_high_dpi_orb_hover(shelf_tab: usize, label: &str) {
use texturecraft_engine::orb_preview::MAX_PREVIEW_SIZE_PX;
@@ -166,7 +175,7 @@ fn check_high_dpi_orb_hover(shelf_tab: usize, label: &str) {
let expected = Some([MAX_PREVIEW_SIZE_PX; 2]);
let started = Instant::now();
while largest_drawn_texture(&harness, BIG_PREVIEW_SIZE) != expected && started.elapsed() < WORKER_TIMEOUT {
while largest_drawn_texture(&harness, BIG_PREVIEW_SIZE) != expected && started.elapsed() < high_dpi_worker_timeout() {
harness.run_steps(1);
std::thread::sleep(Duration::from_millis(20));
}
+2 -2
View File
@@ -121,10 +121,10 @@ on the CPU by `render::displace` from the composited height.
A fill can carry a `MaterialLink` (`core::layer`): a MaterialCraft graph whose cooked maps are the
fill's image sources. `engine::link_cmds` imports `.mcmat` files (`formats::mcmat`), keeps the
`.mcraft` package as a resource, and re-cooks by running `materialcraft-cli` with the link's
`.mcraft` or `.sbs` source as a resource, and re-cooks its named graph by running `materialcraft-cli` with the link's
values, the texture set's resolution and its baked mesh maps (`LinkJob::run`, on a worker thread
in the UI). Every cook stores its maps under fresh resource names, so undo, redo and the decoded
image cache never disagree. The apps share the file format and the command line, never code.
image cache never disagree. The apps share the `craft-mcmat` format library and the command line; neither depends on the other app.
## Commands and automation
+5 -4
View File
@@ -325,8 +325,9 @@ of a second.
A `.mcmat` portable material (MaterialCraft's format, read here by `formats::mcmat`; the manifest is
documented in MaterialCraft's `docs/control-protocol.md` § Portable materials) becomes a fill layer
whose channel sources are its cooked maps and whose `link` (shown by `project.inspect`) holds the
graph's exposed inputs, presets and image inputs. The apps share the format and the command line,
not code.
graph's exposed inputs, presets and image inputs. Both apps use the shared `craft-mcmat` container.
Versions 1 and 2 are accepted; version 1 contains a legacy JSON `.mcraft` source that current
MaterialCraft cannot reopen, so its cooked maps remain usable but re-cooking needs a compatible older version.
| Command | Params |
|---|---|
@@ -334,9 +335,9 @@ not code.
| `material.link.set` | `{layer?, id, value, cook?: true}`: a number, `[..]`, a bool, `"#rrggbb"` or a typed `{"t", "v"}`; re-cooks unless `cook: false` |
| `material.link.preset` | `{layer?, name, cook?: true}` |
| `material.link.cook` | `{layer?}`: re-cook at the texture set's resolution with its baked mesh maps (after a bake or a resize) |
| `material.link.saveSource` | `{layer?, path}`: the `.mcraft` package, to open in MaterialCraft |
| `material.link.saveSource` | `{layer?, path}`: the `.mcraft` or `.sbs` source, to open in MaterialCraft |
Re-cooks run `materialcraft-cli run <package> file.exportMaterial {path, size, values, inputs}`:
Re-cooks use `materialcraft-cli batch` to open the saved graph by name and run `file.exportMaterial` with its size, values and inputs:
`$MATERIALCRAFT_CLI`, else `materialcraft-cli` next to the TextureCraft executable, else on `PATH`
(the app is `$MATERIALCRAFT` / `materialcraft`). Baked maps feed graph input nodes whose identifier
matches the map's shared id (`ambientOcclusion`, `curvature`, `thickness`, `position`,
+2 -1
View File
@@ -80,7 +80,8 @@ Everything TextureCraft does today, by area. What's still missing is in [`ROADMA
- **Open** glTF/GLB, FBX (binary and ASCII), COLLADA, **USD** (usda, usdc, usdz), **Alembic**,
OBJ, PLY and STL, or a built-in mesh; UVs are generated when a mesh has none. A `.gltf`'s buffers
and images and a loose USD layer's textures are read from its folder and kept in the project.
Reimport a changed mesh and your painted strokes stay on the surface.
Reimport a changed mesh and your painted strokes stay on the surface. The
`file.changeMesh` command (trusted local command API and the control channel) moves the project onto a different mesh file and keeps its layers.
- **UDIM / UV tiles:** detected on import or switched on later, with a resolution per tile (blurs,
other filters and height-to-normal slopes keep their size in UV space at any tile resolution)
and one texture per tile on export (`$udim`).