Merge main into the empty-project startup changes

Preserve closed-session guards and project cleanup alongside the new layer, camera and layout controls. Update the menu-order regression for the merged catalog.
This commit is contained in:
chasse20 committed 2026-11-18 07:03:03 +00:00
commit 3939886c4b
167 files changed
+14815 -850

No files matched your search

+1 -1
View File
@@ -238,7 +238,7 @@ mod tests {
for id in ["file.open", "file.new", "file.save", "file.saveAs", "file.saveCopy", "file.exportTextures"] {
assert!(authorize_command(id, &json!({})).is_err(), "{id}");
}
for id in ["resource.import", "material.save", "material.load", "anything.new"] {
for id in ["resource.import", "material.save", "material.load", "mask.smart.create", "mask.smart.apply", "anything.new"] {
assert!(authorize_command(id, &json!({"path": "/etc/x"})).is_err(), "{id}");
assert!(authorize_command(id, &json!({"dir": "/etc"})).is_err(), "{id}");
}
+4 -2
View File
@@ -430,13 +430,15 @@ async fn mesh_files_export_bake_and_reimport_in_the_workspace() {
assert!(!textures.is_empty() && textures.iter().all(|t| base.join(t.as_str().unwrap()).is_file()), "{usda}");
assert_eq!(tool(&c, "mesh_export", json!({"path": "out/cube.glb"})).await["path"], "out/cube.glb");
assert!(base.join("out/cube.usda").is_file() && base.join("out/cube.glb").is_file());
// The loose usda arrives packaged with its textures.
// The loose usda arrives packaged with its textures
let high = tool(&c, "bake_mesh_add", json!({"path": "out/cube.usda"})).await;
assert_eq!(high["name"], "cube.usdz", "{high}");
let cage = tool(&c, "bake_mesh_add", json!({"path": "out/cube.glb", "cage": true})).await;
assert_eq!(cage["meshes"]["cage"]["name"], "cube.glb", "{cage}");
assert_eq!(inspect(&c).await["bakeMeshes"]["highPoly"][0]["name"], "cube.usdz");
// A built-in mesh has no file to re-read; a file does.
// A built-in mesh has no file to re-read; a file does
assert!(tool_err(&c, "mesh_reimport", json!({})).await.contains("built-in"));
tool(&c, "mesh_reimport", json!({"path": "out/cube.glb", "preserveStrokes": true})).await;
assert_eq!(inspect(&c).await["mesh"]["source"], "mesh.glb");
+565 -59
View File
@@ -21,7 +21,7 @@ use texturecraft_texel::{DilationMap, TILE, TILE_AREA, TileImage, from_u16, nois
use crate::below::{Band, BelowCache, Level, StackKey};
use crate::curvature_sizes::CurvatureSizes;
use crate::held_fields::HeldFields;
use crate::pattern::{Coords, decal_uv, image_samples, procedural, world_noise};
use crate::pattern::{Coords, decal_uv_symmetric, image_samples, procedural, world_noise};
use crate::store::{BakedMaps, ImageStore, PixelStore, decode};
const NCH: usize = Channel::ALL.len();
@@ -72,6 +72,10 @@ impl Stencil {
}
}
/// The channel under which a clone or smudge stroke on a mask carries its mask values (the mask
/// has no channels of its own; any scalar channel works).
pub const MASK_CHANNEL: Channel = Channel::Roughness;
/// The stroke being drawn, shown before it is committed.
#[derive(Clone, Debug)]
pub struct StrokePreview {
@@ -89,6 +93,8 @@ pub struct StrokePreview {
pub stencil: Option<Stencil>,
/// Clone and smudge: straight values per channel carried by the stroke (replace `values`).
pub carried: BTreeMap<Channel, TileImage>,
/// Mask coverage sampled by a mask pickup.
pub carried_mask: Option<TileImage>,
}
/// Everything the evaluator reads.
@@ -1269,8 +1275,8 @@ struct Texel<'a, 'b> {
stroke: f32,
/// `eval` stops when it reaches this layer.
stop: Option<LayerId>,
/// Stack values recorded by the anchor points evaluated so far.
anchors: Vec<(LayerId, Acc)>,
/// Stack values recorded by the anchor points evaluated so far; true marks a mask anchor (gray, not channel values).
anchors: Vec<(LayerId, Acc, bool)>,
/// Where `eval` takes layer masks and content from.
tape: Tape<'b>,
}
@@ -1394,8 +1400,10 @@ impl<'a, 'b> Texel<'a, 'b> {
/// position in the decal's frame (then sampled as UVs) and the decal's coverage.
fn projected<'p>(&mut self, proj: &'p Projection) -> (Coords, &'p Projection, f32) {
let c = self.coords();
let (lo, hi) = self.inp.bounds;
let center = (lo + hi) * 0.5;
match proj {
Projection::Decal(d) => match self.world().and_then(|p| decal_uv(d, p, c.nrm)) {
Projection::Decal(d) => match self.world().and_then(|p| decal_uv_symmetric(d, p, c.nrm, center)) {
Some((uv, w)) => (Coords { uv, ..c }, &DECAL_UV, w),
None => (c, &DECAL_UV, 0.0),
},
@@ -1417,11 +1425,37 @@ impl<'a, 'b> Texel<'a, 'b> {
w * image.map_or(1.0, |img| img.sample(c.uv.x, c.uv.y)[3].clamp(0.0, 1.0))
}
/// The stack value anchor point `anchor` recorded for `channel` (the channel default for an
/// anchor not evaluated yet)
fn anchored(&self, anchor: LayerId, channel: Channel) -> [f32; 3] {
let values = self.anchors.iter().rev().find(|(id, ..)| *id == anchor).and_then(|(_, values, _)| values.get(channel.index()).copied());
values.unwrap_or_else(|| channel.default_value())
}
/// Whether anchor point `anchor` sits in a mask, where every channel holds the mask's gray.
fn is_mask_anchor(&self, anchor: LayerId) -> bool {
self.anchors.iter().rev().find(|(id, ..)| *id == anchor).is_some_and(|(_, _, mask)| *mask)
}
/// The value `source` gives this texel through `projection`, read as a channel of `kind`
fn source(&mut self, source: &Source, projection: &Projection, kind: ChannelKind) -> [f32; 3] {
match source {
Source::Uniform(value) => *value,
Source::Procedural { pattern, low, high } => {
// A gradient map: on color channels the value picks a color along the stops
Source::Procedural { pattern, ramp, .. } if kind == ChannelKind::Color && !ramp.is_empty() => {
let (coords, projection, _) = self.projected(projection);
texturecraft_core::gradient(ramp, procedural(pattern, projection, &coords)).unwrap_or_default()
}
Source::Anchor { anchor, channel, ramp } if kind == ChannelKind::Color && !ramp.is_empty() => {
let value = self.anchored(*anchor, *channel);
// Signed values (height) span -1..1; a mask anchor's gray already spans 0..1 in every channel
let signed = channel.kind() == ChannelKind::Signed && !self.is_mask_anchor(*anchor);
let lightness = if signed { lum(value) * 0.5 + 0.5 } else { lum(value) };
texturecraft_core::gradient(ramp, lightness).unwrap_or_default()
}
Source::Procedural { pattern, low, high, .. } => {
let (coords, projection, _) = self.projected(projection);
let amount = procedural(pattern, projection, &coords);
mix3(*low, *high, amount)
@@ -1450,7 +1484,7 @@ impl<'a, 'b> Texel<'a, 'b> {
ChannelKind::Signed => [lum(rgb) * 2.0 - 1.0; 3],
}
}
Source::Anchor { anchor, channel } => self.anchor_value(*anchor, *channel, kind),
Source::Anchor { anchor, channel, .. } => self.anchor_value(*anchor, *channel, kind),
}
}
@@ -1458,8 +1492,7 @@ impl<'a, 'b> Texel<'a, 'b> {
/// where a scalar is needed). An anchor not evaluated yet (above this layer, hidden) reads the
/// channel default.
fn anchor_value(&self, anchor: LayerId, channel: Channel, kind: ChannelKind) -> [f32; 3] {
let value = self.anchors.iter().rev().find(|(id, _)| *id == anchor).and_then(|(_, channels)| channels.get(channel.index()).copied());
let value = value.unwrap_or_else(|| channel.default_value());
let value = self.anchored(anchor, channel);
let needs_gray = matches!(channel.kind(), ChannelKind::Color | ChannelKind::NormalMap) && matches!(kind, ChannelKind::Scalar | ChannelKind::Signed);
if needs_gray { [lum(value); 3] } else { value }
}
@@ -1615,7 +1648,9 @@ impl<'a, 'b> Texel<'a, 'b> {
painted *= 1.0 - stroke;
coverage *= 1.0 - stroke;
} else {
painted = preview.mask_value * stroke + painted * (1.0 - stroke);
// Clone and smudge show the values they carry instead of the mask gray
let deposited = preview.carried_mask.as_ref().map_or(preview.mask_value, |carried| from_u16(carried.get(self.x, self.y)[0]));
painted = deposited * stroke + painted * (1.0 - stroke);
coverage = stroke + coverage * (1.0 - stroke);
}
}
@@ -1655,7 +1690,7 @@ impl<'a, 'b> Texel<'a, 'b> {
}
// Every channel of a mask anchor reads the mask's gray
EffectKind::Anchor => self.anchors.push((effect.id, [[value.clamp(0.0, 1.0); 3]; NCH])),
EffectKind::Anchor => self.anchors.push((effect.id, [[value.clamp(0.0, 1.0); 3]; NCH], true)),
// Content-only effects
EffectKind::Material(_) => {}
@@ -1671,15 +1706,16 @@ impl<'a, 'b> Texel<'a, 'b> {
if self.stop == Some(n.id) {
return true;
}
let m = self.tape_mask(n);
match &n.content {
// A masked-out group still runs when it records anchors (they hold its inner
// stack) or may hold the stop layer.
// Masked-out groups still run when they record anchors or hold the stop layer
Content::Group(children) if m > 0.0 || n.has_anchor || self.stop.is_some() => {
let mut inner = *acc;
if self.eval(children, &mut inner) {
return true;
}
if m > 0.0 {
mix_group(acc, &inner, &n.chans, m);
}
@@ -1691,7 +1727,8 @@ impl<'a, 'b> Texel<'a, 'b> {
apply(acc, c, v, cov, m);
}
}
// Anchors inside the content stack: the stack with the content cut there.
// Anchors inside the content stack read the stack cut at that point
for (a, cut) in &n.anchors {
let rec = match (cut, before) {
(Some(k), Some(mut b)) => {
@@ -1704,14 +1741,14 @@ impl<'a, 'b> Texel<'a, 'b> {
}
_ => *acc,
};
self.anchors.push((*a, rec));
self.anchors.push((*a, rec, false));
}
continue;
}
_ => {}
}
for (a, _) in &n.anchors {
self.anchors.push((*a, *acc));
self.anchors.push((*a, *acc, false));
}
}
false
@@ -2325,6 +2362,7 @@ pub fn pad_tiles(out: &mut Composite, dmap: &DilationMap, tiles: &[(u32, u32)])
if (dmap.width, dmap.height) != (w, h) {
return written;
}
let (nx, ny) = (w.div_ceil(TILE) as i64, h.div_ceil(TILE) as i64);
let mut set = std::collections::BTreeSet::new();
for &(tx, ty) in tiles {
@@ -2341,8 +2379,8 @@ pub fn pad_tiles(out: &mut Composite, dmap: &DilationMap, tiles: &[(u32, u32)])
for img in out.channels.values_mut() {
let comps = img.comps();
let src: &TileImage = img;
// Padding writes only uncovered texels and reads only covered ones, so tiles pad
// independently (in parallel) from the unpadded image.
// Each tile pads from the original image, so parallel writes stay independent
let padded: Vec<((u32, u32), Vec<u16>)> = set
.par_iter()
.filter_map(|&(tx, ty)| {
@@ -2353,10 +2391,12 @@ pub fn pad_tiles(out: &mut Composite, dmap: &DilationMap, tiles: &[(u32, u32)])
if x >= w || y >= h {
continue;
}
let Some((sx, sy)) = dmap.source(x, y) else { continue };
if (sx, sy) == (x, y) {
continue;
}
let v = src.get(sx, sy);
let d = data.get_or_insert_with(|| src.tile(tx, ty).map_or_else(|| vec![0; TILE_AREA * comps], <[u16]>::to_vec));
let o = (ly * TILE + lx) as usize * comps;
@@ -2376,7 +2416,41 @@ pub fn pad_tiles(out: &mut Composite, dmap: &DilationMap, tiles: &[(u32, u32)])
written
}
/// The layer mask over the whole texture set as `0..=1` values, row by row from the top (the
/// orientation of the exported maps), `gbuf.width × gbuf.height` of them; black outside the mesh
/// Returns None without an enabled mask
pub fn mask_texels(inputs: &Inputs, id: LayerId) -> Option<Vec<f32>> {
let mask = layer_mask(inputs.project, id).filter(|mask| mask.enabled)?;
let channels = inputs.project.texture_set(inputs.ts).map(|set| set.channel_list()).unwrap_or_default();
let (width, height) = (inputs.gbuf.width, inputs.gbuf.height);
let coordinates = all_tiles(width, height);
// A hidden layer's mask is left out of the stack's preparation
prepare_mask_curvature_sizes(inputs, std::iter::once(mask));
let fields = neighbourhood_fields(inputs, &channels, &coordinates);
let width_usize = width as usize;
let tile_side = TILE as usize;
let mut output = vec![0.0f32; width_usize * height as usize];
// Write each tile into disjoint atlas rows without temporary tile buffers
output.par_chunks_mut(width_usize.max(1) * tile_side).enumerate().for_each(|(tile_y, rows)| {
for tile_x in 0..width.div_ceil(TILE) {
for (offset, value) in mask_tile(inputs, id, mask, &channels, &fields, (tile_x, tile_y as u32), 0..TILE_AREA) {
let x = tile_x as usize * tile_side + offset % tile_side;
if x < width_usize
&& let Some(destination) = rows.get_mut((offset / tile_side) * width_usize + x)
{
*destination = value;
}
}
}
});
Some(output)
}
/// The layer mask as a square grayscale image, using nearest texels and black outside the mesh
/// Keep preview tiles at 8 bits instead of retaining the export's full float atlas
/// Returns None without an enabled mask
pub fn mask_image(inputs: &Inputs, id: LayerId, size: u32) -> Option<Vec<u8>> {
let mask = layer_mask(inputs.project, id).filter(|mask| mask.enabled)?;
@@ -2388,27 +2462,35 @@ pub fn mask_image(inputs: &Inputs, id: LayerId, size: u32) -> Option<Vec<u8>> {
prepare_mask_curvature_sizes(inputs, std::iter::once(mask));
let fields = neighbourhood_fields(inputs, &channels, &coordinates);
let tiles: HashMap<(u32, u32), Vec<u8>> = coordinates
.par_iter()
.map(|&tile| {
let mut values = vec![0u8; TILE_AREA];
for (offset, value) in mask_tile(inputs, id, mask, &channels, &fields, tile, 0..TILE_AREA) {
if let Some(destination) = values.get_mut(offset) {
let width_usize = width as usize;
let tile_side = TILE as usize;
let mut atlas = vec![0u8; width_usize * height as usize];
// Write each tile row into disjoint atlas rows
atlas.par_chunks_mut(width_usize.max(1) * tile_side).enumerate().for_each(|(tile_y, rows)| {
for tile_x in 0..width.div_ceil(TILE) {
for (offset, value) in mask_tile(inputs, id, mask, &channels, &fields, (tile_x, tile_y as u32), 0..TILE_AREA) {
let x = tile_x as usize * tile_side + offset % tile_side;
if x < width_usize
&& let Some(destination) = rows.get_mut((offset / tile_side) * width_usize + x)
{
*destination = (value * 255.0 + 0.5) as u8;
}
}
(tile, values)
})
.collect();
}
});
let size = size.max(1);
if width == size && height == size {
return Some(atlas);
}
let mut output = vec![0u8; (size * size) as usize];
for y in 0..size {
for x in 0..size {
let sample_x = (u64::from(x) * u64::from(width) / u64::from(size)) as u32;
let sample_y = (u64::from(y) * u64::from(height) / u64::from(size)) as u32;
if let Some(tile) = tiles.get(&(sample_x / TILE, sample_y / TILE))
&& let Some(value) = tile.get(((sample_y % TILE) * TILE + sample_x % TILE) as usize)
if let Some(value) = atlas.get(sample_y as usize * width_usize + sample_x as usize)
&& let Some(destination) = output.get_mut((y * size + x) as usize)
{
*destination = *value;
@@ -2418,6 +2500,41 @@ pub fn mask_image(inputs: &Inputs, id: LayerId, size: u32) -> Option<Vec<u8>> {
Some(output)
}
/// The layer mask as one-component values at the texture set's full resolution over `tiles`
/// (uncovered texels read zero). Clone and smudge read it. Unlike [`mask_image`] it also reads a
/// disabled mask; None when the layer has no mask.
pub fn mask_values(inputs: &Inputs, id: LayerId, tiles: &[(u32, u32)]) -> Option<TileImage> {
let mut image = TileImage::new(inputs.gbuf.width, inputs.gbuf.height, 1);
mask_values_into(inputs, id, tiles, &mut image)?;
Some(image)
}
/// Evaluate requested tiles directly into the stroke's mask image.
pub fn mask_values_into(inputs: &Inputs, id: LayerId, tiles: &[(u32, u32)], image: &mut TileImage) -> Option<()> {
let mask = layer_mask(inputs.project, id)?;
let channels = inputs.project.texture_set(inputs.ts).ok()?.channel_list();
prepare_mask_curvature_sizes(inputs, std::iter::once(mask));
let fields = neighbourhood_fields(inputs, &channels, tiles);
let computed: Vec<((u32, u32), Vec<u16>)> = tiles
.par_iter()
.map(|&tile| {
let mut values = vec![0u16; TILE_AREA];
for (offset, value) in mask_tile(inputs, id, mask, &channels, &fields, tile, 0..TILE_AREA) {
if let Some(destination) = values.get_mut(offset) {
*destination = to_u16(value.clamp(0.0, 1.0));
}
}
(tile, values)
})
.collect();
for ((tx, ty), values) in computed {
image.set_tile(tx, ty, Some(std::sync::Arc::new(values)));
}
Some(())
}
/// Mask values at texture-set coordinates, in request order; None without an enabled mask
/// Uncovered and out-of-range texels read zero; neighbourhood filters also evaluate surrounding texels
pub fn mask_at(inputs: &Inputs, id: LayerId, texels: &[(u32, u32)]) -> Option<Vec<f32>> {
@@ -2823,14 +2940,15 @@ mod tests {
let id = f.project.alloc_id();
let l = Layer::new(id, "Paint", LayerKind::Paint, &[Channel::BaseColor]);
f.project.insert_layer(0, l, None, false).unwrap();
// Half-covered red texel: premul (0.5, 0, 0), coverage 0.5.
// Half-covered red texel has premultiplied color and 0.5 coverage
let img = f.pixels.layer_mut(id, Channel::BaseColor, (64, 64));
img.set(3, 3, &[to_u16(0.5), 0, 0, to_u16(0.5)]);
let out = run(&f, None);
assert!(close(out.value(Channel::BaseColor, 3, 3), [0.75, 0.25, 0.25]));
assert!(close(out.value(Channel::BaseColor, 4, 3), [0.5; 3]));
// A live stroke painting blue at full alpha on texel (4, 3).
// A live stroke paints blue at full alpha on texel (4, 3)
let mut alpha = TileImage::new(64, 64, 1);
alpha.set(4, 3, &[to_u16(1.0)]);
let pv = StrokePreview {
@@ -2842,11 +2960,12 @@ mod tests {
mask_value: 1.0,
stencil: None,
carried: BTreeMap::new(),
carried_mask: None,
};
let out = run(&f, Some(&pv));
assert!(close(out.value(Channel::BaseColor, 4, 3), [0.0, 0.0, 1.0]));
// A black mask hides the layer.
// A black mask hides the layer
f.project.layer_mut(id).unwrap().mask = Some(Mask::new(MaskBackground::Black));
let out = run(&f, None);
assert!(close(out.value(Channel::BaseColor, 3, 3), [0.5; 3]));
@@ -2861,7 +2980,7 @@ mod tests {
let pattern = Procedural::new(ProceduralKind::Checker);
mask.effects.push(Effect::new(
eid,
EffectKind::Fill { source: Source::Procedural { pattern, low: [0.0; 3], high: [1.0; 3] }, projection: Projection::default() },
EffectKind::Fill { source: Source::Procedural { pattern, low: [0.0; 3], high: [1.0; 3], ramp: Vec::new() }, projection: Projection::default() },
));
f.project.layer_mut(id).unwrap().mask = Some(mask);
let out = run(&f, None);
@@ -2911,7 +3030,7 @@ mod tests {
let pattern = Procedural::new(ProceduralKind::Checker);
mask.effects.push(Effect::new(
effect,
EffectKind::Fill { source: Source::Procedural { pattern, low: [0.0; 3], high: [1.0; 3] }, projection: Projection::default() },
EffectKind::Fill { source: Source::Procedural { pattern, low: [0.0; 3], high: [1.0; 3], ramp: Vec::new() }, projection: Projection::default() },
));
fixture.project.layer_mut(layer).unwrap().mask = Some(mask);
@@ -2928,6 +3047,51 @@ mod tests {
assert!(assert_sparse_mask_matches_image(&fixture, layer, &texels).is_none());
}
#[test]
fn mask_image_resamples_a_non_square_atlas() {
let mut fixture = fixture();
fixture.gbuf = UvGBuffer::new(&fixture.mesh, 0, 128, 64);
fixture.project.texture_sets[0].resolution = 128;
let layer = fill_layer(&mut fixture.project, [1.0; 3], 1.0);
let effect = fixture.project.alloc_id();
let mut mask = Mask::new(MaskBackground::Black);
mask.effects.push(Effect::new(
effect,
EffectKind::Fill {
source: Source::Procedural { pattern: Procedural::new(ProceduralKind::Checker), low: [0.0; 3], high: [1.0; 3], ramp: Vec::new() },
projection: Projection::default(),
},
));
fixture.project.layer_mut(layer).unwrap().mask = Some(mask);
let images = ImageStore::default();
let inputs = Inputs {
project: &fixture.project,
ts: 0,
mesh: &fixture.mesh,
gbuf: &fixture.gbuf,
pixels: &fixture.pixels,
baked: &fixture.baked,
block_scales: fixture.project.texture_sets[0].block_scales(),
preview: None,
images: &images,
bounds: fixture.mesh.bounds(),
};
let sampled_texels: Vec<_> = (0..64).flat_map(|y| (0..64).map(move |x| (x * 2, y))).collect();
let preview = mask_image(&inputs, layer, 64).unwrap();
let sparse = mask_at(&inputs, layer, &sampled_texels).unwrap();
let atlas = mask_texels(&inputs, layer).unwrap();
assert_eq!(preview.len(), 64 * 64);
assert_eq!(atlas.len(), 128 * 64);
assert!(preview.contains(&0));
assert!(preview.contains(&255));
for ((&preview_value, &sparse_value), &(x, y)) in preview.iter().zip(&sparse).zip(&sampled_texels) {
assert!((f32::from(preview_value) / 255.0 - sparse_value).abs() <= 0.5 / 255.0 + 1e-6);
assert!((atlas[(y * 128 + x) as usize] - sparse_value).abs() <= 1e-6);
}
}
#[test]
fn mask_at_ignores_out_of_range_texels_before_resampling_paint() {
let mut fixture = fixture();
@@ -2953,13 +3117,16 @@ mod tests {
let lower = fill_layer(&mut fixture.project, [0.0; 3], 1.0);
let LayerKind::Fill(fill) = &mut fixture.project.layer_mut(lower).unwrap().kind else { panic!("expected a fill layer") };
fill.sources.insert(Channel::BaseColor, Source::Procedural { pattern: Procedural::new(ProceduralKind::Checker), low: [0.0; 3], high: [1.0; 3] });
fill.sources.insert(
Channel::BaseColor,
Source::Procedural { pattern: Procedural::new(ProceduralKind::Checker), low: [0.0; 3], high: [1.0; 3], ramp: Vec::new() },
);
let anchor = content_fx(&mut fixture, lower, EffectKind::Anchor);
let upper = fill_layer(&mut fixture.project, [1.0; 3], 1.0);
let mut mask = Mask::new(MaskBackground::Black);
mask.effects.push(Effect::new(
fixture.project.alloc_id(),
EffectKind::Fill { source: Source::Anchor { anchor, channel: Channel::BaseColor }, projection: Projection::default() },
EffectKind::Fill { source: Source::Anchor { anchor, channel: Channel::BaseColor, ramp: Vec::new() }, projection: Projection::default() },
));
fixture.project.layer_mut(upper).unwrap().mask = Some(mask.clone());
let texels: Vec<_> = (0..128).map(|x| (x, 63)).collect();
@@ -2981,7 +3148,7 @@ mod tests {
fixture.gbuf = UvGBuffer::new(&fixture.mesh, 0, 128, 128);
fixture.project.texture_sets[0].resolution = 128;
let layer = fill_layer(&mut fixture.project, [1.0; 3], 1.0);
let checker = Source::Procedural { pattern: Procedural::new(ProceduralKind::Checker), low: [0.0; 3], high: [1.0; 3] };
let checker = Source::Procedural { pattern: Procedural::new(ProceduralKind::Checker), low: [0.0; 3], high: [1.0; 3], ramp: Vec::new() };
let warp = Filter::DirectionalWarp { intensity: 256.0, angle: 90.0, scale: 4.0, seed: 3 };
let texels: Vec<_> = (0..128).map(|x| (x, 63)).collect();
let mut masked = |filters: &[Filter]| {
@@ -3006,7 +3173,10 @@ mod tests {
let layer = fill_layer(&mut fixture.project, [0.0; 3], 1.0);
let LayerKind::Fill(fill) = &mut fixture.project.layer_mut(layer).unwrap().kind else { panic!("expected a fill layer") };
fill.sources.insert(Channel::BaseColor, Source::Procedural { pattern: Procedural::new(ProceduralKind::Checker), low: [0.0; 3], high: [1.0; 3] });
fill.sources.insert(
Channel::BaseColor,
Source::Procedural { pattern: Procedural::new(ProceduralKind::Checker), low: [0.0; 3], high: [1.0; 3], ramp: Vec::new() },
);
let warp = Filter::DirectionalWarp { intensity: 256.0, angle: 90.0, scale: 4.0, seed: 3 };
let warp_effect = content_fx(&mut fixture, layer, EffectKind::Filter(warp));
let row = |fixture: &Fixture| -> Vec<f32> {
@@ -3101,7 +3271,7 @@ mod tests {
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 checker = Source::Procedural { pattern: Procedural::new(ProceduralKind::Checker), low: [0.0; 3], high: [1.0; 3], ramp: Vec::new() };
let below = Effect::new(fixture.project.alloc_id(), EffectKind::Fill { source: checker, projection: Projection::default() });
let mut generator = ridge_generator();
generator.global.blur = blur;
@@ -3235,7 +3405,7 @@ mod tests {
let (e1, e2) = (f.project.alloc_id(), f.project.alloc_id());
mask.effects.push(Effect::new(
e1,
EffectKind::Fill { source: Source::Procedural { pattern, low: [0.0; 3], high: [1.0; 3] }, projection: Projection::default() },
EffectKind::Fill { source: Source::Procedural { pattern, low: [0.0; 3], high: [1.0; 3], ramp: Vec::new() }, projection: Projection::default() },
));
f.project.layer_mut(id).unwrap().mask = Some(mask.clone());
let hard: Vec<f32> = (0..64).map(|x| run(&f, None).value(Channel::BaseColor, x, 20)[0]).collect();
@@ -3321,7 +3491,10 @@ soft {soft:?}"
let mut f = fixture();
let id = f.project.alloc_id();
let mut fill = Fill::default();
fill.sources.insert(Channel::Roughness, Source::Procedural { pattern: Procedural::new(ProceduralKind::Checker), low: [0.0; 3], high: [1.0; 3] });
fill.sources.insert(
Channel::Roughness,
Source::Procedural { pattern: Procedural::new(ProceduralKind::Checker), low: [0.0; 3], high: [1.0; 3], ramp: Vec::new() },
);
f.project.insert_layer(0, Layer::new(id, "F", LayerKind::Fill(fill), &[Channel::Roughness]), None, false).unwrap();
let row = |f: &Fixture| {
let out = run(f, None);
@@ -3337,7 +3510,7 @@ soft {soft:?}"
#[test]
fn high_pass_edge_detect_directional_warp_grayscale_and_normal_invert() {
// Uniform content: high pass is mid gray (0 for height), edge detect black.
// Uniform content gives mid gray high pass and black edge detection
let mut f = fixture();
let id = fill_layer(&mut f.project, [1.0, 0.0, 0.0], 0.2);
let hp = content_fx(&mut f, id, EffectKind::Filter(Filter::HighPass { radius: 64.0 }));
@@ -3347,11 +3520,15 @@ soft {soft:?}"
f.project.layer_mut(id).unwrap().content_effects.retain(|e| e.id != hp);
content_fx(&mut f, id, EffectKind::Filter(Filter::EdgeDetect { width: 64.0 }));
assert!(close(run(&f, None).value(Channel::Roughness, 30, 30), [0.0; 3]));
// A checker: its borders light up, the middle of its cells stays black.
// A checker's borders light up while cell interiors stay black
let mut f = fixture();
let id = f.project.alloc_id();
let mut fill = Fill::default();
fill.sources.insert(Channel::Roughness, Source::Procedural { pattern: Procedural::new(ProceduralKind::Checker), low: [0.0; 3], high: [1.0; 3] });
fill.sources.insert(
Channel::Roughness,
Source::Procedural { pattern: Procedural::new(ProceduralKind::Checker), low: [0.0; 3], high: [1.0; 3], ramp: Vec::new() },
);
f.project.insert_layer(0, Layer::new(id, "F", LayerKind::Fill(fill), &[Channel::Roughness]), None, false).unwrap();
let plain = run(&f, None);
let edges = content_fx(&mut f, id, EffectKind::Filter(Filter::EdgeDetect { width: 32.0 }));
@@ -3364,12 +3541,14 @@ soft {soft:?}"
let warped = run(&f, None);
let differs = (0..64).any(|y| (0..64).any(|x| (warped.value(Channel::Roughness, x, y)[0] - plain.value(Channel::Roughness, x, y)[0]).abs() > 0.2));
assert!(differs, "the warp moves the checker");
// Point filters.
// Point filters
assert!(close(Filter::Grayscale.point(ChannelKind::Color, [1.0, 0.0, 0.0]).unwrap(), [lum([1.0, 0.0, 0.0]); 3]));
assert_eq!(Filter::Grayscale.point(ChannelKind::Scalar, [0.3; 3]), Some([0.3; 3]));
assert_eq!(Filter::NormalInvert.point(ChannelKind::NormalMap, [0.5, 0.25, 1.0]), Some([0.5, 0.75, 1.0]));
assert_eq!(Filter::NormalInvert.point(ChannelKind::Color, [0.5, 0.25, 1.0]), Some([0.5, 0.25, 1.0]));
// Replace color: near colors shift (keeping their offset), far ones and scalars stay.
// Replace color shifts near colors while far colors and scalars stay
let rc = Filter::ReplaceColor { from: [0.8, 0.1, 0.1], to: [0.1, 0.1, 0.8], tolerance: 0.1, softness: 0.1 };
assert!(close(rc.point(ChannelKind::Color, [0.85, 0.1, 0.1]).unwrap(), [0.15, 0.1, 0.8]));
assert!(close(rc.point(ChannelKind::Color, [0.1, 0.8, 0.1]).unwrap(), [0.1, 0.8, 0.1]));
@@ -3383,7 +3562,10 @@ soft {soft:?}"
let checker = |f: &mut Fixture| {
let id = f.project.alloc_id();
let mut fill = Fill::default();
fill.sources.insert(Channel::Roughness, Source::Procedural { pattern: Procedural::new(ProceduralKind::Checker), low: [0.0; 3], high: [1.0; 3] });
fill.sources.insert(
Channel::Roughness,
Source::Procedural { pattern: Procedural::new(ProceduralKind::Checker), low: [0.0; 3], high: [1.0; 3], ramp: Vec::new() },
);
f.project.insert_layer(0, Layer::new(id, "F", LayerKind::Fill(fill), &[Channel::Roughness]), None, false).unwrap();
id
};
@@ -3394,20 +3576,23 @@ soft {soft:?}"
let mut f = fixture();
let id = checker(&mut f);
let plain = values(&f);
// Bevel: never above the shape, and its edges become ramps.
// Bevel stays below the shape and turns edges into ramps
let fx = content_fx(&mut f, id, EffectKind::Filter(Filter::Bevel { width: 128.0 }));
let bevel = values(&f);
let mids = |v: &[f32]| v.iter().filter(|x| **x > 0.05 && **x < 0.95).count();
assert!(bevel.iter().zip(&plain).all(|(b, p)| *b <= p + 1e-4 && *b >= 0.0), "a bevel only lowers values");
assert!(mids(&bevel) > mids(&plain) + 64, "{} vs {}", mids(&bevel), mids(&plain));
// Mosaic: fewer changes from one texel to the next.
// Mosaic reduces changes between adjacent texels
f.project.layer_mut(id).unwrap().content_effects.retain(|e| e.id != fx);
let fx = content_fx(&mut f, id, EffectKind::Filter(Filter::Mosaic { size: 768.0 }));
let mosaic = values(&f);
let steps = |v: &[f32]| v.windows(2).filter(|w| (w[0] - w[1]).abs() > 0.01).count();
assert!(steps(&mosaic) < steps(&plain), "{} vs {}", steps(&mosaic), steps(&plain));
assert!(mosaic.iter().all(|v| (0.0..=1.0).contains(v)));
// Glow on uniform content adds its own blur: 0.2 + 0.2.
// Glow on uniform content adds its own blur
f.project.layer_mut(id).unwrap().content_effects.retain(|e| e.id != fx);
let mut f = fixture();
let id = fill_layer(&mut f.project, [0.1; 3], 0.2);
@@ -3426,7 +3611,8 @@ soft {soft:?}"
(out.value(Channel::BaseColor, 30, 30), out.value(Channel::Roughness, 30, 30))
};
let n = primitives::plane(2.0, 2).normals[0];
// Facing the light: ambient + light = 1 (unchanged); facing away: ambient only.
// Facing the light adds illumination; facing away keeps ambient only
let (toward, rough) = lit(if n.y > 0.0 { 90.0 } else { -90.0 });
assert!(close(toward, [0.5; 3]) && close(rough, [0.3; 3]), "{toward:?} {rough:?}");
let (away, _) = lit(if n.y > 0.0 { -90.0 } else { 90.0 });
@@ -3439,7 +3625,8 @@ soft {soft:?}"
#[test]
fn geometry_masks_show_layers_on_chosen_parts_only() {
let mut f = fixture();
// Two parts of the plane's one material: the first half of its triangles and the rest.
// The plane's material spans both triangle groups
let n = f.mesh.indices.len() as u32 / 6 * 3;
f.mesh.submeshes = vec![
texturecraft_geom::SubMesh { name: "Lid".into(), material: 0, start: 0, count: n },
@@ -3469,13 +3656,15 @@ soft {soft:?}"
material.sources.insert(Channel::Roughness, Source::Uniform([0.2; 3]));
content_fx(&mut f, id, EffectKind::Material(material));
let paint = content_fx(&mut f, id, EffectKind::Paint);
// Roughness 0.9 painted at half coverage (premultiplied).
// Roughness 0.9 is painted at half coverage
f.pixels.layer_mut(paint, Channel::Roughness, (64, 64)).set(3, 3, &[to_u16(0.45), to_u16(0.5)]);
let out = run(&f, None);
assert!(close(out.value(Channel::Roughness, 10, 10), [0.2; 3]), "the fill effect covers the empty paint layer");
assert!(close(out.value(Channel::Roughness, 3, 3), [0.55; 3]), "{:?}", out.value(Channel::Roughness, 3, 3));
assert!(close(out.value(Channel::BaseColor, 3, 3), [0.5; 3]), "channels without a source stay untouched");
// Flattening bakes the content effects in.
// Flattening bakes in the content effects
let images = Default::default();
let inp = Inputs {
project: &f.project,
@@ -3506,15 +3695,17 @@ soft {soft:?}"
let anchor = content_fx(&mut f, low, EffectKind::Anchor);
let top = fill_layer(&mut f.project, [1.0; 3], 0.5);
let mut mask = Mask::new(MaskBackground::Black);
let source = Source::Anchor { anchor, channel: Channel::Height };
let source = Source::Anchor { anchor, channel: Channel::Height, ramp: Vec::new() };
mask.effects.push(Effect::new(f.project.alloc_id(), EffectKind::Fill { source, projection: Projection::default() }));
f.project.layer_mut(top).unwrap().mask = Some(mask.clone());
assert!(close(run(&f, None).value(Channel::BaseColor, 5, 5), [0.7; 3]));
// Under a blur the anchor is read by the field pre-pass too: a flat height stays flat.
// The field pre-pass reads anchors under blur, preserving flat height
mask.effects.push(Effect::new(f.project.alloc_id(), EffectKind::Filter(Filter::Blur { radius: 32.0 })));
f.project.layer_mut(top).unwrap().mask = Some(mask);
assert!(close(run(&f, None).value(Channel::BaseColor, 5, 5), [0.7; 3]));
// An anchor above its reader is not evaluated yet: it reads the channel default (0).
// An anchor above its reader is not evaluated yet, so it reads the channel default
f.project.move_layer(low, 1).unwrap();
assert!(close(run(&f, None).value(Channel::BaseColor, 5, 5), [0.5; 3]));
}
@@ -3523,7 +3714,7 @@ soft {soft:?}"
fn anchor_reader(fixture: &mut Fixture, anchor: LayerId) -> LayerId {
let top = fill_layer(&mut fixture.project, [1.0; 3], 0.5);
let mut mask = Mask::new(MaskBackground::Black);
let source = Source::Anchor { anchor, channel: Channel::Roughness };
let source = Source::Anchor { anchor, channel: Channel::Roughness, ramp: Vec::new() };
mask.effects.push(Effect::new(fixture.project.alloc_id(), EffectKind::Fill { source, projection: Projection::default() }));
fixture.project.layer_mut(top).unwrap().mask = Some(mask);
top
@@ -3564,7 +3755,7 @@ soft {soft:?}"
let lower = fill_layer(&mut fixture.project, [0.0; 3], 1.0);
let anchor = fixture.project.alloc_id();
let mut mask = Mask::new(MaskBackground::Black);
let checker = Source::Procedural { pattern: Procedural::new(ProceduralKind::Checker), low: [0.0; 3], high: [1.0; 3] };
let checker = Source::Procedural { pattern: Procedural::new(ProceduralKind::Checker), low: [0.0; 3], high: [1.0; 3], ramp: Vec::new() };
mask.effects.push(Effect::new(fixture.project.alloc_id(), EffectKind::Fill { source: checker, projection: Projection::default() }));
mask.effects.push(Effect::new(fixture.project.alloc_id(), EffectKind::Filter(Filter::Blur { radius: 64.0 })));
mask.effects.push(Effect::new(anchor, EffectKind::Anchor));
@@ -3676,6 +3867,8 @@ soft {soft:?}"
rotation: 0.0,
offset: [0.0; 2],
depth: 0.5,
symmetry: None,
flip: [false; 2],
};
let id = f.project.alloc_id();
let mut fill = Fill { projection: Projection::Decal(d), ..Fill::default() };
@@ -3707,6 +3900,226 @@ soft {soft:?}"
assert!(close(half.value(Channel::BaseColor, 32, 32), [0.75, 0.25, 0.25]), "the image alpha shapes the decal");
}
/// Composites a cube with a decal of a four-colored image, and checks each texel of the
/// faces picked by `expect` against the image at the coordinates it gives (None: the texel
/// is not part of the check). Returns how many texels were checked.
fn cube_decal_texels(d: texturecraft_core::Decal, expect: impl Fn(Vec3, Vec3) -> Option<Option<(f32, f32)>>) -> usize {
let mesh = primitives::cube(2.0);
let gbuf = UvGBuffer::new(&mesh, 0, 64, 64);
let mut project = Project::new("t", "builtin:cube");
project.texture_sets.push(TextureSet::new("Cube", 0, 64));
let id = project.alloc_id();
let mut fill = Fill { projection: Projection::Decal(d), ..Fill::default() };
fill.sources.insert(Channel::BaseColor, Source::image("decal"));
project.insert_layer(0, Layer::new(id, "Decal", LayerKind::Fill(fill), &[Channel::BaseColor]), None, false).unwrap();
// Top left red, top right blue, bottom left green, bottom right yellow
let img = crate::store::ImageRes {
width: 2,
height: 2,
rgba: vec![[1.0, 0.0, 0.0, 1.0], [0.0, 0.0, 1.0, 1.0], [0.0, 1.0, 0.0, 1.0], [1.0, 1.0, 0.0, 1.0]],
srgb: false,
};
let images: ImageStore = [("decal".to_string(), std::sync::Arc::new(img.clone()))].into_iter().collect();
let pixels = PixelStore::default();
let baked = BakedMaps::default();
let inp = Inputs {
project: &project,
ts: 0,
mesh: &mesh,
gbuf: &gbuf,
pixels: &pixels,
baked: &baked,
block_scales: project.texture_sets[0].block_scales(),
preview: None,
images: &images,
bounds: mesh.bounds(),
};
let mut out = Composite::new(&project.texture_sets[0].channel_list(), 64);
composite_tiles(&inp, &mut out, &all_tiles(64, 64));
let mut checked = 0;
for i in 0..64 * 64 {
let Some(surface) = gbuf.surface(&mesh, i) else { continue };
let Some(want) = expect(surface.pos, surface.nrm) else { continue };
let got = out.value(Channel::BaseColor, (i % 64) as u32, (i / 64) as u32);
let want = want.map_or([0.5; 3], |(u, v)| {
let c = img.sample(u, v);
[c[0], c[1], c[2]]
});
assert!(close(got, want), "texel at {:?} on a face turned to {:?}: {got:?}, expected {want:?}", surface.pos, surface.nrm);
checked += 1;
}
checked
}
/// A 1 by 1 decal on the cube's +X face (the image's right runs toward -Z, its up toward +Y)
fn cube_decal(center: [f32; 3], size: f32, symmetry: Option<texturecraft_core::DecalSymmetry>) -> texturecraft_core::Decal {
texturecraft_core::Decal {
center,
normal: [1.0, 0.0, 0.0],
up: [0.0, 1.0, 0.0],
size: [size; 2],
rotation: 0.0,
offset: [0.0; 2],
depth: 0.5,
symmetry,
flip: [false; 2],
}
}
/// What the decal of `size` centered at (cy, cz) on the +X face gives the point (y, z) of
/// that face: the image coordinates well inside the frame, None for a bare texel clearly
/// outside it, and None for texels near its edge (not part of the checks).
fn face_expect(y: f32, z: f32, (cy, cz): (f32, f32), size: f32) -> Option<Option<(f32, f32)>> {
let (u, v) = (0.5 - (z - cz) / size, 0.5 - (y - cy) / size);
let off = (u - 0.5).abs().max((v - 0.5).abs());
if off < 0.4 {
Some(Some((u, v)))
} else if off > 0.6 {
Some(None)
} else {
None
}
}
#[test]
fn a_mirrored_decal_lands_on_the_opposite_cube_face_with_its_flip() {
use texturecraft_core::{DecalFlip, DecalSymmetry};
let at = (0.1, -0.2);
let on_x = |flip| {
cube_decal_texels(cube_decal([1.0, at.0, at.1], 1.0, Some(DecalSymmetry { axis: 0, flip, offset: 0.0 })), |p, n| {
if n.x > 0.99 {
face_expect(p.y, p.z, at, 1.0)
} else if n.x < -0.99 {
// The mirror image: the point's reflection, then the flip of the copy
face_expect(p.y, p.z, at, 1.0).map(|texel| {
texel.map(|(u, v)| match flip {
DecalFlip::None => (u, v),
DecalFlip::U => (1.0 - u, v),
DecalFlip::V => (u, 1.0 - v),
})
})
} else {
Some(None)
}
})
};
for flip in [DecalFlip::None, DecalFlip::U, DecalFlip::V] {
assert!(on_x(flip) > 800, "{flip:?}: most of the cube was checked");
}
// No symmetry: the -X face stays bare
let bare = cube_decal_texels(cube_decal([1.0, at.0, at.1], 1.0, None), |p, n| if n.x > 0.99 { face_expect(p.y, p.z, at, 1.0) } else { Some(None) });
assert!(bare > 800);
// Mirrored across Z, the copy sits on the same face on the other side of the Z = 0 plane
let at = (0.1, -0.5);
let across_z = Some(DecalSymmetry { axis: 2, flip: DecalFlip::None, offset: 0.0 });
let on_z = cube_decal_texels(cube_decal([1.0, at.0, at.1], 0.4, across_z), |p, n| {
if n.x > 0.99 {
match (face_expect(p.y, p.z, at, 0.4), face_expect(p.y, -p.z, at, 0.4)) {
(Some(Some(texel)), _) | (_, Some(Some(texel))) => Some(Some(texel)),
(Some(None), Some(None)) => Some(None),
_ => None,
}
} else {
Some(None)
}
});
assert!(on_z > 800);
}
#[test]
fn the_mirror_plane_can_be_moved_along_its_axis() {
use texturecraft_core::{DecalFlip, DecalSymmetry};
// Mirrored across Z with the plane at z = 0.3: a decal at z = -0.2 gets its copy at z = 0.8
let at = (0.1, -0.2);
let moved = Some(DecalSymmetry { axis: 2, flip: DecalFlip::None, offset: 0.3 });
let checked = cube_decal_texels(cube_decal([1.0, at.0, at.1], 0.4, moved), |p, n| {
if n.x > 0.99 {
match (face_expect(p.y, p.z, at, 0.4), face_expect(p.y, 0.6 - p.z, at, 0.4)) {
(Some(Some(texel)), _) | (_, Some(Some(texel))) => Some(Some(texel)),
(Some(None), Some(None)) => Some(None),
_ => None,
}
} else {
Some(None)
}
});
assert!(checked > 800);
}
#[test]
fn moving_the_decal_moves_its_mirrored_copy() {
use texturecraft_core::{DecalFlip, DecalSymmetry};
let symmetry = Some(DecalSymmetry { axis: 0, flip: DecalFlip::None, offset: 0.0 });
for at in [(0.5, 0.3), (-0.4, -0.5)] {
let checked =
cube_decal_texels(
cube_decal([1.0, at.0, at.1], 0.4, symmetry),
|p, n| {
if n.x.abs() > 0.99 { face_expect(p.y, p.z, at, 0.4) } else { Some(None) }
},
);
assert!(checked > 800, "{at:?}");
}
}
#[test]
fn flipping_a_decal_mirrors_its_image_inside_the_frame() {
let mut f = fixture();
let s = f.gbuf.surface(&f.mesh, 32 * 64 + 32).unwrap();
// The frame's center sits a quarter of its width to the right of the texel, so the texel reads the image's left half
let d = texturecraft_core::Decal {
center: s.pos.to_array(),
normal: s.nrm.to_array(),
up: s.nrm.any_orthonormal_vector().to_array(),
size: [1.0, 1.0],
rotation: 0.0,
offset: [0.25, 0.0],
depth: 0.5,
symmetry: None,
flip: [false; 2],
};
let id = f.project.alloc_id();
let mut fill = Fill { projection: Projection::Decal(d), ..Fill::default() };
fill.sources.insert(Channel::BaseColor, Source::image("decal"));
f.project.insert_layer(0, Layer::new(id, "Decal", LayerKind::Fill(fill), &[Channel::BaseColor]), None, false).unwrap();
// Left half red, right half blue
let img = crate::store::ImageRes { width: 2, height: 1, rgba: vec![[1.0, 0.0, 0.0, 1.0], [0.0, 0.0, 1.0, 1.0]], srgb: false };
let images: ImageStore = [("decal".to_string(), std::sync::Arc::new(img))].into_iter().collect();
let texel = |f: &Fixture, flip: [bool; 2]| {
let mut project = f.project.clone();
if let Ok(layer) = project.layer_mut(id)
&& let LayerKind::Fill(fill) = &mut layer.kind
{
fill.projection = Projection::Decal(texturecraft_core::Decal { flip, ..d });
}
let inp = Inputs {
project: &project,
ts: 0,
mesh: &f.mesh,
gbuf: &f.gbuf,
pixels: &f.pixels,
baked: &f.baked,
block_scales: project.texture_sets[0].block_scales(),
preview: None,
images: &images,
bounds: f.mesh.bounds(),
};
let mut out = Composite::new(&project.texture_sets[0].channel_list(), 64);
composite_tiles(&inp, &mut out, &all_tiles(64, 64));
out.value(Channel::BaseColor, 32, 32)
};
assert!(close(texel(&f, [false, false]), [1.0, 0.0, 0.0]), "the left half shows red");
assert!(close(texel(&f, [true, false]), [0.0, 0.0, 1.0]), "Flip U shows the right half there");
assert!(close(texel(&f, [false, true]), [1.0, 0.0, 0.0]), "Flip V leaves the left half");
}
#[test]
fn anchors_read_colors_as_gray_in_fill_layers() {
let mut f = fixture();
@@ -3714,9 +4127,102 @@ soft {soft:?}"
let anchor = content_fx(&mut f, low, EffectKind::Anchor);
let id = f.project.alloc_id();
let mut fill = Fill::default();
fill.sources.insert(Channel::Roughness, Source::Anchor { anchor, channel: Channel::BaseColor });
fill.sources.insert(Channel::Roughness, Source::Anchor { anchor, channel: Channel::BaseColor, ramp: Vec::new() });
f.project.insert_layer(0, Layer::new(id, "Top", LayerKind::Fill(fill), &[Channel::Roughness]), None, false).unwrap();
let expect = texturecraft_core::lum([0.2, 0.4, 0.6]);
assert!(close(run(&f, None).value(Channel::Roughness, 9, 9), [expect; 3]));
}
const RAMP: [[f32; 3]; 3] = [[1.0, 0.0, 0.0], [0.0, 1.0, 0.0], [0.0, 0.0, 1.0]];
#[test]
fn an_anchor_gradient_map_recolors_the_stack_below_by_its_lightness() {
// The stops at 0, 0.5 and 1, and halfway between them
for (gray, want) in [(0.0, [1.0, 0.0, 0.0]), (0.25, [0.5, 0.5, 0.0]), (0.5, [0.0, 1.0, 0.0]), (0.75, [0.0, 0.5, 0.5]), (1.0, [0.0, 0.0, 1.0])] {
let mut f = fixture();
let low = fill_layer(&mut f.project, [gray; 3], 0.5);
let anchor = content_fx(&mut f, low, EffectKind::Anchor);
let id = f.project.alloc_id();
let mut fill = Fill::default();
fill.sources.insert(Channel::BaseColor, Source::Anchor { anchor, channel: Channel::BaseColor, ramp: RAMP.to_vec() });
// A scalar channel reading the same anchor with stops keeps reading its gray
fill.sources.insert(Channel::Roughness, Source::Anchor { anchor, channel: Channel::BaseColor, ramp: RAMP.to_vec() });
fill.sources.insert(Channel::Metallic, Source::Uniform([0.3; 3]));
let channels = [Channel::BaseColor, Channel::Roughness, Channel::Metallic];
f.project.insert_layer(0, Layer::new(id, "Top", LayerKind::Fill(fill), &channels), None, false).unwrap();
let out = run(&f, None);
assert!(close(out.value(Channel::BaseColor, 9, 9), want), "gray {gray}: {:?}", out.value(Channel::BaseColor, 9, 9));
assert!(close(out.value(Channel::Roughness, 9, 9), [gray; 3]), "gray {gray}: {:?}", out.value(Channel::Roughness, 9, 9));
assert!(close(out.value(Channel::Metallic, 9, 9), [0.3; 3]));
}
}
#[test]
fn an_anchor_gradient_map_reads_signed_height_from_minus_one_to_one() {
for (height, want) in [(-1.0, [1.0, 0.0, 0.0]), (0.0, [0.0, 1.0, 0.0]), (0.5, [0.0, 0.5, 0.5])] {
let mut f = fixture();
let low = f.project.alloc_id();
let mut below = Fill::default();
below.sources.insert(Channel::Height, Source::Uniform([height; 3]));
f.project.insert_layer(0, Layer::new(low, "Below", LayerKind::Fill(below), &[Channel::Height]), None, false).unwrap();
let anchor = content_fx(&mut f, low, EffectKind::Anchor);
let id = f.project.alloc_id();
let mut fill = Fill::default();
fill.sources.insert(Channel::BaseColor, Source::Anchor { anchor, channel: Channel::Height, ramp: RAMP.to_vec() });
f.project.insert_layer(0, Layer::new(id, "Top", LayerKind::Fill(fill), &[Channel::BaseColor]), None, false).unwrap();
let out = run(&f, None);
assert!(close(out.value(Channel::BaseColor, 9, 9), want), "height {height}: {:?}", out.value(Channel::BaseColor, 9, 9));
}
}
#[test]
fn a_gradient_map_reads_a_mask_anchors_gray_from_zero_to_one_in_every_channel() {
for channel in [Channel::BaseColor, Channel::Height] {
for (gray, want) in [(0.0, [1.0, 0.0, 0.0]), (0.25, [0.5, 0.5, 0.0]), (0.5, [0.0, 1.0, 0.0]), (1.0, [0.0, 0.0, 1.0])] {
let mut f = fixture();
let low = fill_layer(&mut f.project, [0.0; 3], 0.5);
let anchor = f.project.alloc_id();
let mut mask = Mask::new(MaskBackground::Black);
mask.effects
.push(Effect::new(f.project.alloc_id(), EffectKind::Fill { source: Source::Uniform([gray; 3]), projection: Projection::default() }));
mask.effects.push(Effect::new(anchor, EffectKind::Anchor));
f.project.layer_mut(low).unwrap().mask = Some(mask);
let id = f.project.alloc_id();
let mut fill = Fill::default();
fill.sources.insert(Channel::BaseColor, Source::Anchor { anchor, channel, ramp: RAMP.to_vec() });
f.project.insert_layer(0, Layer::new(id, "Top", LayerKind::Fill(fill), &[Channel::BaseColor]), None, false).unwrap();
let out = run(&f, None);
assert!(close(out.value(Channel::BaseColor, 9, 9), want), "{channel:?}, gray {gray}: {:?}", out.value(Channel::BaseColor, 9, 9));
}
}
}
#[test]
fn a_procedural_gradient_map_replaces_low_and_high_and_no_stops_keep_them() {
let (low, high) = ([0.2, 0.3, 0.4], [0.8, 0.7, 0.6]);
let composite = |ramp: Vec<[f32; 3]>, lo: [f32; 3], hi: [f32; 3]| {
let mut f = fixture();
let id = f.project.alloc_id();
let mut fill = Fill::default();
let pattern = Procedural::new(ProceduralKind::Gradient);
fill.sources.insert(Channel::BaseColor, Source::Procedural { pattern: pattern.clone(), low: lo, high: hi, ramp: ramp.clone() });
fill.sources.insert(Channel::Roughness, Source::Procedural { pattern, low: lo, high: hi, ramp });
f.project.insert_layer(0, Layer::new(id, "Fill", LayerKind::Fill(fill), &[Channel::BaseColor, Channel::Roughness]), None, false).unwrap();
let out = run(&f, None);
(0..64).map(|x| (out.value(Channel::BaseColor, x, 20), out.value(Channel::Roughness, x, 20))).collect::<Vec<_>>()
};
// The pattern's own 0..1 values, then the same pattern through low and high and through the stops
let gray = composite(Vec::new(), [0.0; 3], [1.0; 3]);
let plain = composite(Vec::new(), low, high);
let mapped = composite(RAMP.to_vec(), low, high);
let near = |a: [f32; 3], b: [f32; 3]| (0..3).all(|i| (a[i] - b[i]).abs() < 1e-3);
assert!(gray.iter().any(|(v, _)| v[0] < 0.25) && gray.iter().any(|(v, _)| v[0] > 0.75), "the gradient spans dark to light");
for (((t, _), (p, _)), (m, rough)) in gray.iter().zip(&plain).zip(&mapped) {
assert!(near(*p, mix3(low, high, t[0])), "no stops: low to high");
assert!(near(*m, texturecraft_core::gradient(&RAMP, t[0]).unwrap()), "{t:?} -> {m:?}");
assert!((rough[0] - mix3(low, high, t[0])[0]).abs() < 1e-3, "roughness ignores the stops: {rough:?}");
}
}
}
+4 -2
View File
@@ -16,14 +16,16 @@ pub mod eval;
mod held_fields;
mod image_identity;
pub mod pattern;
pub mod solo;
pub mod store;
pub mod thumb;
pub use below::{BelowCache, StackKey};
pub use display::{DisplayKind, kinds_for, tile_bytes};
pub use eval::{
BLOCK, Composite, Inputs, PaintTarget, Stencil, StrokePreview, all_tiles, composite_tiles, composite_tiles_cached, covered_tiles, effect_histogram,
flatten_layer, mask_at, mask_image, pad_tiles, stack_reads_neighbours,
BLOCK, Composite, Inputs, MASK_CHANNEL, PaintTarget, Stencil, StrokePreview, all_tiles, composite_tiles, composite_tiles_cached, covered_tiles,
effect_histogram, flatten_layer, mask_at, mask_image, mask_texels, mask_values, pad_tiles, stack_reads_neighbours,
};
pub use solo::solo_project;
pub use store::{BakedMaps, ImageRes, ImageStore, PixelStore};
pub use thumb::{THUMB_TEXELS, ThumbImage, ThumbTarget};
+73 -4
View File
@@ -1,6 +1,6 @@
//! Procedural patterns and projections.
use texturecraft_core::{Decal, Procedural, ProceduralKind, Projection};
use texturecraft_core::{Decal, DecalFlip, Procedural, ProceduralKind, Projection};
use texturecraft_geom::glam::{Vec2, Vec3};
use texturecraft_texel::noise;
@@ -332,8 +332,38 @@ pub fn decal_uv(d: &Decal, p: Vec3, nrm: Vec3) -> Option<(Vec2, f32)> {
if facing <= 0.0 || lx.abs() > 0.5 || ly.abs() > 0.5 || lz > depth || !(lx.is_finite() && ly.is_finite()) {
return None;
}
let w = smoothstep(0.0, 0.3, facing) * (1.0 - smoothstep(0.75 * depth, depth, lz));
Some((Vec2::new(lx + 0.5, 0.5 - ly), w))
Some((flip_uv(Vec2::new(lx + 0.5, 0.5 - ly), d.flip), w))
}
/// `uv` with the image mirrored left to right (`flip[0]`) and/or top to bottom (`flip[1]`) inside the frame.
fn flip_uv(uv: Vec2, flip: [bool; 2]) -> Vec2 {
Vec2::new(if flip[0] { 1.0 - uv.x } else { uv.x }, if flip[1] { 1.0 - uv.y } else { uv.y })
}
/// [`decal_uv`] for a decal with a mirrored copy: whichever of the decal and its copy covers the
/// point more. The copy is the decal reflected through the plane across `center` (the mesh
/// center), so a point is looked up as its reflection (the plane is `offset` away from the center) and the image flipped as asked.
pub fn decal_uv_symmetric(d: &Decal, p: Vec3, nrm: Vec3, center: Vec3) -> Option<(Vec2, f32)> {
let direct = decal_uv(d, p, nrm);
let Some(symmetry) = d.symmetry else { return direct };
let axis = usize::from(symmetry.axis.min(2));
let (mut mirrored_position, mut mirrored_normal) = (p, nrm);
mirrored_position[axis] = 2.0 * (center[axis] + symmetry.offset) - p[axis];
mirrored_normal[axis] = -nrm[axis];
let mirrored = decal_uv(d, mirrored_position, mirrored_normal).map(|(uv, w)| {
let uv = match symmetry.flip {
DecalFlip::None => uv,
DecalFlip::U => Vec2::new(1.0 - uv.x, uv.y),
DecalFlip::V => Vec2::new(uv.x, 1.0 - uv.y),
};
(uv, w)
});
match (direct, mirrored) {
(Some(a), Some(b)) => Some(if b.1 > a.1 { b } else { a }),
(a, b) => a.or(b),
}
}
/// World-space noise used by generators (seamless across UV islands).
@@ -361,6 +391,8 @@ mod tests {
rotation: 0.0,
offset: [0.0; 2],
depth: 1.0,
symmetry: None,
flip: [false; 2],
}),
];
for k in ProceduralKind::ALL {
@@ -461,14 +493,25 @@ mod tests {
#[test]
fn decals_cover_their_frame_facing_them() {
let d = Decal { center: [0.0; 3], normal: [0.0, 0.0, 1.0], up: [0.0, 1.0, 0.0], size: [2.0, 1.0], rotation: 0.0, offset: [0.0; 2], depth: 0.5 };
let d = Decal {
center: [0.0; 3],
normal: [0.0, 0.0, 1.0],
up: [0.0, 1.0, 0.0],
size: [2.0, 1.0],
rotation: 0.0,
offset: [0.0; 2],
depth: 0.5,
symmetry: None,
flip: [false; 2],
};
let z = Vec3::Z;
let (uv, w) = decal_uv(&d, Vec3::new(0.5, 0.25, 0.0), z).unwrap();
assert!((uv - Vec2::new(0.75, 0.25)).length() < 1e-5 && (w - 1.0).abs() < 1e-5, "{uv} {w}");
assert!(decal_uv(&d, Vec3::new(1.1, 0.0, 0.0), z).is_none(), "outside the frame");
assert!(decal_uv(&d, Vec3::ZERO, -z).is_none(), "back faces");
assert!(decal_uv(&d, Vec3::new(0.0, 0.0, 0.6), z).is_none(), "beyond the depth");
// Rotated a quarter turn and shifted: the frame turns with it.
// Rotated a quarter turn and shifted: the frame turns with it
let r = Decal { rotation: 90.0, offset: [1.0, 0.0], ..d };
let (uv, _) = decal_uv(&r, Vec3::new(1.0, 0.9, 0.0), z).unwrap();
assert!((uv.x - 0.95).abs() < 1e-4 && (uv.y - 0.5).abs() < 1e-4, "{uv}");
@@ -478,6 +521,32 @@ mod tests {
assert!(decal_uv(&Decal { size: [f32::NAN; 2], ..d }, Vec3::ZERO, z).is_none());
}
#[test]
fn decals_mirror_their_image_inside_the_frame() {
let d = Decal {
center: [0.0; 3],
normal: [0.0, 0.0, 1.0],
up: [0.0, 1.0, 0.0],
size: [2.0, 1.0],
rotation: 0.0,
offset: [0.0; 2],
depth: 0.5,
symmetry: None,
flip: [false; 2],
};
let (left, top) = (Vec3::new(-0.5, 0.25, 0.0), Vec3::Z);
let uv = |flip: [bool; 2]| decal_uv(&Decal { flip, ..d }, left, top).unwrap().0;
assert!((uv([false, false]) - Vec2::new(0.25, 0.25)).length() < 1e-5);
assert!((uv([true, false]) - Vec2::new(0.75, 0.25)).length() < 1e-5, "Flip U mirrors left to right only");
assert!((uv([false, true]) - Vec2::new(0.25, 0.75)).length() < 1e-5, "Flip V mirrors top to bottom only");
assert!((uv([true, true]) - Vec2::new(0.75, 0.75)).length() < 1e-5);
// The frame itself does not move: coverage is the same flipped or not
let covered = |flip: [bool; 2], p: Vec3| decal_uv(&Decal { flip, ..d }, p, top).map(|(_, w)| w);
assert_eq!(covered([true, true], left), covered([false, false], left));
assert_eq!(covered([true, true], Vec3::new(1.1, 0.0, 0.0)), None);
}
#[test]
fn twill_floats_run_in_diagonal_ribs() {
// The value at the centre of cell (x, y); cells are half a unit.
+169
View File
@@ -0,0 +1,169 @@
//! The view-only "solo" of one layer: the project as the viewport shows it while a layer is
//! isolated. The document itself is never changed; the compositor reads this copy instead.
use std::collections::BTreeSet;
use texturecraft_core::project::MAX_DEPTH;
use texturecraft_core::{LayerId, Mask, MaskBackground, Project};
/// `project` as shown while `layer` is soloed: every other layer of its texture set hidden, the
/// layer and the folders around it shown (even if their eyes are off), and with `ignore_mask`
/// the layer and its folders drawn at full coverage. Other texture sets stay as they are.
/// None when `layer` is in no stack.
pub fn solo_project(project: &Project, layer: LayerId, ignore_mask: bool) -> Option<Project> {
let (ts, mut parent, _) = project.locate(layer)?;
let set = project.texture_sets.get(ts)?;
// The layer and the folders holding it
let mut shown = vec![layer];
for _ in 0..=MAX_DEPTH {
let Some(folder) = parent else { break };
shown.push(folder);
parent = project.locate(folder).and_then(|located| located.1);
}
// What stays drawn: those, and a soloed folder's contents
let mut kept: BTreeSet<LayerId> = shown.iter().copied().collect();
contents(project, &[layer], &mut kept, 0);
// A soloed instance draws its source's contents, which must stay visible too
kept.extend(project.render_tree(&[layer]));
let mut every = BTreeSet::new();
contents(project, &set.stack, &mut every, 0);
let mut view = project.clone();
for id in every.difference(&kept) {
if let Some(hidden) = view.layers.get_mut(id) {
hidden.visible = false;
}
}
for id in &shown {
let Some(drawn) = view.layers.get_mut(id) else { continue };
drawn.visible = true;
if !ignore_mask {
continue;
}
let instance = drawn.instance_source().is_some();
match drawn.mask.as_mut() {
Some(mask) => mask.enabled = false,
// An instance without its own mask draws its source's: an own, disabled one overrides it
None if instance => drawn.mask = Some(Mask { enabled: false, ..Mask::new(MaskBackground::White) }),
None => {}
}
}
Some(view)
}
/// `roots` and everything in the folders among them (instances' sources are not followed:
/// they may belong to another texture set).
fn contents(project: &Project, roots: &[LayerId], out: &mut BTreeSet<LayerId>, depth: usize) {
if depth > MAX_DEPTH {
return;
}
for id in roots {
out.insert(*id);
if let Some(layer) = project.layers.get(id) {
contents(project, layer.children(), out, depth + 1);
}
}
}
#[cfg(test)]
mod tests {
use super::*;
use texturecraft_core::{Channel, Layer, LayerKind, TextureSet};
const CHANNELS: [Channel; 1] = [Channel::BaseColor];
fn project() -> Project {
let mut p = Project::new("t", "");
p.texture_sets.push(TextureSet::new("a", 0, 64));
p.texture_sets.push(TextureSet::new("b", 0, 64));
p
}
fn add(p: &mut Project, ts: usize, kind: LayerKind, above: Option<LayerId>, inside: bool) -> LayerId {
let id = p.alloc_id();
p.insert_layer(ts, Layer::new(id, "layer", kind, &CHANNELS), above, inside).unwrap();
id
}
fn masked(p: &mut Project, id: LayerId) {
p.layer_mut(id).unwrap().mask = Some(Mask::new(MaskBackground::Black));
}
#[test]
fn solo_hides_the_others_and_leaves_the_original_alone() {
let mut p = project();
let (below, rust, other_set) =
(add(&mut p, 0, LayerKind::Paint, None, false), add(&mut p, 0, LayerKind::Paint, None, false), add(&mut p, 1, LayerKind::Paint, None, false));
p.layer_mut(rust).unwrap().visible = false;
let before = p.clone();
let view = solo_project(&p, rust, false).unwrap();
assert!(view.layers[&rust].visible, "the soloed layer shows even with its eye off");
assert!(!view.layers[&below].visible, "the others are hidden");
assert!(view.layers[&other_set].visible, "another texture set keeps its layers");
assert_eq!(p, before, "the project itself is untouched");
}
#[test]
fn solo_keeps_the_folders_around_a_layer_and_everything_inside_a_soloed_folder() {
let mut p = project();
let outside = add(&mut p, 0, LayerKind::Paint, None, false);
let folder = add(&mut p, 0, LayerKind::Group { children: Vec::new(), collapsed: false }, None, false);
let inner = add(&mut p, 0, LayerKind::Paint, Some(folder), true);
let sibling = add(&mut p, 0, LayerKind::Paint, Some(inner), false);
let view = solo_project(&p, inner, false).unwrap();
assert!(view.layers[&folder].visible && view.layers[&inner].visible);
assert!(!view.layers[&sibling].visible && !view.layers[&outside].visible);
let whole = solo_project(&p, folder, false).unwrap();
assert!(whole.layers[&inner].visible && whole.layers[&sibling].visible, "a soloed folder shows its contents");
assert!(!whole.layers[&outside].visible);
}
#[test]
fn ignoring_the_mask_disables_it_on_the_layer_and_its_folders_only() {
let mut p = project();
let folder = add(&mut p, 0, LayerKind::Group { children: Vec::new(), collapsed: false }, None, false);
let inner = add(&mut p, 0, LayerKind::Paint, Some(folder), true);
let other = add(&mut p, 0, LayerKind::Paint, None, false);
for id in [folder, inner, other] {
masked(&mut p, id);
}
let kept = solo_project(&p, inner, false).unwrap();
assert!(kept.layers[&inner].mask.as_ref().unwrap().enabled, "without the flag the mask stays");
let view = solo_project(&p, inner, true).unwrap();
assert!(!view.layers[&inner].mask.as_ref().unwrap().enabled && !view.layers[&folder].mask.as_ref().unwrap().enabled);
assert!(view.layers[&other].mask.as_ref().unwrap().enabled, "a hidden layer's mask is not touched");
assert!(p.layers[&inner].mask.as_ref().unwrap().enabled, "the project keeps its mask");
}
#[test]
fn an_instance_gets_its_own_disabled_mask_instead_of_changing_its_source() {
let mut p = project();
let source = add(&mut p, 0, LayerKind::Paint, None, false);
masked(&mut p, source);
let instance = add(&mut p, 1, LayerKind::Instance { source }, None, false);
let view = solo_project(&p, instance, true).unwrap();
assert!(!view.layers[&instance].mask.as_ref().unwrap().enabled);
assert!(view.layers[&source].mask.as_ref().unwrap().enabled, "the source keeps its mask");
}
#[test]
fn a_soloed_instance_of_a_folder_keeps_the_folders_contents_drawn() {
let mut p = project();
let folder = add(&mut p, 0, LayerKind::Group { children: Vec::new(), collapsed: false }, None, false);
let inner = add(&mut p, 0, LayerKind::Paint, Some(folder), true);
let instance = add(&mut p, 0, LayerKind::Instance { source: folder }, None, false);
let view = solo_project(&p, instance, false).unwrap();
assert!(view.layers[&instance].visible && view.layers[&folder].visible && view.layers[&inner].visible);
}
#[test]
fn a_layer_in_no_stack_gives_nothing() {
assert!(solo_project(&project(), LayerId(99), true).is_none());
}
}
+19 -12
View File
@@ -31,7 +31,7 @@ fn fixture() -> Fixture {
}
fn procedural(kind: ProceduralKind, low: f32, high: f32) -> Source {
Source::Procedural { pattern: Procedural::new(kind), low: [low; 3], high: [high; 3] }
Source::Procedural { pattern: Procedural::new(kind), low: [low; 3], high: [high; 3], ramp: Vec::new() }
}
fn add(f: &mut Fixture, ts: usize, kind: LayerKind, mask: Option<Mask>) -> LayerId {
@@ -196,11 +196,11 @@ fn instances_draw_their_source_across_texture_sets() {
#[test]
fn mask_with_height_follows_the_layer_height() {
let mut f = fixture();
// A white layer over the default gray, half masked, its height falling from 0.25 (left) to
// -0.25 (right).
// Half masking makes the height fall from 0.25 at left to -0.25 at right
let mut ramp = Procedural::new(ProceduralKind::Gradient);
ramp.scale = 1.0;
let height = Source::Procedural { pattern: ramp, low: [0.25; 3], high: [-0.25; 3] };
let height = Source::Procedural { pattern: ramp, low: [0.25; 3], high: [-0.25; 3], ramp: Vec::new() };
let id = add(&mut f, 0, fill(&[(Channel::BaseColor, Source::Uniform([1.0; 3])), (Channel::Height, height)]), None);
let mut mask = Mask::new(MaskBackground::Black);
mask.effects.push(effect(&mut f, EffectKind::Fill { source: Source::Uniform([0.5; 3]), projection: Projection::default() }));
@@ -214,7 +214,8 @@ fn mask_with_height_follows_the_layer_height() {
assert!((v(&plain, left) - 0.75).abs() < 0.01 && (v(&plain, right) - 0.75).abs() < 0.01, "plain mask: 50 % white over gray");
assert!(v(&hm, left) > 0.84, "high parts show first: {}", v(&hm, left));
assert!(v(&hm, right) < 0.66, "low parts later: {}", v(&hm, right));
// Without a mask there is nothing to combine.
// Without a mask there is nothing to combine
f.project.layer_mut(id).unwrap().mask.as_mut().unwrap().enabled = false;
assert!((v(&reference(&f, 0), left) - 1.0).abs() < 1e-3);
}
@@ -332,6 +333,7 @@ fn stroke(target: LayerId) -> StrokePreview {
mask_value: 1.0,
stencil: None,
carried: BTreeMap::new(),
carried_mask: None,
}
}
@@ -406,9 +408,10 @@ fn anchor_readers_fall_back_to_full_evaluation() {
let mut f = fixture();
let n = nested_stack(&mut f);
let anchor = effect(&mut f, EffectKind::Anchor);
let source = Source::Anchor { anchor: anchor.id, channel: Channel::Height };
let source = Source::Anchor { anchor: anchor.id, channel: Channel::Height, ramp: Vec::new() };
f.project.layer_mut(n.base).unwrap().content_effects.push(anchor);
// A mask above the hot layer reads the stack below it.
// A mask above the hot layer reads the stack below it
let reader = effect(&mut f, EffectKind::Fill { source, projection: Projection::default() });
f.project.layer_mut(n.g2_above).unwrap().mask.as_mut().unwrap().effects.push(reader);
for hot in [n.deep, n.top] {
@@ -512,21 +515,25 @@ fn anchors_inside_a_content_stack_record_the_content_up_to_them() {
f.project.layer_mut(low).unwrap().content_effects.extend([mid, raise, end]);
let top = add(&mut f, 0, LayerKind::Paint, None);
paint_rect(&mut f, top, (0, 0), (60, 60), 0.3);
// Without readers the stack is cached (anchors are still recorded) and exact.
// Without readers the stack is cached (anchors are still recorded) and exact
assert!(!check_cached(&f, 0, top).is_empty());
// Readers: roughness reads the anchor inside the stack, metallic the one at its end.
// Readers: roughness reads the anchor inside the stack, metallic the one at its end
for (c, anchor) in [(Channel::Roughness, mid_id), (Channel::Metallic, end_id)] {
let reader = add(&mut f, 0, fill(&[(c, Source::Anchor { anchor, channel: Channel::Height })]), None);
let reader = add(&mut f, 0, fill(&[(c, Source::Anchor { anchor, channel: Channel::Height, ramp: Vec::new() })]), None);
f.project.layer_mut(reader).unwrap().channels.retain(|x, _| *x == c);
}
let out = reference(&f, 0);
let at = |c| out.value(c, 128, 128)[0];
// Half opacity over the default height 0: 0.4 before the raise, 0.8 after it.
// Half opacity over the default height 0: 0.4 before the raise, 0.8 after it
assert!((at(Channel::Roughness) - 0.2).abs() < 2e-3, "inside the stack: {}", at(Channel::Roughness));
assert!((at(Channel::Metallic) - 0.4).abs() < 2e-3, "at the end: {}", at(Channel::Metallic));
assert!((at(Channel::Height) - 0.4).abs() < 2e-3);
assert!(check_cached(&f, 0, top).is_empty(), "anchor readers evaluate everything");
// Behind a blur the cut reads the filtered field; before it, the unfiltered content.
// Behind a blur the cut reads the filtered field; before it, the unfiltered content
let blur = effect(&mut f, EffectKind::Filter(Filter::Blur { radius: 30.0 }));
f.project.layer_mut(low).unwrap().content_effects.insert(0, blur);
let blurred = reference(&f, 0);
+108 -7
View File
@@ -8,6 +8,8 @@ use crate::{BakedMap, BlendMode, Channel, ChannelKind, lum};
mod curvature_detail;
mod curvature_mode;
mod decal_flip;
mod decal_symmetry;
mod generator_global;
mod micro_detail;
mod output_resolution;
@@ -15,6 +17,8 @@ mod resolution_mode;
pub use curvature_detail::CurvatureDetail;
pub use curvature_mode::CurvatureMode;
pub use decal_flip::DecalFlip;
pub use decal_symmetry::DecalSymmetry;
pub use generator_global::GeneratorGlobal;
pub use micro_detail::MicroDetail;
pub use output_resolution::OutputResolution;
@@ -192,6 +196,18 @@ pub struct Decal {
pub offset: [f32; 2],
/// How far in front of and behind the frame the decal reaches (world units).
pub depth: f32,
/// A mirrored copy of the decal on the other side of the mesh (None: no copy). The copy
/// follows this frame, so moving, scaling or turning the decal moves it too.
#[serde(default, skip_serializing_if = "Option::is_none")]
pub symmetry: Option<DecalSymmetry>,
/// Mirror the image inside the frame: left to right (`[0]`), top to bottom (`[1]`). Old projects have neither.
#[serde(default, skip_serializing_if = "not_flipped")]
pub flip: [bool; 2],
}
/// Serde helper: a decal that mirrors nothing saves without the field
fn not_flipped(flip: &[bool; 2]) -> bool {
!flip[0] && !flip[1]
}
impl Default for Projection {
@@ -348,8 +364,15 @@ impl Procedural {
pub enum Source {
/// A constant value (linear RGB for colors; `[v, v, v]` for scalars).
Uniform([f32; 3]),
/// A procedural pattern mixing two values.
Procedural { pattern: Procedural, low: [f32; 3], high: [f32; 3] },
/// A procedural pattern mixing two values, or on a color channel colored by `ramp` when it
/// has stops (a gradient map: dark to light through evenly spaced linear RGB colors).
Procedural {
pattern: Procedural,
low: [f32; 3],
high: [f32; 3],
#[serde(default, skip_serializing_if = "Vec::is_empty")]
ramp: Vec<[f32; 3]>,
},
/// An imported image resource, by name. `normal_format` is the convention of a normal map
/// image (DirectX images have their green flipped where a normal channel samples them).
Image {
@@ -358,8 +381,14 @@ pub enum Source {
normal_format: crate::NormalFormat,
},
/// The stack value recorded by an anchor point effect (`anchor` is the effect id) for
/// `channel`; colors read as gray where a scalar is needed.
Anchor { anchor: LayerId, channel: Channel },
/// `channel`; colors read as gray where a scalar is needed. On a color channel a `ramp` with
/// stops recolors the value by its lightness (a gradient map).
Anchor {
anchor: LayerId,
channel: Channel,
#[serde(default, skip_serializing_if = "Vec::is_empty")]
ramp: Vec<[f32; 3]>,
},
}
impl Source {
@@ -372,6 +401,14 @@ impl Source {
Source::Image { name: name.into(), normal_format: crate::NormalFormat::OpenGl }
}
/// The gradient map stops of a procedural or anchor source (empty: none).
pub fn ramp(&self) -> &[[f32; 3]] {
match self {
Source::Procedural { ramp, .. } | Source::Anchor { ramp, .. } => ramp,
_ => &[],
}
}
/// The anchor point this source reads, if any.
pub fn anchor(&self) -> Option<LayerId> {
match self {
@@ -1045,6 +1082,10 @@ pub enum EffectKind {
pub struct PathShape {
/// Surface positions (3D view) or texture coordinates with z = 0 (2D view).
pub points: Vec<[f32; 3]>,
/// Per point: the curve turns sharply there instead of passing smoothly through. Empty (and absent from old
/// projects) when every point is smooth; a missing entry is smooth too.
#[serde(default, skip_serializing_if = "Vec::is_empty")]
pub corners: Vec<bool>,
pub uv: bool,
pub closed: bool,
/// A closed path fills its interior instead of stroking the curve.
@@ -1114,7 +1155,7 @@ impl EffectKind {
let mut anchors: Vec<_> = sources
.into_iter()
.filter_map(|source| match source {
Source::Anchor { anchor, channel } => Some((*anchor, *channel)),
Source::Anchor { anchor, channel, .. } => Some((*anchor, *channel)),
_ => None,
})
.collect();
@@ -1164,7 +1205,7 @@ pub struct Effect {
impl Effect {
pub fn new(id: LayerId, kind: EffectKind) -> Effect {
// Generators and fills that build a mask usually add on top of the background.
// Generators and fills that build a mask usually add on top of the background
Effect { id, name: kind.name().to_string(), visible: true, kind, blend: BlendMode::Normal, opacity: 1.0 }
}
}
@@ -1173,6 +1214,27 @@ impl Effect {
mod tests {
use super::*;
#[test]
fn a_decal_saved_without_symmetry_loads_unchanged_and_saves_without_it() {
let old = r#"{"center":[0.0,0.0,1.0],"normal":[0.0,0.0,1.0],"up":[0.0,1.0,0.0],"size":[1.0,1.0],"rotation":0.0,"offset":[0.0,0.0],"depth":0.5}"#;
let decal: Decal = serde_json::from_str(old).unwrap();
assert_eq!(decal.symmetry, None);
assert_eq!(serde_json::to_string(&decal).unwrap(), old.replace(' ', ""), "nothing new is written for a decal without a copy");
let mirrored = Decal { symmetry: Some(DecalSymmetry { axis: 2, flip: DecalFlip::V, offset: 0.0 }), ..decal };
let json = serde_json::to_string(&mirrored).unwrap();
assert!(json.contains(r#""symmetry":{"axis":2,"flip":"v"}"#), "{json}");
assert_eq!(serde_json::from_str::<Decal>(&json).unwrap(), mirrored);
let without_flip = json.replace(r#","flip":"v""#, "");
assert_eq!(serde_json::from_str::<Decal>(&without_flip).unwrap().symmetry, Some(DecalSymmetry { axis: 2, flip: DecalFlip::None, offset: 0.0 }));
// The plane's offset is written only when it is not zero
let moved = Decal { symmetry: Some(DecalSymmetry { axis: 1, flip: DecalFlip::None, offset: -0.25 }), ..decal };
let json = serde_json::to_string(&moved).unwrap();
assert!(json.contains(r#""offset":-0.25}"#), "{json}");
assert_eq!(serde_json::from_str::<Decal>(&json).unwrap(), moved);
}
#[test]
fn material_effect_images_are_reported_as_used() {
let mut fill = Fill::default();
@@ -1296,6 +1358,29 @@ mod tests {
assert!(nan.point(c, [0.5; 3]).unwrap().iter().all(|v| v.is_finite()));
}
#[test]
fn gradient_map_stops_round_trip_and_sources_without_them_save_as_before() {
let ramp = vec![[1.0, 0.0, 0.0], [0.0, 0.0, 1.0]];
let procedural = |ramp: Vec<[f32; 3]>| Source::Procedural { pattern: Procedural::new(ProceduralKind::Clouds), low: [0.25; 3], high: [0.75; 3], ramp };
let anchor = |ramp: Vec<[f32; 3]>| Source::Anchor { anchor: LayerId(7), channel: Channel::BaseColor, ramp };
for source in [procedural(ramp.clone()), anchor(ramp.clone())] {
let json = serde_json::to_value(&source).unwrap();
assert!(json.to_string().contains("\"ramp\""), "{json}");
assert_eq!(serde_json::from_value::<Source>(json).unwrap(), source);
assert_eq!(source.ramp(), ramp.as_slice());
}
// Empty ramps preserve older projects' JSON shape
let old_procedural = serde_json::json!({"Procedural": {"pattern": serde_json::to_value(Procedural::new(ProceduralKind::Clouds)).unwrap(), "low": [0.25, 0.25, 0.25], "high": [0.75, 0.75, 0.75]}});
let old_anchor = serde_json::json!({"Anchor": {"anchor": 7, "channel": "BaseColor"}});
for (old, source) in [(old_procedural, procedural(Vec::new())), (old_anchor, anchor(Vec::new()))] {
assert_eq!(serde_json::to_value(&source).unwrap(), old);
assert_eq!(serde_json::from_value::<Source>(old).unwrap(), source);
assert!(source.ramp().is_empty());
}
assert!(Source::Uniform([0.5; 3]).ramp().is_empty());
}
#[test]
fn effect_targets_and_anchor_reads() {
assert_eq!(EffectKind::Anchor.content_only(), None, "anchors go on content and masks");
@@ -1303,7 +1388,7 @@ mod tests {
assert_eq!(EffectKind::Filter(Filter::Invert).content_only(), None);
let mut fill_layer = Layer::new(LayerId(1), "l", LayerKind::Paint, &[Channel::BaseColor]);
assert!(!fill_layer.reads_anchor());
let source = Source::Anchor { anchor: LayerId(9), channel: Channel::Height };
let source = Source::Anchor { anchor: LayerId(9), channel: Channel::Height, ramp: Vec::new() };
fill_layer.mask = Some(Mask {
effects: vec![Effect::new(LayerId(2), EffectKind::Fill { source, projection: Projection::default() })],
..Mask::new(MaskBackground::Black)
@@ -1336,6 +1421,22 @@ mod tests {
assert_eq!(hm.apply(0.5, f32::NAN), 0.5);
}
#[test]
fn old_decals_load_unflipped_and_save_unchanged() {
let old = r#"{"center":[0.0,0.0,0.0],"normal":[0.0,0.0,1.0],"up":[0.0,1.0,0.0],"size":[1.0,2.0],"rotation":0.0,"offset":[0.0,0.0],"depth":0.5}"#;
let decal: Decal = serde_json::from_str(old).unwrap();
assert_eq!(decal.flip, [false, false]);
assert_eq!(
serde_json::from_str::<serde_json::Value>(&serde_json::to_string(&decal).unwrap()).unwrap(),
serde_json::from_str::<serde_json::Value>(old).unwrap()
);
let flipped = Decal { flip: [true, false], ..decal };
let saved = serde_json::to_string(&flipped).unwrap();
assert!(saved.contains(r#""flip":[true,false]"#), "{saved}");
assert_eq!(serde_json::from_str::<Decal>(&saved).unwrap(), flipped);
}
#[test]
fn generator_kinds_parse() {
for k in GeneratorKind::ALL {
+14
View File
@@ -0,0 +1,14 @@
use serde::{Deserialize, Serialize};
/// How the mirrored decal's image is turned over
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "lowercase")]
pub enum DecalFlip {
/// Only the reflection: the copy is the decal's mirror image
#[default]
None,
/// The image's left and right swapped
U,
/// The image's top and bottom swapped
V,
}
+26
View File
@@ -0,0 +1,26 @@
use serde::{Deserialize, Deserializer, Serialize};
use super::DecalFlip;
/// The mirrored copy of a decal: reflected through the plane perpendicular to `axis`, across the mesh center (moved by `offset`)
#[derive(Clone, Copy, Debug, PartialEq, Serialize, Deserialize)]
pub struct DecalSymmetry {
/// Axis the mirror plane is perpendicular to (0 = X, 1 = Y, 2 = Z)
#[serde(deserialize_with = "deserialize_axis")]
pub axis: u8,
/// Extra flip of the image on the mirrored copy, on top of the reflection itself
#[serde(default)]
pub flip: DecalFlip,
/// Where the mirror plane sits, relative to the mesh center along `axis` (world units, as the brush symmetry's offset)
#[serde(default, skip_serializing_if = "is_zero")]
pub offset: f32,
}
fn deserialize_axis<'de, D: Deserializer<'de>>(deserializer: D) -> Result<u8, D::Error> {
// Recover malformed projects with the same Z plane used by the renderer
Ok(u8::deserialize(deserializer)?.min(2))
}
fn is_zero(value: &f32) -> bool {
*value == 0.0
}
+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, GeneratorGlobal, GeneratorKind, HeightMask,
Layer, LayerId, LayerKind, Levels, LinkParam, LinkPreset, Mask, MaskBackground, MaterialLink, MicroDetail, OutputResolution, PathShape, Procedural,
ProceduralKind, Projection, ResolutionMode, Source, gradient, hsl_adjust, per_unit,
ChannelBlend, CompareOp, CurvatureDetail, CurvatureMode, Decal, DecalFlip, DecalSymmetry, Effect, EffectKind, Fill, Filter, Generator, GeneratorGlobal,
GeneratorKind, HeightMask, Layer, LayerId, LayerKind, Levels, LinkParam, LinkPreset, Mask, MaskBackground, MaterialLink, MicroDetail, 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,
+8 -2
View File
@@ -562,6 +562,11 @@ impl Project {
}
let (ts, parent, i) = self.locate(id).ok_or(CoreError::NoLayer(id))?;
if let Some(t) = target {
let (target_set, _, _) = self.locate(t).ok_or(CoreError::NoLayer(t))?;
if target_set != ts {
return Err(CoreError::Invalid("layer move target belongs to another texture set".into()));
}
let mut sub = Vec::new();
self.collect_subtree(id, 0, &mut sub);
if sub.contains(&t) {
@@ -791,7 +796,7 @@ mod tests {
];
let id = p.insert_layer(0, l, None, false).unwrap();
let mut top = paint(&mut p, "y");
let source = Source::Anchor { anchor, channel: Channel::Height };
let source = Source::Anchor { anchor, channel: Channel::Height, ramp: Vec::new() };
top.mask = Some(Mask {
effects: vec![Effect::new(p.alloc_id(), EffectKind::Fill { source, projection: Projection::default() })],
..Mask::new(MaskBackground::Black)
@@ -801,7 +806,8 @@ mod tests {
let back: Project = serde_json::from_str(&json).unwrap();
assert_eq!(back, p);
assert_eq!(back.effect(anchor).map(|(owner, _)| owner), Some(id));
// Projects saved before content effects existed load with empty stacks.
// Projects saved before content effects existed load with empty stacks
let mut v: serde_json::Value = serde_json::from_str(&json).unwrap();
for l in v["layers"].as_object_mut().unwrap().values_mut() {
l.as_object_mut().unwrap().remove("content_effects");
+114 -1
View File
@@ -37,6 +37,23 @@ pub fn specs() -> Vec<CommandSpec> {
cmd!("camera.bookmark7", "Go to camera 7", ["Viewport"], Some("Ctrl+7"), "{}", always, |s, _| bookmark(s, 6)),
cmd!("camera.bookmark8", "Go to camera 8", ["Viewport"], Some("Ctrl+8"), "{}", always, |s, _| bookmark(s, 7)),
cmd!("camera.bookmark9", "Go to camera 9", ["Viewport"], Some("Ctrl+9"), "{}", always, |s, _| bookmark(s, 8)),
cmd!(
"camera.view",
"Fixed view",
[],
None,
"{view: front|back|left|right|top|bottom} → the camera (looks at the mesh from that side and frames it; the projection stays)",
always,
|s, p| fixed_view(s, strp(p, "view").ok_or_else(|| bad("camera.view", "`view` is required"))?)
),
cmd!("camera.view.front", "Front view", ["Viewport"], None, "{}", always, |s, _| fixed_view(s, "front")),
cmd!("camera.view.back", "Back view", ["Viewport"], None, "{}", always, |s, _| fixed_view(s, "back")),
cmd!("camera.view.left", "Left view", ["Viewport"], None, "{}", always, |s, _| fixed_view(s, "left")),
cmd!("camera.view.right", "Right view", ["Viewport"], None, "{}", always, |s, _| fixed_view(s, "right")),
cmd!("camera.view.top", "Top view", ["Viewport"], None, "{}", always, |s, _| fixed_view(s, "top")),
cmd!("camera.view.bottom", "Bottom view", ["Viewport"], None, "{}", always, |s, _| fixed_view(s, "bottom")),
cmd!("camera.perspective", "Perspective", ["Viewport"], Some("F5"), "{}", always, |s, _| projection(s, false)),
cmd!("camera.orthographic", "Orthographic", ["Viewport"], Some("F6"), "{}", always, |s, _| projection(s, true)),
cmd!("viewport.focusAt", "Focus depth of field here", [], None, "{x, y (viewport pixels), viewport?: [w, h]}", always, focus_at),
]
}
@@ -128,19 +145,48 @@ fn add(s: &mut Session, p: &Value) -> Result<Value> {
fn select(s: &mut Session, p: &Value) -> Result<Value> {
if u64p(p, "index").is_none() && strp(p, "name").is_none_or(|n| n == DEFAULT_CAMERA) {
// The default camera: fov and projection from the display settings, framing the mesh.
// The default camera: fov and projection from the display settings, framing the mesh
s.camera.fov = s.doc.project.display.fov;
s.camera.ortho = false;
return crate::execute(s, "viewport.frame", &Value::Null);
}
let i = which(s, "camera.select", p)?;
if let Some(c) = s.doc.project.cameras.get(i).cloned() {
// A saved view is clamped against the whole mesh, not against a part framed with F
s.camera.scene_radius = s.mesh.radius();
apply(&mut s.camera, &c);
}
s.revision = s.revision.wrapping_add(1);
Ok(crate::view_cmds::camera_json(s))
}
/// The fixed views: name, yaw and pitch in degrees. Yaw 0 puts the eye on +Z (the front), yaw 90
/// on +X (the right side); top and bottom stop at the orbit's ±89° pitch limit.
pub const VIEWS: [(&str, f32, f32); 6] =
[("front", 0.0, 0.0), ("back", 180.0, 0.0), ("left", -90.0, 0.0), ("right", 90.0, 0.0), ("top", 0.0, 89.0), ("bottom", 0.0, -89.0)];
/// Look at the mesh from fixed view `name` and frame it, keeping the projection. The yaw is the
/// one nearest the current yaw, so the desktop UI's glide takes the short way round.
fn fixed_view(s: &mut Session, name: &str) -> Result<Value> {
let Some(&(_, yaw, pitch)) = VIEWS.iter().find(|(view, ..)| *view == name) else {
return Err(bad("camera.view", format!("unknown view `{name}`: one of front, back, left, right, top, bottom")));
};
let current = if s.camera.yaw.is_finite() { s.camera.yaw } else { 0.0 };
let turn = std::f32::consts::TAU;
s.camera.yaw = current + (yaw.to_radians() - current + turn * 0.5).rem_euclid(turn) - turn * 0.5;
s.camera.pitch = pitch.to_radians();
crate::execute(s, "viewport.frame", &Value::Null)
}
/// Switch to a perspective or orthographic projection; position and rotation stay.
fn projection(s: &mut Session, ortho: bool) -> Result<Value> {
s.camera.ortho = ortho;
s.revision = s.revision.wrapping_add(1);
Ok(crate::view_cmds::camera_json(s))
}
/// Shortcut slot `slot` (0-based): the n-th saved camera, in list order.
fn bookmark(s: &mut Session, slot: usize) -> Result<Value> {
if slot >= s.doc.project.cameras.len() {
@@ -238,6 +284,73 @@ mod tests {
assert!(ids.iter().all(|c| c.shortcut.is_some()));
}
#[test]
fn fixed_views_look_from_their_side_frame_the_mesh_and_keep_the_projection() {
let mut s = session();
execute(&mut s, "camera.set", &json!({"yaw": 37, "pitch": 21, "distance": 9, "target": [0.4, -0.3, 0.2]})).unwrap();
let (lo, hi) = s.mesh.bounds();
let mut framed = s.camera;
framed.frame(lo, hi);
let sides = [("front", Vec3::Z), ("back", Vec3::NEG_Z), ("left", Vec3::NEG_X), ("right", Vec3::X), ("top", Vec3::Y), ("bottom", Vec3::NEG_Y)];
for ortho in [false, true] {
execute(&mut s, "camera.set", &json!({"ortho": ortho})).unwrap();
for (view, side) in sides {
// Through the parameterized command and through the menu command alike
let menu_id = format!("camera.view.{view}");
for (id, params) in [("camera.view", json!({"view": view})), (menu_id.as_str(), Value::Null)] {
execute(&mut s, "camera.orbit", &json!({"dx": 123, "dy": 17})).unwrap();
let back = execute(&mut s, id, &params).unwrap();
let looking_from = (s.camera.eye() - s.camera.target).normalize();
assert!(looking_from.dot(side) > 0.999, "{id} {view}: the eye is on the {side} side, not at {looking_from}");
assert_eq!(s.camera.ortho, ortho, "{id} {view} keeps the projection");
assert!((s.camera.target - framed.target).length() < 1e-5, "{view} centres the mesh");
assert!((s.camera.distance - framed.distance).abs() < 1e-4, "{view} frames the mesh");
assert_eq!(back["ortho"], ortho);
}
}
}
// Orbit still works from a fixed view, and a view is not an undo step
let steps = s.history_labels().len();
execute(&mut s, "camera.view.top", &Value::Null).unwrap();
assert!((s.camera.pitch - 89f32.to_radians()).abs() < 1e-6, "top stops at the orbit limit");
execute(&mut s, "camera.orbit", &json!({"dx": 30, "dy": -40})).unwrap();
assert!((s.camera.pitch - 49f32.to_radians()).abs() < 1e-5 && s.camera.yaw.to_degrees().rem_euclid(360.0) > 1.0);
assert_eq!(s.history_labels().len(), steps);
}
#[test]
fn fixed_views_take_the_nearest_turn_and_reject_unknown_views() {
let mut s = session();
execute(&mut s, "camera.set", &json!({"yaw": 715})).unwrap();
execute(&mut s, "camera.view", &json!({"view": "front"})).unwrap();
assert!((s.camera.yaw - 720f32.to_radians()).abs() < 1e-4, "two whole turns, not a spin back to 0: {}", s.camera.yaw.to_degrees());
let before = s.camera;
assert!(execute(&mut s, "camera.view", &json!({"view": "sideways"})).is_err());
assert!(execute(&mut s, "camera.view", &json!({})).is_err(), "`view` is required");
assert!(execute(&mut s, "camera.view", &json!({"view": 3})).is_err());
assert_eq!(s.camera, before, "a rejected view leaves the camera");
let menu: Vec<_> = crate::command_specs().iter().filter(|c| c.id.starts_with("camera.view.")).collect();
assert_eq!(menu.len(), 6);
assert!(menu.iter().all(|c| c.shortcut.is_none() && c.menu == ["Viewport"]), "no default keys: users bind their own");
}
#[test]
fn perspective_and_orthographic_change_only_the_projection() {
let mut s = session();
execute(&mut s, "camera.set", &json!({"yaw": 30, "pitch": 10, "distance": 4})).unwrap();
let before = s.camera;
let r = execute(&mut s, "camera.orthographic", &Value::Null).unwrap();
assert!(s.camera.ortho && r["ortho"] == true);
assert_eq!(OrbitCamera { ortho: false, ..s.camera }, before, "position and rotation stay");
execute(&mut s, "camera.orthographic", &Value::Null).unwrap();
assert!(s.camera.ortho, "a second press keeps it orthographic: two actions, not a toggle");
execute(&mut s, "camera.perspective", &Value::Null).unwrap();
assert_eq!(s.camera, before);
let key = |id: &str| crate::find(id).and_then(|c| c.shortcut);
assert_eq!((key("camera.perspective"), key("camera.orthographic")), (Some("F5"), Some("F6")));
}
#[test]
fn cameras_round_trip_through_the_project_file() {
let mut s = session();
+132
View File
@@ -24,6 +24,63 @@ pub struct CommandSpec {
pub run: Run,
}
impl CommandSpec {
/// Whether a keyboard shortcut can run this command: it acts with no parameters at all, or
/// every parameter in its first `params` form is optional (`name?`) and none of them is one
/// of several alternatives. Left out: commands that need a path, name or similar, commands
/// that only return data or do nothing without parameters, and the ones that replace the
/// open project (the menu asks to save first).
pub fn bindable(&self) -> bool {
const NOT_FROM_A_KEY: [&str; 13] = [
"project.inspect",
"project.templates",
"project.new",
"tool.state",
"text.fonts",
"export.presets",
"edit.history",
"camera.get",
"textureSet.parts",
"bake.settings",
"bake.preview",
"camera.set",
"textureSet.settings",
];
const NOTHING_WITHOUT_PARAMS: [&str; 4] = ["layer.blend", "tool.stencil", "tool.fillSelection", "tool.path"];
!(self.id.ends_with(".list") || NOT_FROM_A_KEY.contains(&self.id) || NOTHING_WITHOUT_PARAMS.contains(&self.id)) && params_all_optional(self.params)
}
}
/// Whether the first `{...}` group of a `params` text has only optional entries.
fn params_all_optional(params: &str) -> bool {
let Some(body) = params.trim_start().strip_prefix('{') else { return false };
let Some(end) = body.find('}') else { return false };
// `{a?} | {b}`: other forms exist, and the first one alone may not do anything
if body[end + 1..].trim_start().starts_with('|') {
return false;
}
let (mut depth, mut start) = (0i32, 0);
let mut entries = Vec::new();
for (i, c) in body[..end].char_indices() {
match c {
'(' | '[' => depth += 1,
')' | ']' => depth -= 1,
',' if depth == 0 => {
entries.push(&body[start..i]);
start = i + 1;
}
_ => {}
}
}
entries.push(&body[start..end]);
entries.iter().filter(|entry| !entry.trim().is_empty()).all(|entry| {
// `index? | name?` asks for one of the two, so it is not optional as a whole
!entry.contains(" | ") && entry.trim().split([':', ' ', '(']).next().is_some_and(|key| key.ends_with('?'))
})
}
pub(crate) fn always(_: &Session) -> std::result::Result<(), String> {
Ok(())
}
@@ -57,12 +114,14 @@ pub fn command_specs() -> &'static [CommandSpec] {
v.extend(crate::layer_ops::specs());
v.extend(crate::instance_cmds::specs());
v.extend(crate::mask_cmds::specs());
v.extend(crate::mask_export::specs());
v.extend(crate::color_selection_cmds::specs());
v.extend(crate::effect_clipboard::specs());
v.extend(crate::tool_cmds::specs());
v.extend(crate::brush_preset_cmds::specs());
v.extend(crate::path_tool::specs());
v.extend(crate::view_cmds::specs());
v.extend(crate::solo::specs());
v.extend(crate::camera_cmds::specs());
v.extend(crate::quick_mask::specs());
v.extend(crate::set_cmds::specs());
@@ -268,6 +327,65 @@ pub(crate) fn color_of(v: &Value) -> Option<[f32; 3]> {
mod tests {
use super::*;
#[test]
fn only_commands_a_key_can_run_are_bindable() {
let bindable = |id: &str| find(id).unwrap_or_else(|| panic!("{id} is gone")).bindable();
for id in [
"layer.add.paint",
"layer.add.fill",
"layer.add.group",
"mask.invert",
"mask.clear",
"layer.visible",
"effect.add.paint",
"file.save",
"tool.paint",
"camera.add",
"effect.duplicate",
"effect.paste",
] {
assert!(bindable(id), "{id} needs no parameters");
}
for id in [
"file.saveCopy",
"textureSet.select",
"layer.rename",
"tool.select",
"layer.select",
"viewport.focusAt",
"tool.stroke",
"mask.smart.apply",
"bake.skew.set",
"textureSet.resolution",
"effect.move",
"camera.remove",
"bake.highPoly.remove",
] {
assert!(!bindable(id), "{id} needs a parameter");
}
for id in ["layer.move", "layer.list", "project.inspect", "edit.history", "export.presets", "tool.state", "project.new", "camera.set", "layer.blend"] {
assert!(!bindable(id), "{id} is a query or has several forms");
}
}
#[test]
fn params_texts_are_read_by_their_required_entries() {
for ok in ["{}", "{layer?}", "{enabled?: bool} \u{2014} toggles when omitted", "{effect?: the selected effect}"] {
assert!(params_all_optional(ok), "{ok}");
}
for no in [
"{path}",
"{layer?, name}",
"{x, y (viewport pixels), viewport?: [w, h]}",
"{a?} | {b}",
"{index? | name?}",
"{ts?, value?: 0..1 | path: image}",
"no braces",
] {
assert!(!params_all_optional(no), "{no}");
}
}
#[test]
fn color_param_accepts_valid_forms() {
let p = json!({
@@ -318,4 +436,18 @@ mod tests {
assert_eq!(color_of(&json!("#GGGGGG")), None);
assert!(color_of(&json!("#ff8000")).is_some());
}
#[test]
fn no_bindable_command_asks_for_a_parameter() {
// Effect commands need a selected effect, which this session lacks
for spec in command_specs().iter().filter(|c| c.bindable() && c.shortcut.is_none() && !c.id.starts_with("effect.")) {
let mut session = crate::sample_session(256, 64).unwrap();
if (spec.enabled)(&session).is_ok()
&& let Err(err) = execute(&mut session, spec.id, &Value::Null)
{
let text = err.to_string();
assert!(!text.contains("required") && !text.contains("give "), "{} asks for a parameter: {text}", spec.id);
}
}
}
}
+106 -8
View File
@@ -2,10 +2,12 @@
//! (a decal fill with a planar projection), as a fill layer with a decal projection.
use serde_json::{Value, json};
use texturecraft_core::{Channel, Decal, Effect, EffectKind, Fill, Layer, LayerId, LayerKind, Mask, MaskBackground, Projection, Source};
use texturecraft_geom::glam::{Vec2, Vec3};
use texturecraft_core::{
Channel, Decal, DecalFlip, DecalSymmetry, Effect, EffectKind, Fill, Layer, LayerId, LayerKind, Mask, MaskBackground, Projection, Source,
};
use texturecraft_geom::glam::{Quat, Vec2, Vec3};
use crate::commands::{CommandSpec, always, bad, channel_param, f32p, has_layer, layer_param, strp, u64p, vec3};
use crate::commands::{CommandSpec, always, bad, boolp, channel_param, f32p, layer_param, strp, u64p, vec3};
use crate::tool_cmds::viewport_of;
use crate::{Result, Session, StackTarget, cmd};
@@ -16,7 +18,7 @@ pub fn specs() -> Vec<CommandSpec> {
"Add decal",
[],
None,
"{image: resource name, channel?: a channel id (default baseColor) | \"mask\" (a new fill layer masked by the image's gray), x?, y?: viewport pixels (default: the view center; a point on another texture set selects it), viewport?: [w,h] | position?: [x,y,z], normal?: [x,y,z] (on the selected texture set), up?: [x,y,z] (the image's up; default the view's up, or the view direction when that is along the normal), size?: height | [w,h] (world units; default a quarter of the mesh), rotation?: degrees, depth?, name?} → {layer, decal, maskEffect: the mask fill effect holding the image with channel \"mask\", else null} — a fill layer projecting the image from a frame placed on the surface; seen from the front, the image reads the right way round",
"{image: resource name, channel?: a channel id (default baseColor) | \"mask\" (a new fill layer masked by the image's gray), x?, y?: viewport pixels (default: the view center; a point on another texture set selects it), viewport?: [w,h] | position?: [x,y,z], normal?: [x,y,z] (on the selected texture set), up?: [x,y,z] (the image's up; default the view's up, or the view direction when that is along the normal), size?: height | [w,h] (world units; default a quarter of the mesh), keepProportions?: true makes the height follow the width by the image's aspect, flipU?, flipV?: mirror the image left to right / top to bottom inside the frame, rotation?: degrees, depth?, symmetry?: x|y|z|off (also place a mirrored copy across the mesh center, perpendicular to that axis; it follows this decal), symmetryFlip?: none|u|v (flip the copy's image on top of the reflection), symmetryOffset?: world units from the mesh center along the axis to the mirror plane (default 0, within the mesh), name?} → {layer, decal, maskEffect: the mask fill effect holding the image with channel \"mask\", else null} — a fill layer projecting the image from a frame placed on the surface; seen from the front, the image reads the right way round",
always,
add
),
@@ -25,8 +27,8 @@ pub fn specs() -> Vec<CommandSpec> {
"Edit decal",
[],
None,
"{layer? | effect?: a mask fill effect id (a decal placed as a mask; with `layer`, it must be in that layer), x?, y?, viewport? | position?, normal? (re-place it on its own texture set), up?: [x,y,z], size?: height | [w,h], rotation?: degrees, offset?: [right, up] (world units from where it was placed), depth?, image?: replaces the image in the channel or mask it was placed in, merge?: true continues the previous Edit decal undo step (drags)}",
has_layer,
"{layer? | effect?: a mask fill effect id (a decal placed as a mask; with `layer`, it must be in that layer), x?, y?, viewport? | position?, normal? (re-place it on its own texture set), up?: [x,y,z] (default: the decal's up carried along when it moves onto a surface facing another way), size?: height | [w,h], keepProportions?: true keeps the image's aspect (the current ratio without an image): a height sets the width, a [w,h] pair or no size sets the height from the width, flipU?, flipV?: mirror the image left to right / top to bottom inside the frame, rotation?: degrees, offset?: [right, up] (world units from where it was placed), depth?, symmetry?: x|y|z|off, symmetryFlip?: none|u|v, symmetryOffset? (the mirrored copy; the flip and offset alone keep the axis), image?: replaces the image in the channel or mask it was placed in, merge?: true continues the previous Edit decal undo step (drags)}",
always,
set
),
]
@@ -91,6 +93,56 @@ fn decal_up(s: &Session, cmd: &str, p: &Value, normal: Vec3) -> Result<Vec3> {
Ok(if up.normalize_or_zero().cross(normal).length_squared() > 1e-4 { up } else { to_world.transform_vector3(Vec3::NEG_Z) })
}
/// The mirrored copy asked for by `symmetry` (x, y, z or off) and `symmetryFlip` (none, u or v),
/// starting from `current` for what the params leave out
fn symmetry_param(cmd: &str, p: &Value, current: Option<DecalSymmetry>, bounds: (Vec3, Vec3)) -> Result<Option<DecalSymmetry>> {
let axis = match strp(p, "symmetry").map(str::to_ascii_lowercase).as_deref() {
None => current.map(|symmetry| symmetry.axis.min(2)),
Some("off" | "none") => None,
Some("x") => Some(0),
Some("y") => Some(1),
Some("z") => Some(2),
Some(other) => return Err(bad(cmd, format!("unknown symmetry `{other}` (x, y, z or off)"))),
};
let flip = match strp(p, "symmetryFlip").map(str::to_ascii_lowercase).as_deref() {
None => current.map_or(DecalFlip::None, |symmetry| symmetry.flip),
Some("none" | "off") => DecalFlip::None,
Some("u") => DecalFlip::U,
Some("v") => DecalFlip::V,
Some(other) => return Err(bad(cmd, format!("unknown symmetryFlip `{other}` (none, u or v)"))),
};
// The plane stays within the mesh, as the brush symmetry's offset does
let (lo, hi) = bounds;
let half_extent = (hi - lo) * 0.5;
let offset = match (f32p(p, "symmetryOffset"), current) {
(Some(offset), _) if !offset.is_finite() => return Err(bad(cmd, "`symmetryOffset` must be a number")),
(Some(offset), _) => offset,
(None, Some(symmetry)) => symmetry.offset,
(None, None) => 0.0,
};
Ok(axis.map(|axis| {
let limit = half_extent[usize::from(axis)];
DecalSymmetry { axis, flip, offset: offset.clamp(-limit, limit) }
}))
}
/// The up of a decal moved from a surface facing `from.0` (up `from.1`) onto one facing `to`: the
/// old up turned by the smallest rotation that takes the old normal to the new one (parallel
/// transport), so it follows the surface smoothly and never degenerates. A surface turned
/// exactly away has no smallest rotation: the camera rule of a new decal decides there.
fn carried_up(s: &Session, from: (Vec3, Vec3), to: Vec3) -> Vec3 {
let (old_normal, old_up) = from;
let (Some(old_normal), Some(new_normal)) = (old_normal.try_normalize(), to.try_normalize()) else { return old_up };
if old_normal.dot(new_normal) < -0.9999 {
return decal_up(s, "", &Value::Null, new_normal).unwrap_or(old_up);
}
Quat::from_rotation_arc(old_normal, new_normal) * old_up
}
fn add(s: &mut Session, p: &Value) -> Result<Value> {
let cmd = "layer.add.decal";
let image = strp(p, "image").ok_or_else(|| bad(cmd, "`image` is required"))?.to_string();
@@ -112,7 +164,10 @@ fn add(s: &mut Session, p: &Value) -> Result<Value> {
let mesh_diagonal = mesh_size(s);
let default_height = mesh_diagonal * DEFAULT_HEIGHT;
let size = size_param(p, aspect, mesh_diagonal).unwrap_or([default_height * aspect, default_height]);
let mut size = size_param(p, aspect, mesh_diagonal).unwrap_or([default_height * aspect, default_height]);
if boolp(p, "keepProportions") == Some(true) && p.get("size").is_some_and(Value::is_array) {
size[1] = (size[0] / aspect).clamp(mesh_diagonal * MIN_SIZE, mesh_diagonal * MAX_SIZE);
}
let decal = Decal {
center: center.to_array(),
normal: normal.to_array(),
@@ -120,8 +175,11 @@ fn add(s: &mut Session, p: &Value) -> Result<Value> {
size,
rotation: f32p(p, "rotation").unwrap_or(0.0).rem_euclid(360.0),
offset: [0.0; 2],
flip: [boolp(p, "flipU").unwrap_or(false), boolp(p, "flipV").unwrap_or(false)],
// By default it reaches half its larger side into the surface
depth: f32p(p, "depth").map_or(size[0].max(size[1]) * 0.5, |depth| depth.clamp(mesh_diagonal * MIN_SIZE, mesh_diagonal * MAX_SIZE)),
symmetry: symmetry_param(cmd, p, None, s.mesh.bounds())?,
};
// A decal dropped on another texture set goes there and selects it, as a dropped material does
@@ -169,6 +227,27 @@ fn decal_of(s: &Session, cmd: &str, id: LayerId, effect: Option<LayerId>) -> Res
}
}
/// Width over height of the image the decal of fill layer `id` (or of mask fill effect `effect`) shows
/// (`new`: the image a call replaces it with, which then counts instead)
fn image_aspect(s: &Session, id: LayerId, effect: Option<LayerId>, new: Option<&str>) -> Option<f32> {
let name = match effect {
_ if new.is_some() => new?.to_string(),
Some(effect) => match &s.doc.project.effect(effect)?.1.kind {
EffectKind::Fill { source: Source::Image { name, .. }, .. } => name.clone(),
_ => return None,
},
None => match &s.doc.project.layer(id).ok()?.kind {
LayerKind::Fill(fill) => fill.sources.values().find_map(|source| match source {
Source::Image { name, .. } => Some(name.clone()),
_ => None,
})?,
_ => return None,
},
};
let image = s.images.get(&name)?;
Some(image.width as f32 / image.height.max(1) as f32)
}
fn set(session: &mut Session, params: &Value) -> Result<Value> {
let command = "layer.decal.set";
let effect = u64p(params, "effect").map(LayerId);
@@ -192,14 +271,32 @@ fn set(session: &mut Session, params: &Value) -> Result<Value> {
return Err(bad(command, "that surface belongs to another texture set"));
}
// Carry up so a stale axis cannot lie in or flip on the new surface
let previous = (Vec3::from(decal.normal), Vec3::from(decal.up));
(decal.center, decal.normal, decal.offset) = (center.to_array(), normal.to_array(), [0.0; 2]);
if params.get("up").is_none() {
decal.up = carried_up(session, previous, normal).to_array();
}
}
if params.get("up").is_some() {
decal.up = decal_up(session, command, params, Vec3::from(decal.normal))?.to_array();
}
if let Some(size) = size_param(params, decal.size[0] / decal.size[1].max(1e-6), mesh_diagonal) {
let keep = boolp(params, "keepProportions") == Some(true);
let ratio = decal.size[0] / decal.size[1].max(1e-6);
let aspect = if keep { image_aspect(session, layer_id, effect, strp(params, "image")).unwrap_or(ratio) } else { ratio };
if let Some(mut size) = size_param(params, aspect, mesh_diagonal).or_else(|| keep.then_some(decal.size)) {
// A height sets the width through `aspect`; a pair or the current size sets the height from the width
if keep && params.get("size").is_none_or(Value::is_array) {
size[1] = (size[0] / aspect).clamp(mesh_diagonal * MIN_SIZE, mesh_diagonal * MAX_SIZE);
}
decal.size = size;
}
if let Some(flip) = boolp(params, "flipU") {
decal.flip[0] = flip;
}
if let Some(flip) = boolp(params, "flipV") {
decal.flip[1] = flip;
}
if let Some(rotation) = f32p(params, "rotation") {
decal.rotation = rotation.rem_euclid(360.0);
}
@@ -212,6 +309,7 @@ fn set(session: &mut Session, params: &Value) -> Result<Value> {
if let Some(depth) = f32p(params, "depth") {
decal.depth = depth.clamp(mesh_diagonal * MIN_SIZE, mesh_diagonal * MAX_SIZE);
}
decal.symmetry = symmetry_param(command, params, decal.symmetry, session.mesh.bounds())?;
let image = strp(params, "image").map(str::to_string);
if let Some(name) = &image
+1 -1
View File
@@ -127,7 +127,7 @@ fn paste(session: &mut Session, params: &Value) -> Result<Value> {
// 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);
session.select_one(layer_set, layer);
if layer_set == session.ts() {
session.target = StackTarget::Effect(pasted);
}
+47 -8
View File
@@ -51,7 +51,7 @@ pub fn specs() -> Vec<CommandSpec> {
"Export textures",
["File"],
None,
"{dir, preset?: built-in or user preset name, or a preset object {name, maps}, ts?: index|\"all\", format?: png|jpg|tga|tif|exr|..., bitDepth?, padding?: none|dilation|dilationDefault|infinite, dilation?: px, size?: px, normalFormat?: openGl|directX, colorSpace?: sRGB (default for 8/16-bit files)|Linear Rec.709 (default for exr, hdr)|ACEScg|ACES2065-1 (colour maps are converted, data maps never are; 8/16-bit files clamp to 0-1; a chosen space is also recorded in the colour maps: an ICC profile in PNG, JPEG, TIFF and WebP, the chromaticities in EXR; TGA, BMP and HDR can't hold one and warn), materialX?: bool (also write a .mtlx OpenPBR material per texture set; needs the \"OpenPBR (separate maps)\" preset)}",
"{dir, preset?: built-in or user preset name, or a preset object {name, maps}, ts?: index|[indexes]|\"all\", format?: png|jpg|tga|tif|exr|..., bitDepth?, padding?: none|dilation|dilationDefault|infinite, dilation?: px, size?: px, normalFormat?: openGl|directX, colorSpace?: sRGB (default for 8/16-bit files)|Linear Rec.709 (default for exr, hdr)|ACEScg|ACES2065-1 (colour maps are converted, data maps never are; 8/16-bit files clamp to 0-1; a chosen space is also recorded in the colour maps: an ICC profile in PNG, JPEG, TIFF and WebP, the chromaticities in EXR; TGA, BMP and HDR can't hold one and warn), materialX?: bool (also write a .mtlx OpenPBR material per texture set; needs the \"OpenPBR (separate maps)\" preset)}",
always,
export_textures
),
@@ -140,6 +140,7 @@ impl Session {
/// for UV-tiled sets, or nothing for them without `tiled`).
fn material_files(&mut self, opts: ExportOptions, tiled: bool, materials: usize) -> Result<Vec<Vec<ExportedFile>>> {
let opts = ExportOptions { atlas: true, ..opts };
(0..materials)
.map(|m| match self.texture_set_of_material(m) {
Some(ts) if tiled || self.doc.project.texture_sets.get(ts).is_some_and(|t| t.tile_grid().is_none()) => self.export_files(&[ts], &opts),
@@ -236,17 +237,21 @@ impl Session {
/// Render every export file for texture sets `sets` (in memory; works on the web).
pub fn export_files(&mut self, sets: &[usize], opts: &ExportOptions) -> Result<Vec<ExportedFile>> {
self.update();
if self.solo.is_none() {
self.update();
}
let mesh_name = stem_of(self.doc.project.mesh.trim_start_matches("builtin:"));
let mut out = Vec::new();
let empty = Default::default();
for &ts in sets {
let cache = self.caches.get(ts).ok_or_else(|| EngineError::Other(format!("no texture set {ts}")))?;
let composite = self.document_composite(ts, &cache.covered_tiles).ok_or_else(|| EngineError::Other(format!("no texture set {ts}")))?;
let coverage = cache.gbuf.coverage_mask();
let input = ExportInput {
project: &self.doc.project,
ts,
composite: &cache.composite,
composite: &composite,
baked: self.doc.baked.get(&ts).unwrap_or(&empty),
coverage: &coverage,
mesh_name: &mesh_name,
@@ -275,6 +280,7 @@ pub fn export_options(s: &Session, p: &Value, cmd: &str) -> Result<ExportOptions
Some(v @ Value::Object(_)) => Some(crate::preset_cmds::preset_param(v, cmd)?),
Some(_) => return Err(bad(cmd, "`preset` must be a preset name or a preset object")),
};
let preset = preset.ok_or_else(|| bad(cmd, format!("unknown export preset {}", p.get("preset").unwrap_or(&Value::Null))))?;
let mut o = ExportOptions::new(preset);
if let Some(f) = strp(p, "format") {
@@ -305,7 +311,8 @@ pub fn export_options(s: &Session, p: &Value, cmd: &str) -> Result<ExportOptions
.ok_or_else(|| bad(cmd, format!("unknown colorSpace `{name}` (sRGB, Linear Rec.709, ACEScg or ACES2065-1)")))?,
);
}
// A value of the wrong type is an error, not the format's default space.
// A value of the wrong type is an error, not the format's default space
Some(other) => return Err(bad(cmd, format!("`colorSpace` is a name (sRGB, Linear Rec.709, ACEScg or ACES2065-1), not {other}"))),
}
Ok(o)
@@ -315,10 +322,24 @@ fn sets_param(s: &Session, p: &Value, cmd: &str) -> Result<Vec<usize>> {
match p.get("ts") {
None => Ok((0..s.set_count()).collect()),
Some(Value::String(a)) if a == "all" => Ok((0..s.set_count()).collect()),
Some(v) => Ok(vec![v.as_u64().map(|t| t as usize).filter(|t| *t < s.set_count()).ok_or_else(|| bad(cmd, "invalid `ts`"))?]),
// Several sets in one command, so a file name two of them share is found before anything is written
Some(Value::Array(a)) => {
let mut sets = a.iter().map(|v| set_index(s, v, cmd)).collect::<Result<Vec<_>>>()?;
// A set listed twice is written once
let mut seen = std::collections::HashSet::new();
sets.retain(|t| seen.insert(*t));
Ok(sets)
}
Some(v) => Ok(vec![set_index(s, v, cmd)?]),
}
}
fn set_index(s: &Session, v: &Value, cmd: &str) -> Result<usize> {
v.as_u64().and_then(|index| usize::try_from(index).ok()).filter(|index| *index < s.set_count()).ok_or_else(|| bad(cmd, "invalid `ts`"))
}
fn plan(s: &mut Session, p: &Value) -> Result<Value> {
let opts = export_options(s, p, "export.plan")?;
let mesh_name = stem_of(s.doc.project.mesh.trim_start_matches("builtin:"));
@@ -546,7 +567,8 @@ fn write_materialx(s: &Session, sets: &[usize], opts: &ExportOptions, dir: &std:
let mut textures: Vec<Texture> = Vec::new();
for f in texturecraft_formats::list_outputs(&s.doc.project, ts, &mesh_name, opts).map_err(fe)? {
let Some(input) = opts.preset.maps.get(f.map).and_then(|m| materialx::input_of_template(&m.file)) else { continue };
// The first tile stands for all of them: its number is written as <UDIM>.
// The first tile stands for all of them: its number is written as <UDIM>
let file = f.udim_name.clone().unwrap_or_else(|| f.name.clone());
let colorspace = materialx::colorspace_name(opts.space_for(f.format));
if !textures.iter().any(|t| t.input == input) {
@@ -558,8 +580,10 @@ fn write_materialx(s: &Session, sets: &[usize], opts: &ExportOptions, dir: &std:
warnings.push(format!("MaterialX: texture set \"{}\" has no OpenPBR maps; use the \"OpenPBR (separate maps)\" preset", set.name));
continue;
}
let stem = texturecraft_formats::export::sanitize_file_stem(&format!("{mesh_name}_{}", set.name));
// Case-insensitive: Windows and macOS file systems are.
// Case-insensitive: Windows and macOS file systems are
if !stems.insert(stem.to_ascii_lowercase()) {
warnings.push(format!(
"MaterialX: texture set \"{}\" exports as \"{stem}\" like an earlier set, so its .mtlx was not written; rename one of them",
@@ -571,7 +595,8 @@ fn write_materialx(s: &Session, sets: &[usize], opts: &ExportOptions, dir: &std:
texturecraft_formats::write_atomic(&path, materialx::write(&format!("{mesh_name}_{}", set.name), &textures, None).as_bytes()).map_err(fe)?;
out.push(path);
}
// The normalmap node only exists in a material that has a normal map.
// The normalmap node only exists in a material that has a normal map
if normal_map_written && opts.normal_format == Some(NormalFormat::DirectX) {
warnings.push("MaterialX: the normalmap node reads OpenGL (+Y) normals; this export wrote DirectX normals, so flip the green channel".into());
}
@@ -918,3 +943,17 @@ f 1/1 2/2 3/3
assert_eq!(parts(&mut old), json!(["mesh"]));
}
}
#[cfg(all(test, target_pointer_width = "32"))]
mod index_tests {
use super::*;
#[test]
fn export_rejects_an_index_that_would_wrap_to_the_first_set() {
let mut session = Session::new_project("t", primitives::material_ball(), "builtin:material_ball", None, 128).unwrap();
let wrapped_index = u64::from(u32::MAX) + 1;
assert!(crate::execute(&mut session, "export.plan", &json!({ "ts": wrapped_index })).is_err());
assert!(crate::execute(&mut session, "export.plan", &json!({ "ts": [wrapped_index] })).is_err());
}
}
+3 -2
View File
@@ -149,10 +149,11 @@ fn mat_finish(id: &str) -> Option<Fill> {
"matFinishHammered" => (ProceduralKind::Hammered, 6.0, [0.25, 0.45], 0.08),
_ => return None,
};
let pattern = Procedural { scale, ..Procedural::new(kind) };
let mut fill = Fill { projection: Projection::Triplanar { scale: 1.0, sharpness: 8.0, offset: [0.0; 3] }, ..Fill::default() };
fill.sources.insert(Channel::Roughness, Source::Procedural { pattern: pattern.clone(), low: [rough[0]; 3], high: [rough[1]; 3] });
fill.sources.insert(Channel::Height, Source::Procedural { pattern, low: [-height; 3], high: [height; 3] });
fill.sources.insert(Channel::Roughness, Source::Procedural { pattern: pattern.clone(), low: [rough[0]; 3], high: [rough[1]; 3], ramp: Vec::new() });
fill.sources.insert(Channel::Height, Source::Procedural { pattern, low: [-height; 3], high: [height; 3], ramp: Vec::new() });
Some(fill)
}
+5
View File
@@ -0,0 +1,5 @@
#[derive(Clone, Copy)]
pub(crate) enum FrameTarget {
All,
Selection,
}
+17 -4
View File
@@ -10,15 +10,26 @@ use crate::session::StackTarget;
fn source_json(s: &Source) -> Value {
match s {
Source::Uniform(v) => json!({ "uniform": v }),
Source::Procedural { pattern, low, high } => json!({
"procedural": pattern.kind.label(), "scale": pattern.scale, "seed": pattern.seed, "contrast": pattern.contrast, "low": low, "high": high
}),
Source::Procedural { pattern, low, high, ramp } => with_ramp(
json!({
"procedural": pattern.kind.label(), "scale": pattern.scale, "seed": pattern.seed, "contrast": pattern.contrast, "low": low, "high": high
}),
ramp,
),
Source::Image { name, normal_format: NormalFormat::OpenGl } => json!({ "image": name }),
Source::Image { name, normal_format: NormalFormat::DirectX } => json!({ "image": name, "normalFormat": "directX" }),
Source::Anchor { anchor, channel } => json!({ "anchor": anchor.0, "channel": channel.id() }),
Source::Anchor { anchor, channel, ramp } => with_ramp(json!({ "anchor": anchor.0, "channel": channel.id() }), ramp),
}
}
/// `v` with the gradient map stops of its source as `colors`, when it has any.
fn with_ramp(mut v: Value, ramp: &[[f32; 3]]) -> Value {
if !ramp.is_empty() {
v["colors"] = json!(ramp);
}
v
}
fn fill_json(f: &Fill) -> Value {
let mut v = json!({
"projection": f.projection.label(),
@@ -194,10 +205,12 @@ pub fn session(session: &Session) -> Value {
"bakeMeshes": crate::bake::meshes_json(session),
"activeTextureSet": texture_set,
"selectedLayer": session.selected_layer().map(|layer| layer.0),
"selectedLayers": crate::layer_selection::ids_json(&session.selected_layers()),
"target": match session.target { StackTarget::Content => json!("content"), StackTarget::Mask => json!("mask"), StackTarget::Effect(effect) => json!(effect.0) },
"layers": stack(session, texture_set),
"tool": { "tool": session.tool.tool.id(), "brush": crate::tool_cmds::brush_json(session) },
"view": session.view.label(),
"solo": session.solo.map(|solo| json!({ "layer": solo.layer.0, "ignoreMask": solo.ignore_mask })),
"bakePreview": crate::bake_preview::preview_json(session),
"camera": crate::view_cmds::camera_json(session),
"display": session.doc.project.display,
+2 -2
View File
@@ -49,7 +49,7 @@ pub(crate) fn make_instance(s: &mut Session, source: LayerId, ts: usize) -> Resu
let sel = s.selected.get(&ts).copied().filter(|l| s.doc.project.locate(*l).is_some_and(|(t, _, _)| t == ts));
let inside = sel.and_then(|l| s.doc.project.layer(l).ok()).is_some_and(Layer::is_group);
s.doc.project.insert_layer(ts, Layer::new(id, name, LayerKind::Instance { source: src_id }, &[]), sel, inside)?;
s.selected.insert(ts, id);
s.select_one(ts, id);
if ts == s.ts() {
s.target = StackTarget::Content;
}
@@ -98,7 +98,7 @@ pub(crate) fn detach(s: &mut Session, src: &Document, inst: LayerId) -> Result<L
}
s.doc.project.remove_layer(inst)?;
if s.selected.get(&ts) == Some(&inst) {
s.selected.insert(ts, copy);
s.select_one(ts, copy);
}
Ok(copy)
}
+333 -56
View File
@@ -2,11 +2,14 @@
//! per-channel blending and fill sources.
use serde_json::{Value, json};
use texturecraft_core::{BlendMode, Channel, ChannelBlend, EffectKind, Fill, Layer, LayerId, LayerKind, Procedural, ProceduralKind, Projection, Source};
use texturecraft_core::{
BlendMode, Channel, ChannelBlend, EffectKind, Fill, Layer, LayerId, LayerKind, Procedural, ProceduralKind, Project, Projection, Source,
};
use crate::commands::{
CommandSpec, always, bad, blend_param, boolp, channel_param, color_param, content_param, f32p, has_layer, layer_param, normal_format_param, strp, u64p,
};
use crate::layer_selection::{batch_param, ids_json};
use crate::{EngineError, Result, Session, cmd, session::StackTarget};
pub fn specs() -> Vec<CommandSpec> {
@@ -14,20 +17,77 @@ pub fn specs() -> Vec<CommandSpec> {
cmd!("layer.add.paint", "Add paint layer", ["Layers"], None, "{name?}", always, add_paint),
cmd!("layer.add.fill", "Add fill layer", ["Layers"], None, "{name?, color?, roughness?, metallic?}", always, add_fill),
cmd!("layer.add.group", "Add folder", ["Layers"], None, "{name?}", always, add_group),
cmd!("layer.remove", "Remove layer(s)", ["Layers"], Some("Delete"), "{layer?}", has_layer, remove),
cmd!("layer.duplicate", "Duplicate layer(s)", ["Layers"], Some("Ctrl+D"), "{layer?}", has_layer, duplicate),
cmd!("layer.group", "Group layer(s)", ["Layers"], Some("Ctrl+G"), "{layer?}", has_layer, group),
cmd!("layer.select", "Select layer", [], None, "{layer, target?: content|mask|<effect id>}", always, select),
cmd!(
"layer.remove",
"Remove layer(s)",
["Layers"],
Some("Delete"),
"{layer?, layers?: [id] (wins over `layer`)} — default: every selected layer",
has_layer,
remove
),
cmd!(
"layer.duplicate",
"Duplicate layer(s)",
["Layers"],
Some("Ctrl+D"),
"{layer?, layers?: [id] (wins over `layer`)} — default: every selected layer",
has_layer,
duplicate
),
cmd!(
"layer.group",
"Group layer(s)",
["Layers"],
Some("Ctrl+G"),
"{layer?, layers?: [id] (wins over `layer`)} — default: every selected layer",
has_layer,
group
),
cmd!(
"layer.select",
"Select layer",
[],
None,
"{layer, target?: content|mask|<effect id>} | {layer, toggle: true} (Ctrl+click: add or take out one layer) | {layer, range: true} (Shift+click: the rows from the last clicked layer) | {all: true} (Ctrl+A: every shown row of the active texture set, folder rows and the layers of open folders included) | {layers: [id], layer?} (select several; `layer` is the active one)",
always,
select
),
cmd!("layer.rename", "Rename layer", [], None, "{layer?, name}", has_layer, rename),
cmd!("layer.visible", "Toggle layer visibility", [], None, "{layer?, visible?}", has_layer, visible),
cmd!("layer.move", "Move layer", [], None, "{layer?, index?} | {layer?, above?: id|null, inside?: bool} | {layer?, delta: ±n}", has_layer, move_layer),
cmd!(
"layer.visible",
"Toggle layer visibility",
[],
None,
"{layer?, layers?: [id], visible?} — default: every selected layer; with `layers`, `layer` is the one the others follow",
has_layer,
visible
),
cmd!(
"layer.move",
"Move layer",
[],
None,
"{layer? | layers?: [id], index?} | {layer? | layers?: [id], above?: id|null, inside?: bool} | {layer?, delta: ±n}",
has_layer,
move_layer
),
cmd!("layer.blend", "Set channel blending", [], None, "{layer?, channel?: id|all, mode?, opacity?: 0..1, enabled?}", has_layer, blend),
cmd!(
"layer.blending.set",
"Set blending of several channels",
[],
None,
"{layer?, channels: {<channel id>: {mode?, opacity?: 0..1}}} (only channels the layer has enabled; one undo step)",
has_layer,
blending_set
),
cmd!(
"layer.fill.set",
"Set fill source",
[],
None,
"{layer? | effect?: content fill effect id, channel, color?|value?|procedural?: kind, scale?, seed?, contrast?, balance?, invert?, low?, high?|image?, normalFormat?: openGl|directX (the image's normal map convention; alone, it changes the channel's image)|anchor?: anchor effect id, anchorChannel?, enabled?, solo?: true (this channel on, every other one off)}",
"{layer? | effect?: content fill effect id, channel, color?|value?|procedural?: kind, scale?, seed?, contrast?, balance?, invert?, low?, high?|image?, normalFormat?: openGl|directX (the image's normal map convention; alone, it changes the channel's image)|anchor?: anchor effect id, anchorChannel?, colors?: gradient map of a color channel's procedural or anchor, 1 to 16 colors dark to light ([r, g, b] linear or \"#rrggbb\"; [] removes it; absent keeps it; alone, it changes the channel's source)|gradientMap?: true (turns the color stops on from the channel's current procedural or anchor: a procedural's low, their midpoint and high; an anchor's black, gray and white; stops already there stay), enabled?, solo?: true (this channel on, every other one off)}",
has_layer,
fill_set
),
@@ -51,7 +111,7 @@ pub(crate) fn insert_selected(s: &mut Session, layer: Layer) -> Result<LayerId>
let sel = s.selected_layer();
let inside = sel.and_then(|id| s.doc.project.layer(id).ok()).is_some_and(|l| l.is_group());
let id = s.doc.project.insert_layer(ts, layer, sel, inside)?;
s.selected.insert(ts, id);
s.select_one(ts, id);
s.target = StackTarget::Content;
Ok(id)
}
@@ -110,45 +170,66 @@ fn add_group(s: &mut Session, p: &Value) -> Result<Value> {
}
fn remove(s: &mut Session, p: &Value) -> Result<Value> {
let id = layer_param(s, "layer.remove", p)?;
let ids = batch_param(s, "layer.remove", p, true)?;
let before = s.doc.clone();
let removed = s.edit("Remove layer", |s| {
let (ts, parent, i) = s.doc.project.locate(id).ok_or(EngineError::Other("layer not in a stack".into()))?;
let removed = s.doc.project.remove_layer(id)?;
// Instances of what was removed keep their look as independent layers.
let mut removed = Vec::new();
// Top row first, so the layer under the lowest removed one is never removed after it is chosen
for id in &ids {
let (ts, parent, i) = s.doc.project.locate(*id).ok_or(EngineError::Other("layer not in a stack".into()))?;
removed.extend(s.doc.project.remove_layer(*id)?);
// Select the layer below (or above) the removed one
let list = match parent {
Some(g) => s.doc.project.layer(g).map(|l| l.children().to_vec()).unwrap_or_default(),
None => s.doc.project.texture_set(ts).map(|t| t.stack.clone()).unwrap_or_default(),
};
let next = list.get(i.saturating_sub(1)).or(list.first()).copied().or(parent);
match next {
Some(n) => s.select_one(ts, n),
None => s.select_none(ts),
}
}
// Instances of what was removed keep their look as independent layers
crate::instance_cmds::detach_orphans(s, &before)?;
// Select the layer below (or above) the removed one.
let list = match parent {
Some(g) => s.doc.project.layer(g).map(|l| l.children().to_vec()).unwrap_or_default(),
None => s.doc.project.texture_set(ts).map(|t| t.stack.clone()).unwrap_or_default(),
};
let next = list.get(i.saturating_sub(1)).or(list.first()).copied().or(parent);
match next {
Some(n) => s.selected.insert(ts, n),
None => s.selected.remove(&ts),
};
Ok(removed)
})?;
Ok(json!({ "removed": removed.iter().map(|l| l.0).collect::<Vec<_>>() }))
}
fn duplicate(s: &mut Session, p: &Value) -> Result<Value> {
let id = layer_param(s, "layer.duplicate", p)?;
let (ts, _, _) = s.doc.project.locate(id).ok_or(EngineError::Other("layer not in a stack".into()))?;
let ids = batch_param(s, "layer.duplicate", p, true)?;
let first = ids.first().copied().ok_or_else(|| bad("layer.duplicate", "no layer to duplicate"))?;
let (ts, _, _) = s.doc.project.locate(first).ok_or(EngineError::Other("layer not in a stack".into()))?;
let src = s.doc.clone();
let new = s.edit("Duplicate layer", |s| {
let new = crate::layer_ops::copy_tree(&src, id, &mut s.doc, ts, Some(id), false, 0)?;
let name = format!("{} copy", src.project.layer(id)?.name);
s.doc.project.layer_mut(new)?.name = name;
Ok(new)
let copies = s.edit("Duplicate layer", |s| {
// Insert copies in order above the topmost selected layer, at its folder level
let mut copies = Vec::new();
let mut above = first;
for id in ids.iter().rev() {
let new = crate::layer_ops::copy_tree(&src, *id, &mut s.doc, ts, Some(above), false, 0)?;
let name = format!("{} copy", src.project.layer(*id)?.name);
s.doc.project.layer_mut(new)?.name = name;
copies.insert(0, new);
above = new;
}
Ok(copies)
})?;
s.selected.insert(ts, new);
Ok(json!({ "layer": new.0 }))
// The copies are selected; the active layer's copy stays the active one
let active =
s.selected.get(&ts).and_then(|active| ids.iter().position(|id| id == active)).and_then(|i| copies.get(i)).or(copies.first()).copied().unwrap_or(first);
s.select_several(ts, active, active, copies.clone());
Ok(json!({ "layer": active.0, "layers": ids_json(&copies) }))
}
fn group(s: &mut Session, p: &Value) -> Result<Value> {
let id = layer_param(s, "layer.group", p)?;
let ids = batch_param(s, "layer.group", p, true)?;
let g = s.edit("Group layers", |s| {
// The folder takes the top layer's place and parent; the others follow it in, in stack order
let id = ids.first().copied().ok_or_else(|| bad("layer.group", "no layer to group"))?;
let (ts, _, _) = s.doc.project.locate(id).ok_or(EngineError::Other("layer not in a stack".into()))?;
let gid = s.doc.project.alloc_id();
let name = s.doc.project.next_layer_name(ts, "Folder");
@@ -158,29 +239,51 @@ fn group(s: &mut Session, p: &Value) -> Result<Value> {
b.mode = BlendMode::Passthrough;
}
s.doc.project.insert_layer(ts, gl, Some(id), false)?;
s.doc.project.move_above(id, Some(gid), true)?;
s.selected.insert(ts, gid);
move_stacked(&mut s.doc.project, &ids, Some(gid), true)?;
s.select_one(ts, gid);
Ok(gid)
})?;
Ok(json!({ "layer": g.0 }))
}
fn select(s: &mut Session, p: &Value) -> Result<Value> {
if boolp(p, "all") == Some(true) {
return crate::layer_selection::select_all(s);
}
if p.get("layers").is_some() {
return crate::layer_selection::select_list(s, p);
}
let id = layer_param(s, "layer.select", p)?;
let (ts, _, _) = s.doc.project.locate(id).ok_or_else(|| bad("layer.select", "layer not in a stack"))?;
// Paths paint into the active set
if ts != s.ts() {
s.finish_path()?;
// The clone source is a point of the set it was picked in
s.tool.clone_source = None;
}
// Shift+click and Ctrl/Cmd+click select several layers, each on its content
let range = boolp(p, "range") == Some(true);
if range || boolp(p, "toggle") == Some(true) {
s.active_set = ts;
let active = crate::layer_selection::extend(s, ts, id, range);
s.target = StackTarget::Content;
s.revision = s.revision.wrapping_add(1);
return Ok(json!({ "layer": active.map(|active| active.0), "textureSet": ts, "layers": ids_json(&s.selected_layers()) }));
}
s.active_set = ts;
s.selected.insert(ts, id);
s.select_one(ts, id);
s.target = match p.get("target") {
Some(Value::String(t)) if t == "mask" => {
if s.doc.project.layer(s.doc.project.mask_owner(id))?.mask.is_none() {
return Err(bad("layer.select", "the layer has no mask"));
}
StackTarget::Mask
}
Some(Value::String(t)) if t == "content" => StackTarget::Content,
@@ -192,7 +295,7 @@ fn select(s: &mut Session, p: &Value) -> Result<Value> {
};
s.revision = s.revision.wrapping_add(1);
Ok(json!({ "layer": id.0, "textureSet": ts }))
Ok(json!({ "layer": id.0, "textureSet": ts, "layers": [id.0] }))
}
fn rename(s: &mut Session, p: &Value) -> Result<Value> {
@@ -209,33 +312,105 @@ fn rename(s: &mut Session, p: &Value) -> Result<Value> {
}
fn visible(s: &mut Session, p: &Value) -> Result<Value> {
let id = layer_param(s, "layer.visible", p)?;
let ids = batch_param(s, "layer.visible", p, false)?;
// Use the clicked layer as lead, then the active or top layer if absent
let lead = u64p(p, "layer")
.map(LayerId)
.filter(|lead| ids.contains(lead))
.or(s.selected_layer().filter(|active| ids.contains(active)))
.or(ids.first().copied())
.ok_or_else(|| bad("layer.visible", "no layer given"))?;
let v = s.edit("Layer visibility", |s| {
let l = s.doc.project.layer_mut(id)?;
l.visible = boolp(p, "visible").unwrap_or(!l.visible);
Ok(l.visible)
let v = boolp(p, "visible").unwrap_or(!s.doc.project.layer(lead)?.visible);
for id in &ids {
s.doc.project.layer_mut(*id)?.visible = v;
}
Ok(v)
})?;
Ok(json!({ "visible": v }))
}
/// Move `ids` (top row first) above `target` (inside it when `inside`), keeping their order:
/// the lowest goes first and each next one above it.
fn move_stacked(project: &mut Project, ids: &[LayerId], target: Option<LayerId>, inside: bool) -> Result<()> {
let (mut target, mut inside) = (target, inside);
for id in ids.iter().rev() {
project.move_above(*id, target, inside)?;
(target, inside) = (Some(*id), false);
}
Ok(())
}
/// The positions of the moved layers determine whether a reorder needs an undo step.
fn apply_move(s: &mut Session, ids: &[LayerId], change: impl FnOnce(&mut Project) -> Result<()>) -> Result<Value> {
s.edit_if_changed("Move layer", s.merge_edits, |s| {
let project = &mut s.doc.project;
let previous: Vec<_> = ids.iter().map(|id| project.locate(*id)).collect();
change(project)?;
let changed = ids.iter().map(|id| project.locate(*id)).ne(previous);
Ok((Value::Null, changed))
})
}
/// `layer.move {layers, index | above}`: the listed layers move together, keeping their order.
fn move_layers(s: &mut Session, p: &Value) -> Result<Value> {
let ids = batch_param(s, "layer.move", p, true)?;
if let Some(i) = u64p(p, "index") {
// The lowest one goes to `index` of the texture set's stack, the others right above it in their order
let to = usize::try_from(i).unwrap_or(usize::MAX);
apply_move(s, &ids, |project| {
let mut below = None;
for id in ids.iter().rev() {
match below {
None => {
project.move_above(*id, None, false)?;
project.move_layer(*id, to)?;
}
Some(below) => project.move_above(*id, Some(below), false)?,
}
below = Some(*id);
}
Ok(())
})
} else if p.get("above").is_some() {
let above = u64p(p, "above").map(LayerId);
if above.is_some_and(|above| ids.contains(&above)) {
return Err(bad("layer.move", "`above` is one of the moved layers"));
}
let inside = boolp(p, "inside").unwrap_or(false);
apply_move(s, &ids, |project| move_stacked(project, &ids, above, inside))
} else {
Err(bad("layer.move", "give `index` or `above` with `layers`"))
}
}
fn move_layer(s: &mut Session, p: &Value) -> Result<Value> {
if p.get("layers").is_some() {
return move_layers(s, p);
}
let id = layer_param(s, "layer.move", p)?;
s.edit("Move layer", |s| {
apply_move(s, &[id], |project| {
if let Some(d) = p.get("delta").and_then(Value::as_i64) {
let (_, _, i) = s.doc.project.locate(id).ok_or(EngineError::Other("layer not in a stack".into()))?;
let to = (i as i64 + d).max(0) as usize;
s.doc.project.move_layer(id, to)?;
let (_, _, i) = project.locate(id).ok_or(EngineError::Other("layer not in a stack".into()))?;
// Saturate hostile deltas before the sibling-list clamp
let distance = usize::try_from(d.unsigned_abs()).unwrap_or(usize::MAX);
let to = if d < 0 { i.saturating_sub(distance) } else { i.saturating_add(distance) };
project.move_layer(id, to)?;
} else if let Some(i) = u64p(p, "index") {
s.doc.project.move_layer(id, usize::try_from(i).unwrap_or(usize::MAX))?;
project.move_layer(id, usize::try_from(i).unwrap_or(usize::MAX))?;
} else if p.get("above").is_some() {
let above = u64p(p, "above").map(LayerId);
s.doc.project.move_above(id, above, boolp(p, "inside").unwrap_or(false))?;
project.move_above(id, above, boolp(p, "inside").unwrap_or(false))?;
} else {
return Err(bad("layer.move", "give `delta`, `index` or `above`"));
}
Ok(())
})?;
Ok(Value::Null)
})
}
fn blend(s: &mut Session, p: &Value) -> Result<Value> {
@@ -278,6 +453,35 @@ fn blend(s: &mut Session, p: &Value) -> Result<Value> {
Ok(Value::Null)
}
/// `layer.blending.set`: each listed channel gets its own mode and opacity in one undo step. Channels the layer
/// has disabled stay disabled, and channels not listed stay as they are.
fn blending_set(s: &mut Session, p: &Value) -> Result<Value> {
let id = content_param(s, "layer.blending.set", p)?;
let listed = p.get("channels").and_then(Value::as_object).ok_or_else(|| bad("layer.blending.set", "`channels` is required"))?;
let mut edits: Vec<(Channel, Option<BlendMode>, Option<f32>)> = Vec::new();
for (key, value) in listed {
let channel = Channel::parse(key).ok_or_else(|| bad("layer.blending.set", format!("unknown channel `{key}`")))?;
let mode = blend_param("layer.blending.set", value, "mode")?;
let opacity = f32p(value, "opacity").map(|o| o.clamp(0.0, 1.0));
edits.push((channel, mode, opacity));
}
s.edit("Layer blending", |s| {
let l = s.doc.project.layer_mut(id)?;
for (channel, mode, opacity) in edits {
if let Some(b) = l.channels.get_mut(&channel) {
if let Some(m) = mode {
b.mode = m;
}
if let Some(o) = opacity {
b.opacity = o;
}
}
}
Ok(())
})?;
Ok(Value::Null)
}
/// Which fill `layer.fill.*` edits: a fill layer's (`layer`) or a content fill effect's
/// (`effect`).
#[derive(Clone, Copy)]
@@ -312,7 +516,8 @@ fn fill_mut(s: &mut Session, target: FillTarget) -> Result<&mut Fill> {
fn fill_set(s: &mut Session, p: &Value) -> Result<Value> {
let target = fill_target(s, p, "layer.fill.set")?;
let ch = channel_param("layer.fill.set", p, "channel")?.ok_or_else(|| bad("layer.fill.set", "`channel` is required"))?;
// `solo`: this channel on, every other one off.
// `solo`: this channel on, every other one off
let solo = boolp(p, "solo") == Some(true);
let enabled = if solo { Some(true) } else { boolp(p, "enabled") };
let normal_format = normal_format_param("layer.fill.set", p)?;
@@ -320,6 +525,12 @@ fn fill_set(s: &mut Session, p: &Value) -> Result<Value> {
let high = color_param("layer.fill.set", p, "high")?.unwrap_or([1.0; 3]);
let color = color_param("layer.fill.set", p, "color")?;
let value = color_param("layer.fill.set", p, "value")?;
let colors = ramp_param(p, ch)?;
let init_ramp = boolp(p, "gradientMap") == Some(true);
if init_ramp && colors.is_some() {
return Err(bad("layer.fill.set", "give `gradientMap` or `colors`, not both"));
}
let source = if let Some(kind) = strp(p, "procedural") {
let kind = ProceduralKind::parse(kind).ok_or_else(|| bad("layer.fill.set", format!("unknown procedural `{kind}`")))?;
let mut pr = Procedural::new(kind);
@@ -336,7 +547,7 @@ fn fill_set(s: &mut Session, p: &Value) -> Result<Value> {
pr.balance = v.clamp(-1.0, 1.0);
}
pr.invert = boolp(p, "invert").unwrap_or(false);
Some(Source::Procedural { pattern: pr, low, high })
Some(Source::Procedural { pattern: pr, low, high, ramp: Vec::new() })
} else if let Some(c) = color.or(value) {
Some(Source::Uniform(c))
} else if let Some(name) = strp(p, "image") {
@@ -349,30 +560,38 @@ fn fill_set(s: &mut Session, p: &Value) -> Result<Value> {
let reader = reader.ok_or_else(|| bad("layer.fill.set", "the fill is not in a layer"))?;
let anchor_channel = channel_param("layer.fill.set", p, "anchorChannel")?.unwrap_or(ch);
Some(crate::mask_cmds::anchor_source(s, "layer.fill.set", reader, LayerId(a), anchor_channel)?)
} else if enabled.is_some() || normal_format.is_some() {
} else if enabled.is_some() || normal_format.is_some() || colors.is_some() || init_ramp {
None
} else {
return Err(bad("layer.fill.set", "give `color`, `value`, `procedural`, `image`, `anchor`, `normalFormat`, `enabled` or `solo`"));
return Err(bad("layer.fill.set", "give `color`, `value`, `procedural`, `image`, `anchor`, `colors`, `normalFormat`, `enabled` or `solo`"));
};
if normal_format.is_some() && source.as_ref().is_some_and(|src| !matches!(src, Source::Image { .. })) {
return Err(bad("layer.fill.set", "`normalFormat` goes with `image` or alone"));
}
// A format-only edit leaves the channel on or off.
// A format-only edit leaves the channel on or off
let touches_channel = source.is_some() || enabled.is_some();
s.edit("Set fill", |s| {
let f = fill_mut(s, target)?;
// `normalFormat` alone: the convention of the channel's image.
// `normalFormat` alone: the convention of the channel's image
if let (None, Some(nf)) = (&source, normal_format) {
match f.sources.get_mut(&ch) {
Some(Source::Image { normal_format, .. }) => *normal_format = nf,
_ => return Err(bad("layer.fill.set", "`normalFormat` needs an image on the channel")),
}
}
let colors = if init_ramp { initial_ramp(ch, &source, f.sources.get(&ch))? } else { colors };
let source = with_ramp(ch, f.sources.get(&ch), source, colors)?;
match target {
// A fill effect's channel is on while it has a source.
// A fill effect's channel is on while it has a source
FillTarget::Effect(_) if enabled == Some(false) => {
f.sources.remove(&ch);
}
// Removing stops (`colors: []`) from a channel the fill does not have adds nothing
FillTarget::Effect(_) if source.is_none() && enabled != Some(true) && !f.sources.contains_key(&ch) => {}
FillTarget::Effect(_) => {
let src = source.unwrap_or_else(|| f.source(ch));
f.sources.insert(ch, src);
@@ -400,6 +619,64 @@ fn fill_set(s: &mut Session, p: &Value) -> Result<Value> {
Ok(Value::Null)
}
/// The gradient map stops `colors` gives for channel `ch` (None when absent, empty to remove).
fn ramp_param(p: &Value, ch: Channel) -> Result<Option<Vec<[f32; 3]>>> {
let Some(list) = p.get("colors").filter(|v| !v.is_null()) else { return Ok(None) };
let parsed: Option<Vec<[f32; 3]>> =
list.as_array().and_then(|a| a.iter().map(|c| crate::commands::color_of(c).map(|v| v.map(|x| x.clamp(0.0, 1.0)))).collect());
match parsed {
Some(c) if c.len() <= 16 && (c.is_empty() || ch.kind() == texturecraft_core::ChannelKind::Color) => Ok(Some(c)),
Some(c) if c.len() <= 16 => Err(bad("layer.fill.set", "`colors` (a gradient map) goes on a color channel")),
_ => Err(bad("layer.fill.set", "`colors` must be up to 16 colors ([r, g, b] linear or \"#rrggbb\")")),
}
}
/// The stops `gradientMap: true` turns on for channel `ch`: those the source already has, else a
/// procedural's low, midpoint and high (so its look holds) or an anchor's black, gray and white.
/// `source` is the one the call sets, else the channel's `current` one.
fn initial_ramp(ch: Channel, source: &Option<Source>, current: Option<&Source>) -> Result<Option<Vec<[f32; 3]>>> {
if ch.kind() != texturecraft_core::ChannelKind::Color {
return Err(bad("layer.fill.set", "`gradientMap` goes on a color channel"));
}
if let Some(kept) = current.map(Source::ramp).filter(|r| !r.is_empty()) {
return Ok(Some(kept.to_vec()));
}
match source.as_ref().or(current) {
Some(Source::Procedural { low, high, .. }) => Ok(Some(vec![*low, std::array::from_fn(|k| (low[k] + high[k]) * 0.5), *high])),
Some(Source::Anchor { .. }) => Ok(Some(vec![[0.0; 3], [0.5; 3], [1.0; 3]])),
_ => Err(bad("layer.fill.set", "`gradientMap` needs a procedural or an anchor on the channel")),
}
}
/// `source` (or, for `colors` alone, the channel's `current` source) with its gradient map stops:
/// `colors` when given, else those of `current`, so picking another pattern or anchor keeps them.
/// Only color channels keep stops, so a source copied onto another channel loses them; removing
/// stops (`colors: []`) where there are none changes nothing.
fn with_ramp(ch: Channel, current: Option<&Source>, source: Option<Source>, colors: Option<Vec<[f32; 3]>>) -> Result<Option<Source>> {
let adds = colors.as_ref().is_some_and(|c| !c.is_empty());
let needs = || bad("layer.fill.set", "`colors` needs a procedural or an anchor on the channel");
let mut source = match (source, current) {
(Some(source), _) => source,
(None, Some(current)) if colors.is_some() => current.clone(),
_ if adds => return Err(needs()),
_ => return Ok(None),
};
let kept = match current {
Some(current) if ch.kind() == texturecraft_core::ChannelKind::Color => current.ramp().to_vec(),
_ => Vec::new(),
};
match &mut source {
Source::Procedural { ramp, .. } | Source::Anchor { ramp, .. } => *ramp = colors.unwrap_or(kept),
_ if adds => return Err(needs()),
_ => {}
}
Ok(Some(source))
}
/// The projection `p` asks for. Fields it does not give keep their values from `current` when
/// that is of the same kind (or `p` names no kind), and the kind's defaults otherwise.
pub(crate) fn projection_from(p: &Value, cmd: &str, current: Option<&Projection>) -> Result<Projection> {
+3 -3
View File
@@ -128,7 +128,7 @@ fn paste(s: &mut Session, _: &Value) -> Result<Value> {
let sel = s.selected_layer();
let inside = sel.and_then(|l| s.doc.project.layer(l).ok()).is_some_and(|l| l.is_group());
let new = copy_tree(&src, id, &mut s.doc, ts, sel, inside, 0)?;
s.selected.insert(ts, new);
s.select_one(ts, new);
s.target = StackTarget::Content;
Ok(new)
})?;
@@ -147,8 +147,8 @@ fn to_all_sets(s: &mut Session, p: &Value) -> Result<Value> {
let new = if copy {
copy_tree(&src, id, &mut s.doc, ts, None, false, 0)?
} else {
// On top of the set: clear its selection first.
s.selected.remove(&ts);
// On top of the set: clear its selection first
s.select_none(ts);
crate::instance_cmds::make_instance(s, id, ts)?
};
made.push(new.0);
+260
View File
@@ -0,0 +1,260 @@
//! Several selected layers, as in the reference app: Shift+click selects the rows between the
//! last clicked layer and the clicked one, Ctrl/Cmd+click adds or removes one layer, and the
//! batch layer commands (remove, duplicate, group, visibility, move) act on every selected layer.
//!
//! The selected layer (`Session::selected`) stays the active one the properties panel shows. The
//! layers picked with it live beside it and count only while it is still the layer they were
//! picked with, so any command that selects another layer leaves a single selection without
//! having to know about this one.
use serde_json::{Value, json};
use texturecraft_core::project::MAX_DEPTH;
use texturecraft_core::{LayerId, LayerKind, Project};
use crate::commands::{bad, u64p};
use crate::session::StackTarget;
use crate::{Result, Session};
mod multi_selection;
pub use multi_selection::MultiSelection;
impl Session {
/// Every selected layer of the active texture set, top row first: the selected layer and the
/// layers picked with it (Shift/Ctrl+click), or the selected layer alone.
pub fn selected_layers(&self) -> Vec<LayerId> {
let ts = self.ts();
let picked = self.selection_in(ts);
if picked.len() < 2 {
return picked;
}
stack_rows(&self.doc.project, ts, false).into_iter().filter(|id| picked.contains(id)).collect()
}
/// Whether `id` is one of the [`Session::selected_layers`].
pub fn is_layer_selected(&self, id: LayerId) -> bool {
let ts = self.ts();
let Some(active) = self.active_in(ts) else { return false };
match self.multi.get(&ts).filter(|multi| multi.active == active) {
Some(multi) => multi.layers.contains(&id) && self.doc.project.locate(id).is_some_and(|(set, _, _)| set == ts),
None => active == id,
}
}
/// The selected layer of texture set `ts`, if it is still in that set's stack.
fn active_in(&self, ts: usize) -> Option<LayerId> {
self.selected.get(&ts).copied().filter(|id| self.doc.project.locate(*id).is_some_and(|(t, _, _)| t == ts))
}
/// The layers picked with the selected layer of `ts`, while it is still the one they were
/// picked with.
fn multi_in(&self, ts: usize) -> Option<&MultiSelection> {
let active = self.active_in(ts)?;
self.multi.get(&ts).filter(|multi| multi.active == active)
}
/// The selected layers of texture set `ts` in the order they were picked.
fn selection_in(&self, ts: usize) -> Vec<LayerId> {
match self.multi_in(ts) {
Some(multi) => multi.layers.iter().copied().filter(|id| self.doc.project.locate(*id).is_some_and(|(t, _, _)| t == ts)).collect(),
None => self.active_in(ts).into_iter().collect(),
}
}
/// Select layer `id` alone in texture set `ts`.
pub(crate) fn select_one(&mut self, ts: usize, id: LayerId) {
self.selected.insert(ts, id);
self.multi.remove(&ts);
}
/// Select no layer in texture set `ts`.
pub(crate) fn select_none(&mut self, ts: usize) {
self.selected.remove(&ts);
self.multi.remove(&ts);
}
/// Select `layers` of texture set `ts` with `active` as the active layer (one of them) and
/// `anchor` where the next Shift+click range starts.
pub(crate) fn select_several(&mut self, ts: usize, active: LayerId, anchor: LayerId, layers: Vec<LayerId>) {
self.selected.insert(ts, active);
if layers.len() > 1 {
self.multi.insert(ts, MultiSelection { active, anchor, layers });
} else {
self.multi.remove(&ts);
}
}
}
/// The rows of texture set `ts` from the top, as the Layers panel lists them: each layer, then
/// its children unless `expanded_only` and the folder is collapsed.
pub fn stack_rows(project: &Project, ts: usize, expanded_only: bool) -> Vec<LayerId> {
let mut rows = Vec::new();
if let Some(set) = project.texture_sets.get(ts) {
push_rows(project, &set.stack, expanded_only, 0, &mut rows);
}
rows
}
fn push_rows(project: &Project, list: &[LayerId], expanded_only: bool, depth: usize, rows: &mut Vec<LayerId>) {
if depth > MAX_DEPTH {
return;
}
for id in list.iter().rev() {
let Some(layer) = project.layers.get(id) else { continue };
rows.push(*id);
if let LayerKind::Group { children, collapsed } = &layer.kind
&& !(expanded_only && *collapsed)
{
push_rows(project, children, expanded_only, depth + 1, rows);
}
}
}
/// `layer.select` with `toggle` (Ctrl/Cmd+click) or `range` (Shift+click) on `id` of texture set
/// `ts`. Returns the layer that becomes the active one (none when nothing stays selected).
///
/// A range covers the rows shown between the anchor and `id` (a collapsed folder's layers are
/// not shown, so they are not selected); `id` becomes active and the anchor stays. A toggle adds
/// `id` and makes it the active layer and the anchor, or takes it out when it was selected (the
/// active layer and the anchor stay, or the last picked layer takes their place when it was them);
/// taking out the only selected layer leaves an empty selection.
pub(crate) fn extend(s: &mut Session, ts: usize, id: LayerId, range: bool) -> Option<LayerId> {
let current = s.selection_in(ts);
let anchor = s.multi_in(ts).map(|multi| multi.anchor).filter(|anchor| current.contains(anchor)).or_else(|| s.active_in(ts));
if range {
let rows = stack_rows(&s.doc.project, ts, true);
let span = anchor.and_then(|anchor| Some((anchor, rows.iter().position(|row| *row == anchor)?, rows.iter().position(|row| *row == id)?)));
match span {
Some((anchor, from, to)) => {
let layers = rows.get(from.min(to)..=from.max(to)).map(<[LayerId]>::to_vec).unwrap_or_else(|| vec![id]);
s.select_several(ts, id, anchor, layers);
}
// Nothing to range from (or it is hidden in a collapsed folder): start over at `id`
None => s.select_several(ts, id, id, vec![id]),
}
return Some(id);
}
let mut layers = current;
if layers.contains(&id) {
layers.retain(|layer| *layer != id);
// Taking out the only selected layer leaves nothing selected
let Some(last) = layers.last().copied() else {
s.select_none(ts);
return None;
};
let kept = |layer: Option<LayerId>| layer.filter(|layer| layers.contains(layer)).unwrap_or(last);
let (active, anchor) = (kept(s.active_in(ts)), kept(anchor));
s.select_several(ts, active, anchor, layers);
Some(active)
} else {
layers.push(id);
s.select_several(ts, id, id, layers);
Some(id)
}
}
/// `layer.select {layers, layer?}`: select every layer in `layers` at once, with `layer` (one of
/// them; default the last) as the active one.
pub(crate) fn select_list(s: &mut Session, p: &Value) -> Result<Value> {
let (ts, layers) = ids_param(s, "layer.select", p)?;
let active = match u64p(p, "layer").map(LayerId) {
Some(active) if layers.contains(&active) => active,
Some(_) => return Err(bad("layer.select", "`layer` must be one of `layers`")),
None => layers.last().copied().ok_or_else(|| bad("layer.select", "`layers` is empty"))?,
};
// Paths paint into the active set
if ts != s.ts() {
s.finish_path()?;
s.tool.clone_source = None;
}
s.active_set = ts;
s.select_several(ts, active, active, layers);
s.target = StackTarget::Content;
s.revision = s.revision.wrapping_add(1);
Ok(json!({ "layer": active.0, "textureSet": ts, "layers": ids_json(&s.selected_layers()) }))
}
/// `layer.select {all: true}` (Ctrl/Cmd+A in the Layers panel): every row shown in the active
/// texture set: the folder rows and the layers inside open folders, but not the layers inside
/// collapsed ones. The active layer and the Shift+click anchor stay when they are among them,
/// else the top row takes their place. An empty stack changes nothing.
pub(crate) fn select_all(s: &mut Session) -> Result<Value> {
let ts = s.ts();
let rows = stack_rows(&s.doc.project, ts, true);
let Some(top) = rows.first().copied() else {
return Ok(json!({ "layer": Value::Null, "textureSet": ts, "layers": [] }));
};
let active = s.active_in(ts).filter(|active| rows.contains(active)).unwrap_or(top);
let anchor = s.multi_in(ts).map(|multi| multi.anchor).filter(|anchor| rows.contains(anchor)).unwrap_or(active);
s.select_several(ts, active, anchor, rows);
s.target = StackTarget::Content;
s.revision = s.revision.wrapping_add(1);
Ok(json!({ "layer": active.0, "textureSet": ts, "layers": ids_json(&s.selected_layers()) }))
}
/// The `layers` param: ids of layers in one texture set's stack, without repeats.
fn ids_param(s: &Session, cmd: &str, p: &Value) -> Result<(usize, Vec<LayerId>)> {
let list = p.get("layers").and_then(Value::as_array).ok_or_else(|| bad(cmd, "`layers` must be a list of layer ids"))?;
let mut set = None;
let mut ids = Vec::new();
for value in list {
let id = value.as_u64().map(LayerId).ok_or_else(|| bad(cmd, "`layers` must be a list of layer ids"))?;
let (ts, _, _) = s.doc.project.locate(id).ok_or_else(|| bad(cmd, format!("no layer {} in a stack", id.0)))?;
if *set.get_or_insert(ts) != ts {
return Err(bad(cmd, "`layers` must all be in one texture set"));
}
if !ids.contains(&id) {
ids.push(id);
}
}
let ts = set.ok_or_else(|| bad(cmd, "`layers` is empty"))?;
Ok((ts, ids))
}
/// The layers a batch command acts on, top row first: `layers`, else `layer` alone, else every
/// selected layer. With `outermost`, a layer whose folder is also in the list is left out (the
/// folder takes it along).
pub(crate) fn batch_param(s: &Session, cmd: &str, p: &Value, outermost: bool) -> Result<Vec<LayerId>> {
let ids = if p.get("layers").is_some() {
ids_param(s, cmd, p)?.1
} else if u64p(p, "layer").is_some() {
vec![crate::commands::layer_param(s, cmd, p)?]
} else {
s.selected_layers()
};
if ids.len() < 2 {
return if ids.is_empty() { Err(bad(cmd, "no layer selected and no `layer` given")) } else { Ok(ids) };
}
let project = &s.doc.project;
let Some((ts, _, _)) = ids.first().and_then(|id| project.locate(*id)) else { return Ok(ids) };
Ok(stack_rows(project, ts, false).into_iter().filter(|id| ids.contains(id) && !(outermost && in_listed_folder(project, *id, &ids))).collect())
}
/// Whether a folder holding `id` (at any depth) is in `ids`.
fn in_listed_folder(project: &Project, id: LayerId, ids: &[LayerId]) -> bool {
let mut at = id;
for _ in 0..=MAX_DEPTH {
match project.locate(at) {
Some((_, Some(parent), _)) if ids.contains(&parent) => return true,
Some((_, Some(parent), _)) => at = parent,
_ => return false,
}
}
false
}
pub(crate) fn ids_json(ids: &[LayerId]) -> Vec<u64> {
ids.iter().map(|id| id.0).collect()
}
@@ -0,0 +1,12 @@
use texturecraft_core::LayerId;
/// The layers selected in one texture set together with the active one.
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct MultiSelection {
/// The active layer these were picked with; another selected layer ends the selection.
pub active: LayerId,
/// Where a Shift+click range starts: the last layer clicked without Shift.
pub anchor: LayerId,
/// Every selected layer, the active one included, in the order they were picked.
pub layers: Vec<LayerId>,
}
+15 -1
View File
@@ -20,12 +20,16 @@ pub mod file_cmds;
pub mod fill_hit_test;
pub mod fill_mode;
pub mod filter_lib;
mod frame_target;
pub mod inspect;
pub mod instance_cmds;
pub mod layer_cmds;
pub mod layer_ops;
pub mod layer_selection;
pub mod link_cmds;
mod mask_bitmap;
pub mod mask_cmds;
pub mod mask_export;
mod mask_preview_pixel;
pub mod material_lib;
mod material_preview_pixel;
@@ -42,6 +46,8 @@ pub mod path_tool;
pub mod pbr_cmds;
mod polygon_fill;
mod polygon_fill_drag;
mod polygon_fill_mirror;
mod stencil_look;
// Mesh reimport reads files on native targets only
#[cfg(not(target_arch = "wasm32"))]
mod preserve;
@@ -53,13 +59,16 @@ pub mod resource_cmds;
pub mod session;
pub mod set_cmds;
pub mod smart_masks;
mod solo;
pub mod template_cmds;
pub mod text_cmds;
pub mod thumbs;
mod tool_availability;
pub mod tool_cmds;
pub mod tool_settings;
mod triangle_partition;
mod uv_stroke_state;
mod uv_symmetry;
pub mod uv_tile_cmds;
pub mod view_cmds;
@@ -70,8 +79,13 @@ pub use fill_hit_test::FillHitTest;
pub use fill_mode::FillMode;
pub use path_tool::PathState;
pub use project_cmds::sample_session;
pub use session::{CloneFrom, CloneSource, Document, Session, SetCache, StackTarget, StencilState, Tool, ToolState, ViewMode};
pub use session::{
CloneFrom, CloneSource, Document, HISTORY_TEMPLATES, Session, SetCache, StackTarget, StencilLook, StencilState, Tool, ToolState, ViewMode, history_label,
stroke_template,
};
pub use set_cmds::{ResizeOutput, ResizeTask};
pub use solo::Solo;
pub use tool_settings::ToolSettings;
pub use texturecraft_compose as compose;
pub use texturecraft_core as core;
+2 -1
View File
@@ -351,6 +351,7 @@ impl Session {
if maps.is_empty() {
return Err(EngineError::Other(format!("{} has no maps TextureCraft can paint with", m.manifest.name)));
}
let label = format!("Add {}", m.manifest.name);
let (id, names) = self.edit(&label, |s| {
let ts = s.ts();
@@ -376,7 +377,7 @@ impl Session {
let name = s.doc.project.next_layer_name(ts, &m.manifest.name);
let lid = crate::layer_cmds::insert_selected(s, Layer::new(lid, name, LayerKind::Fill(fill), &channels))?;
place.apply(s, lid)?;
s.selected.insert(ts, lid);
s.select_one(ts, lid);
s.target = crate::session::StackTarget::Content;
Ok((lid, names))
})?;
+28
View File
@@ -0,0 +1,28 @@
use crate::{EngineError, Result};
/// An evaluated mask: `width × height` values in `0..=1`, row by row from the top
#[derive(Clone, Debug, PartialEq)]
pub struct MaskBitmap {
/// UDIM number of the tile (None: the whole texture set)
pub tile: Option<u32>,
pub width: u32,
pub height: u32,
pub values: Vec<f32>,
}
impl MaskBitmap {
/// The values as 16-bit gray levels
pub fn gray16(&self) -> Vec<u16> {
self.values.iter().map(|v| (v.clamp(0.0, 1.0) * 65535.0 + 0.5) as u16).collect()
}
/// The values as 8-bit gray levels
pub fn gray8(&self) -> Vec<u8> {
self.values.iter().map(|v| (v.clamp(0.0, 1.0) * 255.0 + 0.5) as u8).collect()
}
/// A 16-bit grayscale PNG
pub fn to_png16(&self) -> Result<Vec<u8>> {
texturecraft_formats::gray16_png(self.width, self.height, self.values.iter().copied()).map_err(|error| EngineError::Other(error.to_string()))
}
}
+4 -3
View File
@@ -273,11 +273,12 @@ pub(crate) fn anchor_source(s: &Session, cmd: &str, reader: LayerId, anchor: Lay
Some((owner, e)) if matches!(e.kind, EffectKind::Anchor) => owner,
_ => return Err(bad(cmd, format!("{} is not an anchor point", anchor.0))),
};
let (ts, _, _) = s.doc.project.locate(reader).ok_or_else(|| bad(cmd, "layer not in a stack"))?;
let order: Vec<LayerId> = s.doc.project.walk(ts).into_iter().map(|(id, _)| id).collect();
let pos = |id: LayerId| order.iter().position(|x| *x == id);
match (pos(owner), pos(reader)) {
(Some(o), Some(r)) if o < r => Ok(Source::Anchor { anchor, channel }),
(Some(o), Some(r)) if o < r => Ok(Source::Anchor { anchor, channel, ramp: Vec::new() }),
_ => Err(bad(cmd, "the anchor point must be on a layer below this one in the same texture set")),
}
}
@@ -334,7 +335,7 @@ fn add_fill(session: &mut Session, params: &Value) -> Result<Value> {
pattern.seed = seed as u32;
}
Source::Procedural { pattern, low: [0.0; 3], high: [1.0; 3] }
Source::Procedural { pattern, low: [0.0; 3], high: [1.0; 3], ramp: Vec::new() }
}
None => Source::Uniform([f32p(params, "value").unwrap_or(1.0).clamp(0.0, 1.0); 3]),
};
@@ -591,7 +592,7 @@ fn set(session: &mut Session, params: &Value) -> Result<Value> {
let anchor = match session.doc.project.effect(effect) {
Some((owner, Effect { kind: EffectKind::Fill { source, .. }, .. })) => {
let (current, channel) = match source {
Source::Anchor { anchor, channel } => (Some(*anchor), *channel),
Source::Anchor { anchor, channel, .. } => (Some(*anchor), *channel),
_ => (None, Channel::Height),
};
let channel_param = channel_param(CMD, params, "anchorChannel")?;
+115
View File
@@ -0,0 +1,115 @@
//! Mask export: a layer's evaluated mask as a grayscale bitmap at the texture set's resolution
//! (`mask.export`, and the layer menu's "Copy mask to clipboard").
//!
//! The bitmap has the orientation of the exported texture maps (row 0 is the top of the UV
//! square) and is black where the mesh does not cover the texture. A classic texture set gives one
//! bitmap; a UV-tiled set gives one per tile (what the texture export does) or, for the clipboard,
//! one of the whole tile atlas.
use serde_json::Value;
#[cfg(not(target_arch = "wasm32"))]
use serde_json::json;
use texturecraft_core::LayerId;
use crate::commands::{CommandSpec, bad, has_layer};
#[cfg(not(target_arch = "wasm32"))]
use crate::commands::{layer_param, strp};
pub use crate::mask_bitmap::MaskBitmap;
use crate::{EngineError, Result, Session, cmd};
pub fn specs() -> Vec<CommandSpec> {
vec![cmd!(
"mask.export",
"Export mask to file...",
[],
None,
"{layer?, path: .png file} → {files}. Writes the evaluated mask as a 16-bit grayscale PNG at the texture set's resolution, black outside the mesh and oriented like the exported textures. A UV-tiled set writes one file per tile with the tile number before the extension (mask.1001.png). A layer without an enabled mask is an error",
has_layer,
export
)]
}
impl Session {
/// Layer `id`'s evaluated mask: one bitmap per UV tile (`per_tile`) or one of the whole
/// texture set. A tile smaller than its atlas block gives its own size. Errors without an
/// enabled mask.
pub fn mask_bitmaps(&mut self, id: LayerId, per_tile: bool) -> Result<Vec<MaskBitmap>> {
let (ts, _, _) = self.doc.project.locate(id).ok_or_else(|| EngineError::Other(format!("no layer {}", id.0)))?;
self.update();
let atlas = self
.with_inputs(ts, |inputs| texturecraft_compose::mask_texels(inputs, id).map(|values| (inputs.gbuf.width, inputs.gbuf.height, values)))
.ok_or_else(|| EngineError::Other("the layer has no enabled mask".into()))?;
let (width, height, values) = atlas;
let set = self.doc.project.texture_set(ts).map_err(|e| EngineError::Other(e.to_string()))?;
let Some(grid) = set.tile_grid().filter(|_| per_tile) else { return Ok(vec![MaskBitmap { tile: None, width, height, values }]) };
let block = set.block_resolution();
set.uv_tiles
.iter()
.map(|&tile| {
let (block_x, block_y) = grid.block(tile).ok_or_else(|| EngineError::Other(format!("UV tile {tile} is not in the set's grid")))?;
// A tile smaller than its block fills the block's top-left corner
let side = ((block as f32 * set.tile_scale(tile)).round() as u32).clamp(1, block);
let mut tile_values = Vec::with_capacity(side as usize * side as usize);
for row in 0..side {
let start = ((block_y * block + row) as usize) * width as usize + (block_x * block) as usize;
tile_values.extend_from_slice(values.get(start..start + side as usize).unwrap_or(&[]));
}
Ok(MaskBitmap { tile: Some(tile), width: side, height: side, values: tile_values })
})
.collect()
}
}
/// `path` as a `.png` path, with `tile` before the extension for a UV tile.
#[cfg(not(target_arch = "wasm32"))]
fn file_path(path: &str, tile: Option<u32>) -> std::path::PathBuf {
let path = std::path::Path::new(path);
let is_png = path.extension().is_some_and(|e| e.eq_ignore_ascii_case("png"));
let name = path.file_name().map_or_else(|| "mask".into(), |n| n.to_string_lossy().into_owned());
let stem = if is_png { name[..name.len() - 4].to_string() } else { name };
let named = match tile {
Some(tile) => format!("{stem}.{tile}.png"),
None => format!("{stem}.png"),
};
path.with_file_name(named)
}
#[cfg(not(target_arch = "wasm32"))]
fn export(s: &mut Session, p: &Value) -> Result<Value> {
let path = strp(p, "path").filter(|path| !path.trim().is_empty()).ok_or_else(|| bad("mask.export", "`path` is required"))?;
let id = layer_param(s, "mask.export", p)?;
let bitmaps = s.mask_bitmaps(id, true)?;
let mut files = Vec::new();
for bitmap in &bitmaps {
let file = file_path(path, bitmap.tile);
texturecraft_formats::write_atomic(&file, &bitmap.to_png16()?).map_err(|e| bad("mask.export", format!("cannot write {}: {e}", file.display())))?;
files.push(file.display().to_string());
}
s.log.push(format!("Exported the mask to {}", files.join(", ")));
Ok(json!({ "files": files }))
}
#[cfg(target_arch = "wasm32")]
fn export(_: &mut Session, _: &Value) -> Result<Value> {
Err(bad("mask.export", "writing files is not available in the browser"))
}
#[cfg(all(test, not(target_arch = "wasm32")))]
mod tests {
use super::file_path;
#[test]
fn the_tile_number_goes_before_the_png_extension() {
// Compared as paths: Windows writes the folder with backslashes
let name = |path: &str, tile| {
let file = file_path(path, tile);
assert_eq!(file.parent(), std::path::Path::new(path).parent(), "the folder is kept");
file.file_name().unwrap().to_string_lossy().into_owned()
};
assert_eq!(name("/a/mask.png", None), "mask.png");
assert_eq!(name("/a/mask", None), "mask.png");
assert_eq!(name("/a/mask.PNG", Some(1002)), "mask.1002.png");
assert_eq!(name("/a/skin.v2", Some(1001)), "skin.v2.1001.png");
}
}
+21 -11
View File
@@ -25,7 +25,7 @@ pub fn specs() -> Vec<CommandSpec> {
"Add smart material from file",
[],
None,
"{path: .tcmat smart material, .mcmat MaterialCraft material or .mcraft package, above?: layer id, inside?: bool, index?: n} — above the selection by default, or placed like material.apply",
"{path: .tcmat smart material, .mcmat MaterialCraft material or .mcraft package, above?: layer id, inside?: bool, below?: layer id, top?: true, index?: n} — above the selection by default, or placed like material.apply",
always,
load
),
@@ -59,24 +59,33 @@ pub(crate) fn images_used(project: &Project, id: LayerId, out: &mut Vec<String>,
}
}
/// An empty document with one texture set shaped like `src_set` (size, tiles, channels): what a saved library file holds.
pub(crate) fn one_set_document(src_set: &TextureSet, name: &str) -> Document {
let mut project = Project::new(name, "builtin:none");
let mut set = TextureSet::new(name, 0, src_set.resolution);
set.uv_tiles = src_set.uv_tiles.clone();
set.tile_resolutions = src_set.tile_resolutions.clone();
set.channels = src_set.channels.clone();
project.texture_sets.push(set);
Document { bake_paint: BTreeMap::new(), project, pixels: PixelStore::default(), baked: BTreeMap::new(), resources: BTreeMap::new() }
}
impl Session {
/// Serialize layer `id` (with children, pixels and images) as a smart material file.
pub fn smart_material_bytes(&self, id: LayerId, name: &str) -> Result<Vec<u8>> {
let (ts, _, _) = self.doc.project.locate(id).ok_or_else(|| EngineError::Other("layer not in a stack".into()))?;
let src_set = self.doc.project.texture_set(ts)?;
let mut project = Project::new(name, "builtin:none");
let mut set = TextureSet::new(name, 0, src_set.resolution);
set.uv_tiles = src_set.uv_tiles.clone();
set.tile_resolutions = src_set.tile_resolutions.clone();
set.channels = src_set.channels.clone();
project.texture_sets.push(set);
let mut mini = Document { bake_paint: BTreeMap::new(), project, pixels: PixelStore::default(), baked: BTreeMap::new(), resources: BTreeMap::new() };
let mut mini = one_set_document(self.doc.project.texture_set(ts)?, name);
let new = crate::layer_ops::copy_tree(&self.doc, id, &mut mini, 0, None, false, 0)?;
if let Ok(l) = mini.project.layer_mut(new) {
l.name = name.to_string();
}
self.file_bytes(mini, new)
}
/// The smart material file holding `mini` (a document from [`one_set_document`]) and the images layer `root` of it uses.
pub(crate) fn file_bytes(&self, mini: Document, root: LayerId) -> Result<Vec<u8>> {
let mut used = Vec::new();
images_used(&mini.project, new, &mut used, 0);
images_used(&mini.project, root, &mut used, 0);
let resources = used.iter().filter_map(|n| self.doc.resources.get(n).map(|b| (n.clone(), b.as_ref().clone()))).collect();
let pf = texturecraft_formats::ProjectFile {
project: mini.project,
@@ -104,6 +113,7 @@ impl Session {
if texturecraft_formats::mcmat::is_mcmat(bytes) || texturecraft_formats::mcmat::is_mcraft(bytes) {
return self.add_linked_material_bytes_at(bytes, place);
}
let pf = texturecraft_formats::load_project_bytes(bytes).map_err(fe)?;
let root = pf
.project
@@ -122,7 +132,7 @@ impl Session {
let inside = sel.and_then(|l| s.doc.project.layer(l).ok()).is_some_and(|l| l.is_group());
let id = crate::layer_ops::copy_tree(&src, root, &mut s.doc, ts, sel, inside, 0)?;
place.apply(s, id)?;
s.selected.insert(ts, id);
s.select_one(ts, id);
s.target = StackTarget::Content;
Ok(id)
})?;
+114 -30
View File
@@ -167,7 +167,7 @@ fn rgb(c: [f32; 3]) -> Source {
}
fn pat(kind: ProceduralKind, scale: f32, seed: u32, contrast: f32, low: [f32; 3], high: [f32; 3]) -> Source {
Source::Procedural { pattern: Procedural { kind, scale, seed, contrast, balance: 0.0, invert: false }, low, high }
Source::Procedural { pattern: Procedural { kind, scale, seed, contrast, balance: 0.0, invert: false }, low, high, ramp: Vec::new() }
}
/// A scalar pattern between `lo` and `hi`.
@@ -241,7 +241,8 @@ pub(crate) fn build(b: &mut Builder, id: &str) -> Result<Vec<Layer>> {
use ProceduralKind as P;
let m = find(id).ok_or_else(|| EngineError::Other(format!("unknown material `{id}`")))?;
let one = |b: &mut Builder, s: Sources| -> Result<Vec<Layer>> { Ok(vec![b.fill(m.label, s)]) };
// A simple metal: subtle cloudy tone and roughness variation around the table values.
// A simple metal: subtle cloudy tone and roughness variation around the table values
let plain_metal = |b: &mut Builder, rough: Source| {
let lo = m.base.map(|v| v * 0.94);
one(b, metal(pat(P::Clouds, 3.0, 5, 1.0, lo, m.base), rough))
@@ -253,9 +254,11 @@ pub(crate) fn build(b: &mut Builder, id: &str) -> Result<Vec<Layer>> {
"steel" | "steel_dark" | "iron" | "copper" | "brass" | "bronze" | "gold_polished" | "silver" | "aluminium" | "chrome" | "nickel" | "platinum"
| "cobalt" => plain_metal(b, clouds_rough(7)),
"steel_stainless" | "aluminium_brushed" | "titanium" => plain_metal(b, gray(P::Brushed, 3.0, 3, r * 0.75, r * 1.25)),
// Zinc plate: large crystalline spangles.
// Zinc plate: large crystalline spangles
"zinc" => one(b, metal(pat(P::Voronoi, 6.0, 21, 1.0, m.base.map(|v| v * 0.8), m.base), gray(P::Voronoi, 6.0, 21, r * 1.5, r * 0.6))),
// Brushing lines run along X; the highlights stretch across them (a quarter turn).
// Brushing lines run along X; the highlights stretch across them (a quarter turn)
"steel_brushed_aniso" => one(
b,
plus(
@@ -274,7 +277,8 @@ pub(crate) fn build(b: &mut Builder, id: &str) -> Result<Vec<Layer>> {
height(gray(P::Hammered, 6.0, 1, -0.04, 0.0)),
),
),
// Iron oxide is a dielectric: rough, pitted, blotchy orange-brown.
// Iron oxide is a dielectric: rough, pitted, blotchy orange-brown
"rust" => one(
b,
plus(
@@ -292,14 +296,17 @@ pub(crate) fn build(b: &mut Builder, id: &str) -> Result<Vec<Layer>> {
"sandstone" => {
one(b, plus(dielectric(pat(P::Noise, 4.0, 13, 1.0, [0.42, 0.3, 0.18], [0.6, 0.45, 0.28]), u(0.9)), height(gray(P::Perlin, 6.0, 13, -0.01, 0.0))))
}
// Stone chips in a pale binder, polished flat.
// Stone chips in a pale binder, polished flat
"terrazzo" => one(b, dielectric(pat(P::Voronoi, 18.0, 9, 1.0, [0.55, 0.55, 0.53], [0.85, 0.84, 0.8]), gray(P::Voronoi, 18.0, 9, 0.34, 0.26))),
// Fine grains in soft wind ripples.
// Fine grains in soft wind ripples
"sand" => one(
b,
plus(dielectric(pat(P::Noise, 12.0, 27, 1.0, [0.42, 0.32, 0.19], [0.6, 0.48, 0.31]), u(0.95)), height(gray(P::Perlin, 4.0, 27, -0.012, 0.0))),
),
// Glossy wet patches over rougher, drier mud.
// Glossy wet patches over rougher, drier mud
"mud" => one(
b,
plus(
@@ -307,7 +314,8 @@ pub(crate) fn build(b: &mut Builder, id: &str) -> Result<Vec<Layer>> {
height(gray(P::Clouds, 3.0, 29, -0.03, 0.0)),
),
),
// Rounded stones with deep joints between them.
// Rounded stones with deep joints between them
"cobblestone" => one(
b,
plus(
@@ -315,7 +323,8 @@ pub(crate) fn build(b: &mut Builder, id: &str) -> Result<Vec<Layer>> {
height(gray(P::Cells, 6.0, 37, 0.0, -0.05)),
),
),
// Small loose stones of mixed tones.
// Small loose stones of mixed tones
"gravel" => one(
b,
plus(
@@ -323,7 +332,8 @@ pub(crate) fn build(b: &mut Builder, id: &str) -> Result<Vec<Layer>> {
height(gray(P::Cells, 30.0, 39, -0.03, 0.0)),
),
),
// Troweled wall: soft patches and a fine sandy tooth.
// Troweled wall: soft patches and a fine sandy tooth
"plaster" => one(
b,
plus(
@@ -331,7 +341,8 @@ pub(crate) fn build(b: &mut Builder, id: &str) -> Result<Vec<Layer>> {
height(gray(P::Clouds, 2.0, 41, -0.008, 0.0)),
),
),
// Low cushions of tiny leaves.
// Low cushions of tiny leaves
"moss" => one(
b,
plus(
@@ -347,6 +358,7 @@ pub(crate) fn build(b: &mut Builder, id: &str) -> Result<Vec<Layer>> {
plus(dielectric(pat(P::Clouds, 8.0, 19, 1.0, [0.78, 0.77, 0.73], [0.86, 0.85, 0.81]), u(0.92)), height(gray(P::Noise, 1.0, 19, -0.002, 0.0))),
),
"galvanized" => one(b, metal(pat(P::Voronoi, 10.0, 4, 1.0, [0.6, 0.62, 0.63], [0.78, 0.8, 0.81]), gray(P::Voronoi, 10.0, 4, 0.5, 0.28))),
// ---- Woods (grain along X, rings across Y) ---------------------------------------------
"wood" => one(
b,
@@ -374,12 +386,14 @@ pub(crate) fn build(b: &mut Builder, id: &str) -> Result<Vec<Layer>> {
),
),
"plywood" => one(b, dielectric(pat(P::Wood, 1.2, 15, 0.6, [0.42, 0.27, 0.13], [0.66, 0.47, 0.27]), gray(P::Wood, 1.2, 15, 0.8, 0.7))),
// Dark, deep furrows between gray-brown ridges.
// Dark, deep furrows between gray-brown ridges
"bark" => one(
b,
plus(dielectric(pat(P::Streaks, 8.0, 25, 1.4, [0.13, 0.105, 0.08], [0.03, 0.022, 0.015]), u(0.9)), height(gray(P::Streaks, 8.0, 25, 0.0, -0.06))),
),
// Pale, fine and even grain.
// Pale, fine and even grain
"wood_maple" => one(
b,
plus(
@@ -387,7 +401,8 @@ pub(crate) fn build(b: &mut Builder, id: &str) -> Result<Vec<Layer>> {
height(gray(P::Wood, 3.0, 31, -0.006, 0.0)),
),
),
// Reddish heartwood with a satin finish.
// Reddish heartwood with a satin finish
"wood_cherry" => one(
b,
plus(
@@ -395,7 +410,8 @@ pub(crate) fn build(b: &mut Builder, id: &str) -> Result<Vec<Layer>> {
height(gray(P::Wood, 2.2, 33, -0.008, 0.0)),
),
),
// Long straight fibres with a few raised ridges.
// Long straight fibres with a few raised ridges
"bamboo" => one(
b,
plus(
@@ -410,6 +426,7 @@ pub(crate) fn build(b: &mut Builder, id: &str) -> Result<Vec<Layer>> {
height(gray(P::Wood, 2.0, 7, -0.015, 0.0)),
),
),
// ---- Stone, masonry, earth ----------------------------------------------------------
"concrete" => one(
b,
@@ -446,11 +463,13 @@ pub(crate) fn build(b: &mut Builder, id: &str) -> Result<Vec<Layer>> {
b,
plus(dielectric(pat(P::Clouds, 5.0, 2, 1.0, [0.4, 0.15, 0.07], [0.5, 0.21, 0.11]), clouds_rough(2)), height(gray(P::Noise, 0.8, 3, -0.005, 0.005))),
),
// ---- Plastics, rubber, composites ---------------------------------------------------
"plastic_glossy" | "plastic_matte" | "ceramic" => one(b, dielectric(rgb(m.base), clouds_rough(9))),
"plastic_textured" => one(b, plus(dielectric(rgb(m.base), gray(P::Leather, 40.0, 5, 0.66, 0.5)), height(gray(P::Leather, 40.0, 5, -0.01, 0.0)))),
"rubber" => one(b, dielectric(pat(P::Noise, 0.5, 3, 1.0, [0.025; 3], [0.035; 3]), gray(P::Noise, 0.5, 3, 0.84, 0.94))),
// Twill-woven tows under a clear coat: the warp catches the light, the weft stays dark.
// Twill-woven tows under a clear coat: the warp catches the light, the weft stays dark
"carbon_fiber" => one(
b,
plus(
@@ -458,19 +477,23 @@ pub(crate) fn build(b: &mut Builder, id: &str) -> Result<Vec<Layer>> {
[(CoatWeight, u(1.0)), (CoatRoughness, u(r * 0.2)), (Height, gray(P::Twill, 12.0, 1, 0.0, 0.002))],
),
),
// ---- Fabric and leather -------------------------------------------------------------
"fabric" => {
one(b, plus(dielectric(pat(P::Weave, 18.0, 2, 1.0, [0.27, 0.29, 0.34], [0.6, 0.62, 0.7]), u(r)), height(gray(P::Weave, 18.0, 2, -0.01, 0.0))))
}
// Indigo twill: diagonal ribs.
// Indigo twill: diagonal ribs
"denim" => {
one(b, plus(dielectric(pat(P::Twill, 22.0, 5, 1.0, [0.015, 0.025, 0.07], [0.15, 0.2, 0.38]), u(r)), height(gray(P::Twill, 22.0, 5, -0.01, 0.0))))
}
// Coarse, slubby plain weave.
// Coarse, slubby plain weave
"linen" => {
one(b, plus(dielectric(pat(P::Weave, 30.0, 45, 1.0, [0.58, 0.52, 0.42], [0.8, 0.74, 0.62]), u(r)), height(gray(P::Weave, 30.0, 45, -0.006, 0.0))))
}
// Fuzzy knit: no visible threads, a soft sheen at grazing angles.
// Fuzzy knit: no visible threads, a soft sheen at grazing angles
"wool" => one(
b,
plus(
@@ -495,11 +518,12 @@ pub(crate) fn build(b: &mut Builder, id: &str) -> Result<Vec<Layer>> {
"velvet" => one(
b,
plus(
// A pile, not a weave: soft crushed patches under a bright sheen.
// A pile, not a weave: soft crushed patches under a bright sheen
dielectric(pat(P::Clouds, 3.0, 3, 1.0, [0.06, 0.006, 0.045], m.base), u(r)),
[(SheenWeight, u(1.0)), (SheenColor, rgb([0.95, 0.55, 0.85])), (SheenRoughness, u(0.35)), (Height, gray(P::Noise, 1.0, 3, -0.002, 0.0))],
),
),
// ---- Coated and translucent ---------------------------------------------------------
"car_paint" => one(
b,
@@ -516,14 +540,17 @@ pub(crate) fn build(b: &mut Builder, id: &str) -> Result<Vec<Layer>> {
),
),
"wax" => one(b, plus(dielectric(pat(P::Clouds, 2.0, 11, 1.0, [0.74, 0.66, 0.5], m.base), clouds_rough(11)), [(ScatterWeight, u(1.0))])),
// ---- Glass (the Transmission channel; the base color tints the light going through) ----
"glass" => one(b, plus(dielectric(rgb(m.base), u(r)), [(Transmission, u(1.0))])),
// Clear with cloudy patches of trapped air.
// Clear with cloudy patches of trapped air
"ice" => one(
b,
plus(dielectric(pat(P::Clouds, 4.0, 31, 1.0, m.base, [0.84, 0.88, 0.9]), clouds_rough(31)), [(Transmission, gray(P::Clouds, 4.0, 31, 0.9, 0.5))]),
),
// Bright, rough and slightly translucent.
// Bright, rough and slightly translucent
"snow" => one(
b,
plus(
@@ -531,7 +558,8 @@ pub(crate) fn build(b: &mut Builder, id: &str) -> Result<Vec<Layer>> {
[(ScatterWeight, u(0.5)), (Height, gray(P::Perlin, 3.0, 33, -0.02, 0.0))],
),
),
// Porous, ivory to tan, with a little light under the surface.
// Porous, ivory to tan, with a little light under the surface
"bone" => one(
b,
plus(
@@ -540,6 +568,7 @@ pub(crate) fn build(b: &mut Builder, id: &str) -> Result<Vec<Layer>> {
),
),
"glass_frosted" => one(b, plus(dielectric(rgb(m.base), gray(P::Noise, 1.0, 2, 0.4, 0.5)), [(Transmission, u(1.0))])),
// ---- Smart materials ----------------------------------------------------------------
"steel_painted_worn" => {
let mut v = build(b, "steel")?;
@@ -715,6 +744,47 @@ pub(crate) fn build(b: &mut Builder, id: &str) -> Result<Vec<Layer>> {
}
}
/// The channel sources of simple material `id`: its single, unmasked fill layer. `None` for smart
/// materials (several layers, or a masked layer) and for unknown ids: a brush paints one fill's
/// sources, so those stay layers.
pub fn brush_sources(id: &str) -> Option<Vec<(Channel, Source)>> {
let m = find(id).filter(|m| !m.smart)?;
let mut scratch = Project::new("", "");
let layers = build(&mut Builder { p: &mut scratch, channels: Channel::LOBES.to_vec() }, m.id).ok()?;
let [layer] = layers.as_slice() else { return None };
let LayerKind::Fill(fill) = &layer.kind else { return None };
if layer.mask.is_some() {
return None;
}
Some(fill.sources.iter().map(|(channel, source)| (*channel, source.clone())).collect())
}
/// The brush's plain values for simple material `id`, one per channel it sets (what the tool's
/// material shows): a pattern counts as the middle between its two values. `None` as
/// [`brush_sources`].
pub fn brush_values(id: &str) -> Option<Vec<(Channel, [f32; 3])>> {
let mean = |low: &[f32; 3], high: &[f32; 3]| std::array::from_fn(|i| (low[i] + high[i]) * 0.5);
Some(
brush_sources(id)?
.into_iter()
.filter_map(|(channel, source)| match source {
Source::Uniform(value) => Some((channel, value)),
Source::Procedural { low, high, .. } => Some((channel, mean(&low, &high))),
Source::Image { .. } | Source::Anchor { .. } => None,
})
.collect(),
)
}
/// The fill a brush material paints through, as a layer: `sources` projected tri-planar at
/// `scale` (the same fill evaluation a layer with that material uses).
pub(crate) fn brush_fill(id: LayerId, sources: Vec<(Channel, Source)>, scale: f32) -> Layer {
let channels: Vec<Channel> = sources.iter().map(|(channel, _)| *channel).collect();
let projection = Projection::Triplanar { scale, sharpness: 8.0, offset: [0.0; 3] };
Layer::new(id, "Brush material", LayerKind::Fill(Fill { sources: sources.into_iter().collect(), projection, link: None }), &channels)
}
/// Where [`apply_at`] puts a material.
#[derive(Clone, Copy, Debug)]
pub enum Place {
@@ -724,6 +794,10 @@ pub enum Place {
Above(LayerId, bool),
/// At this index of the top-level stack (0 = bottom).
Index(usize),
/// Directly below a layer, in the same stack or folder (a shelf drop on a layer row).
Below(LayerId),
/// At the top of the top-level stack (a shelf drop on the 3D or 2D view).
Top,
}
/// Add material `id` above the selection: a single fill layer, or a folder for multi-layer
@@ -739,7 +813,8 @@ pub fn apply_at(s: &mut Session, id: &str, place: Place) -> Result<LayerId> {
s.edit(&label, |s| {
let ts = s.ts();
let mut channels = s.doc.project.texture_set(ts)?.channel_list();
// Lobe channels the material uses join the texture set (other channels it lacks are skipped).
// Lobe channels the material uses join the texture set (other channels it lacks are skipped)
let missing: Vec<Channel> = Channel::LOBES.into_iter().filter(|c| !channels.contains(c)).collect();
let layers = build(&mut Builder { p: &mut s.doc.project, channels: [channels.clone(), missing.clone()].concat() }, m.id)?;
for c in missing.into_iter().filter(|c| layers.iter().any(|l| l.channels.contains_key(c))) {
@@ -759,7 +834,7 @@ pub fn apply_at(s: &mut Session, id: &str, place: Place) -> Result<LayerId> {
for l in layers {
s.doc.project.insert_layer(ts, l, Some(gid), true)?;
}
s.selected.insert(ts, gid);
s.select_one(ts, gid);
gid
};
place.apply(s, top)?;
@@ -770,10 +845,12 @@ pub fn apply_at(s: &mut Session, id: &str, place: Place) -> Result<LayerId> {
impl Place {
/// From `above` (+ `inside`) or `index` params; the selection by default.
pub(crate) fn from_params(p: &serde_json::Value) -> Place {
match (crate::commands::u64p(p, "above"), crate::commands::u64p(p, "index")) {
(Some(above), _) => Place::Above(LayerId(above), crate::commands::boolp(p, "inside").unwrap_or(false)),
(None, Some(i)) => Place::Index(usize::try_from(i).unwrap_or(usize::MAX)),
(None, None) => Place::Selection,
match (crate::commands::u64p(p, "above"), crate::commands::u64p(p, "below"), crate::commands::u64p(p, "index")) {
(Some(above), _, _) => Place::Above(LayerId(above), crate::commands::boolp(p, "inside").unwrap_or(false)),
(None, Some(below), _) => Place::Below(LayerId(below)),
(None, None, Some(i)) => Place::Index(usize::try_from(i).unwrap_or(usize::MAX)),
(None, None, None) if crate::commands::boolp(p, "top") == Some(true) => Place::Top,
(None, None, None) => Place::Selection,
}
}
@@ -786,6 +863,13 @@ impl Place {
s.doc.project.move_above(top, None, false)?;
s.doc.project.move_layer(top, i)?;
}
Place::Below(target) => {
s.doc.project.move_above(top, Some(target), false)?;
if let Some((_, _, index)) = s.doc.project.locate(top) {
s.doc.project.move_layer(top, index.saturating_sub(1))?;
}
}
Place::Top => s.doc.project.move_above(top, None, false)?,
}
Ok(())
}
+170 -47
View File
@@ -4,17 +4,24 @@
use std::collections::{BTreeMap, BTreeSet};
use texturecraft_compose::PaintTarget;
use texturecraft_core::{Channel, Effect, EffectKind, LayerId, LayerKind, Mask, MaskBackground};
use texturecraft_core::{Channel, Effect, EffectKind, LayerId, LayerKind, Mask, MaskBackground, Source};
use texturecraft_geom::glam::Vec2;
use texturecraft_paint::{
CommitSource, EyeDepth, PickCtx, Pickup, PickupMode, RasterCtx, Shape, Staging, Stroke, StrokeCanvas, SurfaceHit, commit_layer, commit_mask, pick,
rasterize,
};
use crate::session::{ActiveStroke, CloneFrom, Session, StackTarget, Tool};
use crate::session::{ActiveStroke, CloneFrom, QUICK_MASK_STROKE_LABEL, Session, StackTarget, Tool, history_label, stroke_template};
use crate::uv_stroke_state::UvStrokeState;
use crate::uv_symmetry::UvMirror;
use crate::{EngineError, Result};
/// The brush size (as in `BrushSettings::size`) at which a brush material's pattern has its natural size; a smaller brush makes the pattern smaller in proportion
pub const BRUSH_PATTERN_SIZE: f32 = 0.1;
/// Brush size floor for the pattern scale
const MIN_PATTERN_BRUSH_SIZE: f32 = 0.0005;
/// Shortest distance between 2D view stamps, so a stamp with no radius (a pen at zero pressure) can't stall a stroke.
const MIN_UV_STAMP_STEP: f32 = 1e-5;
@@ -59,7 +66,8 @@ impl Session {
/// when painting a mask. Must run inside the stroke's history snapshot.
fn paint_target(&mut self) -> Result<PaintTarget> {
let id = self.selected_layer().ok_or_else(|| EngineError::Other("select a layer to paint on".into()))?;
// Painting an instance paints its source (its own mask when it overrides the mask).
// Painting an instance paints its source unless its own mask overrides the mask
let p = &self.doc.project;
let id = if self.target == StackTarget::Mask { p.mask_owner(id) } else { p.content_layer(id).map_or(id, |l| l.id) };
match self.target {
@@ -72,12 +80,13 @@ impl Session {
}
}
StackTarget::Effect(e) => match self.doc.project.effect(e) {
// Content paint effects hold channel pixels like a paint layer.
// Content paint effects hold channel pixels like a paint layer
Some((owner, eff)) if matches!(eff.kind, EffectKind::Paint) => {
let content = self.doc.project.layer(owner)?.content_effects.iter().any(|x| x.id == e);
Ok(if content { PaintTarget::Layer(e) } else { PaintTarget::Mask(e) })
}
// Path sublayers are painted only from their stored paths.
// Path sublayers are painted only from their stored paths
Some((owner, eff)) if matches!(eff.kind, EffectKind::Path(_)) && self.painting_paths => {
let content = self.doc.project.layer(owner)?.content_effects.iter().any(|x| x.id == e);
Ok(if content { PaintTarget::Layer(e) } else { PaintTarget::Mask(e) })
@@ -85,8 +94,8 @@ impl Session {
Some((_, eff)) if matches!(eff.kind, EffectKind::Path(_)) => {
Err(EngineError::Other("a path sublayer holds paths only: edit them with the Path tool, or paint on a paint sublayer".into()))
}
// A filter (or another effect) is selected, e.g. just added from the shelf: paint
// what lies beneath it, so the new paint goes through it.
// Paint below a selected non-paint effect so new paint passes through it
Some((owner, _)) => self.paint_target_below(owner, e),
None => Err(EngineError::Other("the selected effect is not a paint effect".into())),
},
@@ -97,12 +106,26 @@ impl Session {
if let Some(top) = mask.effects.last().filter(|e| matches!(e.kind, EffectKind::Paint)) {
return Ok(PaintTarget::Mask(top.id));
}
mask.effects.push(Effect::new(eid, EffectKind::Paint));
Ok(PaintTarget::Mask(eid))
}
}
}
/// Whether the stroke the selection starts paints a mask (the layer's mask, or a paint or
/// filter sublayer inside it).
fn paints_mask(&self) -> bool {
match self.target {
StackTarget::Content => false,
StackTarget::Mask => true,
StackTarget::Effect(effect) => {
let project = &self.doc.project;
project.effect(effect).and_then(|(owner, _)| project.layers.get(&owner)).is_some_and(|l| !l.content_effects.iter().any(|e| e.id == effect))
}
}
}
/// What a stroke paints while non-paint effect `effect` of layer `owner` is selected: the
/// nearest paint effect below it in the same stack, else the paint layer's own pixels (for
/// content) or a new paint effect inserted just below it (for a mask).
@@ -133,11 +156,44 @@ impl Session {
Ok(PaintTarget::Mask(eid))
}
/// The pattern of the brush's material (`tool.material`) as a pickup over the texture, for the
/// channels in `values`: the material's fill, evaluated with the compose fill code tri-planar
/// in world space, so it stays fixed to the surface and continuous across stamps and strokes.
/// Its size follows the brush size ([`BRUSH_PATTERN_SIZE`] is the natural size). Channels the
/// material lacks carry the tool's value. None without a brush material.
fn brush_pattern(&self, values: &BTreeMap<Channel, [f32; 3]>) -> Option<Pickup> {
let id = self.tool.material.clone()?;
let mut sources = crate::materials::brush_sources(&id)?;
sources.retain(|(channel, _)| values.contains_key(channel));
for (channel, value) in values {
if !sources.iter().any(|(set, _)| set == channel) {
sources.push((*channel, Source::Uniform(*value)));
}
}
let ts = self.ts();
let set = self.doc.project.texture_sets.get(ts)?;
let mut project = crate::material_lib::one_set_document(set, "Brush material").project;
let layer_id = project.alloc_id();
let scale = BRUSH_PATTERN_SIZE / self.tool.brush.size.max(MIN_PATTERN_BRUSH_SIZE);
project.insert_layer(0, crate::materials::brush_fill(layer_id, sources, scale), None, false).ok()?;
let snapshot = texturecraft_paint::pickup::PickupSnapshot {
project,
ts: 0,
target: PaintTarget::Layer(layer_id),
mesh: self.mesh.clone(),
bounds: self.mesh.bounds(),
pixels: Default::default(),
baked: self.doc.baked.get(&ts).cloned().unwrap_or_default(),
images: Default::default(),
};
Some(Pickup::from_snapshot(PickupMode::Clone { offset: [0; 2] }, snapshot, self.caches.get(ts)?.gbuf.clone(), values.keys().copied()))
}
fn stroke_values(&self, target: PaintTarget) -> BTreeMap<Channel, [f32; 3]> {
let ts = self.ts();
let Ok(set) = self.doc.project.texture_set(ts) else { return BTreeMap::new() };
let layer_channels = match target {
// A content paint effect paints its owner layer's channels.
// A content paint effect paints its owner layer's channels
PaintTarget::Layer(id) => {
let owner = self.doc.project.effect(id).map(|(owner, _)| owner).unwrap_or(id);
self.doc.project.layer(owner).map(|l| l.channels.keys().copied().collect::<BTreeSet<_>>()).unwrap_or_default()
@@ -162,13 +218,15 @@ impl Session {
let ts = self.ts();
let size = self.caches.get(ts).map(|c| c.size).unwrap_or((1024, 1024));
let pickup = if quick_mask { None } else { self.pickup_mode(first_uv)? };
if pickup.is_some() {
// Clone and smudge read the composite: bring it up to date first.
let composite_pickup = tool == Tool::Smudge || (tool == Tool::Clone && self.tool.clone_from == CloneFrom::Composite);
if pickup.is_some() && composite_pickup && !self.paints_mask() && self.solo.is_none() {
// Only a composite pickup reads the viewport cache
self.update();
}
// Cloning from the selected layer reads that layer alone.
// Cloning from the selected layer reads that layer alone
let layer_source = match self.selected_layer() {
Some(id) if pickup.is_some() && tool == Tool::Clone && self.tool.clone_from == CloneFrom::Layer => {
Some(id) if pickup.is_some() && tool == Tool::Clone && self.tool.clone_from == CloneFrom::Layer && !self.paints_mask() => {
Some(self.flatten(ts, id).ok_or_else(|| EngineError::Other("clone from a paint or fill layer (folders have no content of their own)".into()))?)
}
_ => None,
@@ -186,11 +244,15 @@ impl Session {
}
};
let values = target.map(|t| self.stroke_values(t)).unwrap_or_default();
// Clone and smudge on a mask read the mask as it was before the stroke
let mask_owner = match target {
Some(PaintTarget::Mask(effect)) if pickup.is_some() => self.doc.project.effect(effect).map(|(owner, _)| owner),
_ => None,
};
let stencil = if tool == Tool::Projection && !quick_mask { self.capture_stencil(viewport) } else { None };
let problem = if !erase && values.is_empty() && matches!(target, Some(PaintTarget::Layer(_))) {
Some("no channel enabled to paint: enable channels in the tool's material")
} else if pickup.is_some() && matches!(target, Some(PaintTarget::Mask(_))) {
Some("the Clone and Smudge tools paint layer content: select the layer instead of its mask")
} else if tool == Tool::Projection && !quick_mask && stencil.is_none() && !uv_mode {
Some("the Projection tool needs a stencil: pick an image in the tool properties (tool.stencil)")
} else {
@@ -200,13 +262,9 @@ impl Session {
self.doc = before;
return Err(EngineError::Other(msg.into()));
}
let depth = (!uv_mode).then(|| self.eye_depth(viewport));
let mut brush = self.tool.brush.clone();
if tool == Tool::Smudge {
// shortcut: smudge drags one stamp trail; mirrored trails would need one pickup each.
brush.symmetry = Default::default();
}
let stroke = Stroke::new(&brush, &self.mesh);
let stroke = Stroke::new(&self.tool.brush, &self.mesh);
let mut canvas = StrokeCanvas::new(size.0, size.1);
if !quick_mask {
canvas.limit = self.stroke_limit(ts, size);
@@ -220,24 +278,49 @@ impl Session {
}
m => m,
};
canvas.pickup = Some(match &layer_source {
Some(flat) => Pickup::from_layer(mode, flat, size, cache.gbuf.clone(), values.keys().copied()),
None => Pickup::new(mode, cache.composite.clone(), cache.gbuf.clone(), values.keys().copied()),
});
let mut pickup = match (&layer_source, mask_owner) {
// On a mask the stroke reads the mask's own values
(_, Some(owner)) => {
let snapshot = texturecraft_paint::pickup::PickupSnapshot {
project: self.doc.project.clone(),
ts,
target: PaintTarget::Mask(owner),
mesh: self.mesh.clone(),
bounds: self.mesh.bounds(),
pixels: self.doc.pixels.clone(),
baked: self.doc.baked.get(&ts).cloned().unwrap_or_default(),
images: self.images.clone(),
};
Pickup::from_snapshot(mode, snapshot, cache.gbuf.clone(), [])
}
(Some(flat), None) => Pickup::from_layer(mode, flat, size, cache.gbuf.clone(), values.keys().copied()),
(None, None) => Pickup::new(
mode,
self.document_composite(ts, &cache.covered_tiles).ok_or_else(|| EngineError::Other("texture set not ready".into()))?.into_owned(),
cache.gbuf.clone(),
values.keys().copied(),
),
};
if tool == Tool::Smudge && stroke.settings.symmetry.any() {
// Every mirrored copy of a smudge drags its own trail, in the 3D and the 2D view
pickup.isolate_copies();
}
canvas.pickup = Some(pickup);
if tool == Tool::Clone
&& self.tool.clone_aligned
&& let Some(src) = self.tool.clone_source.as_mut()
{
src.offset.get_or_insert(offset);
}
}
if canvas.pickup.is_none() && tool == Tool::Paint && matches!(target, Some(PaintTarget::Layer(_))) {
canvas.pickup = self.brush_pattern(&values);
}
let label = if quick_mask {
"Quick mask stroke"
} else if erase {
"Eraser stroke"
} else if matches!(target, Some(PaintTarget::Mask(_))) {
"Mask stroke"
QUICK_MASK_STROKE_LABEL.to_string()
} else {
"Paint stroke"
let on_mask = matches!(target, Some(PaintTarget::Mask(_)));
history_label(stroke_template(tool, on_mask), &self.stroke_layer_name())
};
self.stroke = Some(ActiveStroke {
ts,
@@ -252,12 +335,20 @@ impl Session {
erase,
stencil,
before,
label: label.to_string(),
label,
staging: Staging::default(),
});
Ok(())
}
/// The name of the layer a stroke paints on (the owner layer when an effect is selected)
fn stroke_layer_name(&self) -> String {
let p = &self.doc.project;
let Some(id) = self.selected_layer() else { return String::new() };
let owner = p.effect(id).map_or(id, |(owner, _)| owner);
p.layer(owner).map(|l| l.name.clone()).unwrap_or_default()
}
/// Clone / smudge pickup for the current tool, with the clone offset (source minus
/// destination) in texture coordinates.
fn pickup_mode(&self, first_uv: Option<Vec2>) -> Result<Option<(PickupMode, [f32; 2])>> {
@@ -266,11 +357,15 @@ impl Session {
Tool::Clone => {
let src =
self.tool.clone_source.ok_or_else(|| EngineError::Other("set a clone source first: V + click on the mesh (tool.cloneSource)".into()))?;
let offset = match (src.offset, first_uv) {
// Not aligned: every stroke measures the offset from its own first point
let kept = if self.tool.clone_aligned { src.offset } else { None };
let offset = match (kept, first_uv) {
(Some(o), _) => o,
(None, Some(p)) => [src.uv[0] - p.x, src.uv[1] - p.y],
(None, None) => return Err(EngineError::Other("start the clone stroke on the mesh".into())),
};
Ok(Some((PickupMode::Clone { offset: [0; 2] }, offset)))
}
_ => Ok(None),
@@ -284,6 +379,7 @@ impl Session {
alpha: b.alpha,
image: b.alpha_image.as_ref().and_then(|n| images.get(n)).map(|i| &**i),
library: b.alpha_library.as_deref().and_then(texturecraft_paint::alphas::find).map(|a| a.image()),
params: b.alpha_params,
level: 0,
}
}
@@ -355,11 +451,18 @@ impl Session {
// The first sample is one stamp; a later one stamps every `step` along the segment from the previous
let (start, segment, mut distance) = match progress.last.replace(uv) {
None => (uv, Vec2::ZERO, 0.0),
// Pressure can shrink the step below the carry from the preceding sample
Some(previous) => (previous, uv - previous, (step - progress.carry).max(0.0)),
};
let length = segment.length();
let shape = Self::shape(&self.images, settings);
// The copies of each dab: the Clone tool's pickup offset is fixed, so it paints none
let material = self.doc.project.texture_sets.get(active.ts).map(|t| t.material).unwrap_or(0);
let mirror = (self.tool.tool != Tool::Clone)
.then(|| UvMirror::new(&settings.symmetry, active.stroke.center(), &self.mesh, &self.bvh, &cache.gbuf, material))
.flatten();
let mut batch = Vec::new();
let mut stamped = 0;
while distance <= length && stamped < MAX_UV_STAMPS_PER_SAMPLE {
@@ -368,11 +471,18 @@ impl Session {
while distance <= length && batch.len() < batch_size {
let center = start + segment * (distance / length.max(f32::MIN_POSITIVE));
let seed = progress.stamps.wrapping_add((stamped + batch.len()) as u32);
batch.push(texturecraft_paint::UvStamp { center, radius, angle, flow: settings.flow, hardness: settings.hardness, seed });
batch.push(texturecraft_paint::UvStamp { center, radius, angle, flow: settings.flow, hardness: settings.hardness, seed, source: None });
distance += step;
}
stamped += batch.len();
if let Some(mirror) = &mirror {
for index in 0..batch.len() {
if let Some(stamp) = batch.get(index).copied() {
mirror.add_copies(&stamp, &mut batch);
}
}
}
texturecraft_paint::rasterize_uv(&mut active.canvas, &cache.gbuf, shape, &batch);
}
@@ -538,7 +648,7 @@ impl Session {
pub(crate) fn paint_fill(&mut self, ts: usize, canvas: &StrokeCanvas) -> Result<()> {
let size = (canvas.alpha.width(), canvas.alpha.height());
let opacity = self.tool.brush.opacity;
let source = CommitSource { alpha: &canvas.alpha, tiles: &canvas.dirty, opacity, erase: false, per_texel: None, carried: None };
let source = CommitSource { alpha: &canvas.alpha, tiles: &canvas.dirty, opacity, erase: false, per_texel: None, carried: None, carried_mask: None };
if self.quick_mask.editing {
self.commit_quick_mask(ts, size, source);
return Ok(());
@@ -562,12 +672,11 @@ impl Session {
let (width, height) = (cache.size.0 as f32, cache.size.1 as f32);
let (x, y) = ((hit.uv.x * width).clamp(0.0, width - 1.0) as u32, (hit.uv.y * height).clamp(0.0, height - 1.0) as u32);
let mut picked = BTreeMap::new();
for channel in cache.composite.channels.keys() {
let value = cache.composite.value(*channel, x, y);
self.tool.values.insert(*channel, value);
picked.insert(*channel, value);
}
let tile = (x / texturecraft_texel::TILE, y / texturecraft_texel::TILE);
let source = self.document_composite(texture_set, &[tile]).ok_or_else(|| EngineError::Other("texture set not ready".into()))?;
let picked: BTreeMap<_, _> = source.channels.keys().map(|&channel| (channel, source.value(channel, x, y))).collect();
self.tool.values.extend(&picked);
self.tool.material = None;
Ok(picked)
}
@@ -576,17 +685,30 @@ impl Session {
self.stroke.as_ref().map(|s| s.canvas.dirty.len()).unwrap_or(0)
}
/// Where the Clone tool reads for destination `at` (texture coordinates) as a surface
/// point: the source itself until the first stroke fixes the offset, or when `at` is None.
pub fn clone_source_point(&self, at: Option<Vec2>) -> Option<texturecraft_geom::glam::Vec3> {
/// Where the Clone tool reads for destination `at` (texture coordinates), in texture
/// coordinates: the source itself until the first stroke fixes the offset, or when `at` is
/// None. None without a source or when that spot is outside the texture. The far edge
/// (1.0) counts as inside, so the 2D marker shows a source set on the edge; reads of the
/// surface use `clone_source_uv`, which stays half-open.
pub fn clone_source_marker_uv(&self, at: Option<Vec2>) -> Option<Vec2> {
let src = self.tool.clone_source?;
let uv = match (src.offset, at) {
(Some(o), Some(p)) => Vec2::new(p.x + o[0], p.y + o[1]),
_ => Vec2::from(src.uv),
};
if !((0.0..1.0).contains(&uv.x) && (0.0..1.0).contains(&uv.y)) {
return None;
}
((0.0..=1.0).contains(&uv.x) && (0.0..=1.0).contains(&uv.y)).then_some(uv)
}
/// Like `clone_source_marker_uv`, but half-open: None on the far edge, where the G-buffer
/// has no texel.
pub fn clone_source_uv(&self, at: Option<Vec2>) -> Option<Vec2> {
self.clone_source_marker_uv(at).filter(|uv| uv.x < 1.0 && uv.y < 1.0)
}
/// Where the Clone tool reads for destination `at` (texture coordinates) as a surface
/// point: the source itself until the first stroke fixes the offset, or when `at` is None.
pub fn clone_source_point(&self, at: Option<Vec2>) -> Option<texturecraft_geom::glam::Vec3> {
let uv = self.clone_source_uv(at)?;
let g = &self.caches.get(self.ts())?.gbuf;
let (x, y) = ((uv.x * g.width as f32) as usize, (uv.y * g.height as f32) as usize);
Some(g.surface(&self.mesh, y * g.width as usize + x)?.pos)
@@ -613,5 +735,6 @@ fn with_commit_source<R>(
};
let per_texel: Option<texturecraft_paint::TexelFn> = if st.stencil.is_some() { Some(&stencil_fn) } else { None };
let carried = st.canvas.pickup.as_ref().map(|p| &p.values);
f(CommitSource { alpha: &st.canvas.alpha, tiles, opacity: st.stroke.settings.opacity, erase: st.erase, per_texel, carried })
let carried_mask = st.canvas.pickup.as_ref().and_then(|p| p.mask_values());
f(CommitSource { alpha: &st.canvas.alpha, tiles, opacity: st.stroke.settings.opacity, erase: st.erase, per_texel, carried, carried_mask })
}
+226 -44
View File
@@ -15,7 +15,7 @@ use texturecraft_compose::{PaintTarget, PixelStore};
use texturecraft_core::{Channel, Effect, EffectKind, LayerId, LayerKind, Mask, MaskBackground, PathShape};
use texturecraft_geom::glam::{Mat3, Vec2, Vec3};
use texturecraft_geom::{OrbitCamera, surface_at};
use texturecraft_paint::{BrushSettings, Lasso, PickCtx, fill_coverage, pick, spline, spline_segments};
use texturecraft_paint::{BrushSettings, Lasso, PickCtx, fill_coverage, pick, spline_segments_with_corners, spline_with_corners};
use texturecraft_texel::TileImage;
use crate::commands::{CommandSpec, always, bad, boolp, has_layer, u64p};
@@ -47,6 +47,10 @@ const RAY_HIT_RELATIVE_TOLERANCE: f32 = 0.001;
pub struct PathState {
/// Control points: surface positions (3D view) or texture coordinates with z = 0 (2D view)
pub points: Vec<Vec3>,
/// Per control point: the curve turns sharply there (a corner). Empty or shorter than `points` means smooth;
/// read it through [`PathState::is_corner`] and [`PathState::corner_flags`]
#[serde(default)]
pub corners: Vec<bool>,
/// The points are texture coordinates (placed in the 2D view)
pub uv: bool,
/// The curve loops back to its first point
@@ -69,13 +73,38 @@ impl PathState {
pub fn push(&mut self, point: Vec3, uv: bool) {
if uv != self.uv {
self.points.clear();
self.corners.clear();
self.uv = uv;
}
if self.points.len() < MAX_PATH_POINTS {
self.points.push(point);
if !self.corners.is_empty() {
self.corners.resize(self.points.len(), false);
}
}
}
/// Does the curve turn sharply at point `i`?
pub fn is_corner(&self, i: usize) -> bool {
self.corners.get(i).copied().unwrap_or(false)
}
/// One flag per point for the curve and storage: empty when no point is a corner, so smooth paths look like old ones
pub fn corner_flags(&self) -> Vec<bool> {
if self.points.iter().enumerate().any(|(i, _)| self.is_corner(i)) { (0..self.points.len()).map(|i| self.is_corner(i)).collect() } else { Vec::new() }
}
/// Make point `i` a corner or smooth; false when there is no such point or it already is
pub fn set_corner(&mut self, i: usize, corner: bool) -> bool {
if i >= self.points.len() || self.is_corner(i) == corner {
return false;
}
self.corners.resize(self.points.len(), false);
self.corners[i] = corner;
true
}
/// Insert a control point before point `at` (on the segment ending there) and select it; None when it can't
pub fn insert(&mut self, at: usize, point: Vec3) -> Option<usize> {
if at > self.points.len() || self.points.len() >= MAX_PATH_POINTS {
@@ -83,18 +112,23 @@ impl PathState {
}
self.points.insert(at, point);
if !self.corners.is_empty() {
self.corners.resize(self.points.len() - 1, false);
self.corners.insert(at, false);
}
self.selected = Some(at);
self.selected
}
/// The same curve (points, open or closed, filled, view) as `other`
fn same_curve(&self, other: &PathState) -> bool {
(&self.points, self.closed, self.fill, self.uv) == (&other.points, other.closed, other.fill, other.uv)
(&self.points, self.corner_flags(), self.closed, self.fill, self.uv) == (&other.points, other.corner_flags(), other.closed, other.fill, other.uv)
}
/// Empty the tool for the next path: no points, open, nothing selected or edited
pub fn clear(&mut self) {
self.points.clear();
self.corners.clear();
self.closed = false;
self.selected = None;
self.editing = None;
@@ -106,6 +140,10 @@ impl PathState {
let at = self.selected.take().filter(|i| *i < self.points.len()).or(self.points.len().checked_sub(1));
if let Some(i) = at {
self.points.remove(i);
if !self.corners.is_empty() {
self.corners.resize(self.points.len() + 1, false);
self.corners.remove(i);
}
}
if self.closed && self.points.len() < 3 {
self.closed = false;
@@ -116,10 +154,10 @@ impl PathState {
/// A path sublayer's pixels after painting its first paths (`below`), with the mesh and
/// texture size they were painted for.
#[derive(Clone)]
// shortcut: the key doesn't cover image resources a path's brush alpha reads; replacing one
// leaves cached paths with the old alpha until a path below the edited one changes.
pub(crate) struct PathCache {
eid: LayerId,
pub(crate) eid: LayerId,
// Alpha image resources are not part of this cache key
// Replacing an alpha takes effect when a cached path changes
key: (u64, Option<(u32, u32)>),
below: Vec<PathShape>,
mask: Option<texturecraft_texel::TileImage>,
@@ -143,10 +181,19 @@ pub fn specs() -> Vec<CommandSpec> {
"Path",
["Tools"],
Some("7"),
"{points?: [[x,y],...] viewport pixels on the mesh | uvPoints?: [[u,v],...], viewport?: [w,h], closed?, fill?, commit?: bool, clear?: bool} — selects the Path tool and edits its curve; commit adds the path to the selected path sublayer (or a new one), painted with the current brush or filled when closed and filled. While a stored path is edited (path.edit), changes repaint it at once",
"{points?: [[x,y],...] viewport pixels on the mesh | uvPoints?: [[u,v],...], corners?: [bool,...] up to one per point (true: the curve turns sharply there; missing entries are smooth; applies to supplied points or the current curve), viewport?: [w,h], closed?, fill?, commit?: bool, clear?: bool} — selects the Path tool and edits its curve; commit adds the path to the selected path sublayer (or a new one), painted with the current brush or filled when closed and filled. While a stored path is edited (path.edit), changes repaint it at once",
always,
path
),
cmd!(
"path.corner",
"Toggle path corner",
["Tools"],
None,
"{index?: point (default: the selected point), corner?: bool (default: toggle)} — makes a control point of the Path tool's curve a corner (the curve turns sharply there) or smooth again; one undo step per change, repainting the edited path at once",
always,
path_corner
),
cmd!(
"path.edit",
"Edit path",
@@ -171,35 +218,60 @@ pub fn specs() -> Vec<CommandSpec> {
/// Set the curve from command parameters, then preview or commit it in the supplied viewport
fn path(s: &mut Session, p: &Value) -> Result<Value> {
const CMD: &str = "tool.path";
let viewport = viewport_of(s, p);
let clear = boolp(p, "clear") == Some(true);
let placed = match (points_param(CMD, p, "points")?, points_param(CMD, p, "uvPoints")?) {
(Some(pixels), _) => {
if pixels.len() > MAX_PATH_POINTS {
return Err(bad(CMD, format!("at most {MAX_PATH_POINTS} control points")));
}
Some((
pixels
.iter()
.enumerate()
.map(|(i, pixel)| s.pick(*pixel, viewport).map(|hit| hit.pos).ok_or_else(|| bad(CMD, format!("point {i} misses the mesh"))))
.collect::<Result<Vec<_>>>()?,
false,
))
}
(None, Some(uvs)) => {
if uvs.len() > MAX_PATH_POINTS {
return Err(bad(CMD, format!("at most {MAX_PATH_POINTS} control points")));
}
Some((uvs.iter().map(|uv| uv.clamp(Vec2::ZERO, Vec2::ONE).extend(0.0)).collect(), true))
}
(None, None) => None,
};
let point_count = placed.as_ref().map_or(if clear { 0 } else { s.tool.path.points.len() }, |(points, _)| points.len());
let corners = match p.get("corners") {
Some(value) => {
let flags = value.as_array().ok_or_else(|| bad(CMD, "`corners` must be an array of booleans"))?;
if flags.len() > point_count || flags.len() > MAX_PATH_POINTS {
return Err(bad(CMD, "`corners` has more flags than control points"));
}
Some(flags.iter().map(Value::as_bool).collect::<Option<Vec<_>>>().ok_or_else(|| bad(CMD, "`corners` must be an array of booleans"))?)
}
None => None,
};
if s.tool.tool != Tool::Path {
set_tool(s, Tool::Path)?;
}
let viewport = viewport_of(s, p);
if boolp(p, "clear") == Some(true) {
if clear {
s.cancel_path();
}
let placed = match (points_param(CMD, p, "points")?, points_param(CMD, p, "uvPoints")?) {
(Some(pixels), _) => Some((
pixels
.iter()
.enumerate()
.map(|(i, pixel)| s.pick(*pixel, viewport).map(|hit| hit.pos).ok_or_else(|| bad(CMD, format!("point {i} misses the mesh"))))
.collect::<Result<Vec<_>>>()?,
false,
)),
(None, Some(uvs)) => Some((uvs.iter().map(|uv| uv.clamp(Vec2::ZERO, Vec2::ONE).extend(0.0)).collect(), true)),
(None, None) => None,
};
if let Some((points, uv)) = placed {
if points.len() > MAX_PATH_POINTS {
return Err(bad(CMD, format!("at most {MAX_PATH_POINTS} control points")));
}
s.tool.path.points = points;
s.tool.path.corners.clear();
s.tool.path.uv = uv;
}
if let Some(flags) = corners {
s.tool.path.corners = flags;
}
if let Some(v) = boolp(p, "closed") {
s.tool.path.closed = v;
}
@@ -224,6 +296,24 @@ fn path(s: &mut Session, p: &Value) -> Result<Value> {
Ok(json!({ "points": path.points.len(), "uv": path.uv, "closed": path.closed, "fill": path.fill, "editing": editing, "committed": committed }))
}
/// Make a control point a corner or smooth (a toggle by default) as one undoable point edit
fn path_corner(s: &mut Session, p: &Value) -> Result<Value> {
const CMD: &str = "path.corner";
let path = &s.tool.path;
let index = match u64p(p, "index") {
Some(i) => usize::try_from(i).ok().filter(|i| *i < path.points.len()),
None => path.selected.filter(|i| *i < path.points.len()),
}
.ok_or_else(|| bad(CMD, "no such point: pass `index` or select a point of the Path tool's curve"))?;
let corner = boolp(p, "corner").unwrap_or(!path.is_corner(index));
s.set_path_point_corner(index, corner);
s.revision = s.revision.wrapping_add(1);
if s.path_live()? {
s.update();
}
Ok(json!({ "index": index, "corner": s.tool.path.is_corner(index) }))
}
/// The `effect` and `index` params naming a stored path, with the path.
fn path_ref(s: &Session, cmd: &str, p: &Value) -> Result<(LayerId, usize, PathShape)> {
let eid = LayerId(u64p(p, "effect").ok_or_else(|| bad(cmd, "`effect` (a path sublayer id) is required"))?);
@@ -282,7 +372,21 @@ fn read_paint(shape: &PathShape) -> Result<PathPaint> {
/// The Path tool state showing a stored path (finite points only, at most [`MAX_PATH_POINTS`])
fn state_of(shape: &PathShape) -> PathState {
let points = shape.points.iter().filter(|p| p.iter().all(|v| v.is_finite())).take(MAX_PATH_POINTS).map(|p| Vec3::from_array(*p)).collect();
PathState { points, uv: shape.uv, closed: shape.closed, fill: shape.fill, ..PathState::default() }
// Points dropped as unreadable shift the later flags with them
let corners = if shape.corners.is_empty() {
Vec::new()
} else {
shape
.points
.iter()
.zip(shape.corners.iter().copied().chain(std::iter::repeat(false)))
.filter(|(p, _)| p.iter().all(|v| v.is_finite()))
.take(MAX_PATH_POINTS)
.map(|(_, c)| c)
.collect()
};
PathState { points, corners, uv: shape.uv, closed: shape.closed, fill: shape.fill, ..PathState::default() }
}
/// Tiles (x, y) where sublayer `eid`'s pixels differ between `before` and `after` (copy-on-write: an unchanged tile is the same allocation)
@@ -358,6 +462,7 @@ impl Session {
let paint = PathPaint { brush: t.brush.clone(), values: t.values.clone(), enabled: t.enabled.clone(), mask_value: t.mask_value, camera };
PathShape {
points: path.points.iter().map(|p| p.to_array()).collect(),
corners: path.corner_flags(),
uv: path.uv,
closed: path.closed,
fill: path.fill,
@@ -399,7 +504,8 @@ impl Session {
let shape = self.path_shape(self.camera, viewport);
let editing = self.tool.path.editing;
let label = editing.map_or(NEW_PATH_LABEL.to_string(), |(_, i)| format!("Edit path {}", i + 1));
let label =
editing.map_or(NEW_PATH_LABEL.to_string(), |(_, i)| crate::session::history_label(crate::session::EDIT_PATH_TEMPLATE, &(i + 1).to_string()));
let report = self.edit_merging(&label, editing.is_some() && self.tool.path.edited, |session| {
let (effect_id, index) = match editing {
Some(at) => at,
@@ -426,7 +532,11 @@ impl Session {
// JSON round trips can change float representation without changing the paint settings
read_paint(stored).is_ok_and(|paint| {
let current = self.path_shape(paint.camera, Vec2::from_array(stored.viewport));
(&current.points, current.uv, current.closed, current.fill) == (&stored.points, stored.uv, stored.closed, stored.fill)
// Normalised like the current flags: a short, long or all-smooth stored list must not count as a change
let stored_corners = state_of(stored).corner_flags();
(&current.points, &current.corners, current.uv, current.closed, current.fill)
== (&stored.points, &stored_corners, stored.uv, stored.closed, stored.fill)
&& read_paint(&current).is_ok_and(|current_paint| current_paint == paint)
})
}
@@ -457,16 +567,21 @@ impl Session {
if self.path_draft.is_some() {
self.cancel_path();
} else {
self.edit_merging(&format!("Edit path {}", index + 1), self.tool.path.edited, |session| {
if let Some(Effect { kind: EffectKind::Path(paths), .. }) = session.doc.project.effect_mut(effect) {
paths.remove(index);
}
session.render_paths(effect, index)
})?;
self.edit_merging(
&crate::session::history_label(crate::session::EDIT_PATH_TEMPLATE, &(index + 1).to_string()),
self.tool.path.edited,
|session| {
if let Some(Effect { kind: EffectKind::Path(paths), .. }) = session.doc.project.effect_mut(effect) {
paths.remove(index);
}
session.render_paths(effect, index)
},
)?;
self.cancel_path();
}
return Ok(true);
}
return Ok(false);
}
@@ -488,7 +603,7 @@ impl Session {
None => {
// The path's own repaint keeps its point changes undoable, unlike other steps
let steps = std::mem::take(&mut self.path_steps);
self.push_step(&format!("Edit path {}", index + 1), before, self.tool.path.edited);
self.push_step(&crate::session::history_label(crate::session::EDIT_PATH_TEMPLATE, &(index + 1).to_string()), before, self.tool.path.edited);
self.path_steps = steps;
self.tool.path.edited = true;
}
@@ -588,6 +703,37 @@ impl Session {
self.tool.path.remove_selected();
}
/// Make a point a corner or smooth again, with point undo; false when nothing changed
pub fn set_path_point_corner(&mut self, index: usize, corner: bool) -> bool {
if index >= self.tool.path.points.len() || self.tool.path.is_corner(index) == corner {
return false;
}
self.path_checkpoint();
self.tool.path.set_corner(index, corner)
}
/// Switch the selected point between corner and smooth, with point undo; false without a selected point
pub fn toggle_selected_path_corner(&mut self) -> bool {
let Some(i) = self.tool.path.selected.filter(|i| *i < self.tool.path.points.len()) else { return false };
let corner = !self.tool.path.is_corner(i);
self.set_path_point_corner(i, corner)
}
/// Append a point that is a corner, selecting it; as [`Session::append_path_point`]
pub fn append_path_corner(&mut self, point: Vec3, uv: bool) -> Option<usize> {
let at = self.append_path_point(point, uv)?;
self.tool.path.set_corner(at, true);
Some(at)
}
/// Insert a point that is a corner, selecting it; as [`Session::insert_path_point`]
pub fn insert_path_corner(&mut self, index: usize, point: Vec3) -> Option<usize> {
let at = self.insert_path_point(index, point)?;
self.tool.path.set_corner(at, true);
Some(at)
}
/// Change whether the path loops back to its first point, with point undo
pub fn set_path_closed(&mut self, closed: bool) {
if self.tool.path.closed != closed {
@@ -823,8 +969,9 @@ impl Session {
}
_ => 0,
};
// Each path goes through the regular stroke and fill code with its own settings; their
// own history entries are dropped (the caller records one step).
// Regular stroke and fill code paints each path with its own settings
// Discard its history entries because the caller records one undo step
let saved = (self.tool.clone(), self.camera, self.target, self.quick_mask.editing);
let history = (std::mem::take(&mut self.undo), std::mem::take(&mut self.redo));
self.target = StackTarget::Effect(eid);
@@ -866,15 +1013,20 @@ impl Session {
self.paint_path(viewport)
}
/// Where a 3D path's curve lands on the mesh painted through `camera`, per segment as [`spline_segments`] (None off the mesh)
/// Where a 3D path's curve lands on the mesh painted through `camera`, per segment as [`texturecraft_paint::spline_segments`] (None off the mesh)
pub fn path_surface(&self, points: &[Vec3], closed: bool, camera: OrbitCamera, viewport: Vec2) -> Vec<Vec<Option<Vec3>>> {
self.path_surface_with_corners(points, &[], closed, camera, viewport)
}
/// [`Session::path_surface`] for a curve with corner points (`corners` as [`PathState::corners`])
pub fn path_surface_with_corners(&self, points: &[Vec3], corners: &[bool], closed: bool, camera: OrbitCamera, viewport: Vec2) -> Vec<Vec<Option<Vec3>>> {
let aspect = viewport.x.max(1.0) / viewport.y.max(1.0);
let Some(screen) = points.iter().map(|p| camera.project(*p, aspect).map(|n| to_pixels(n.truncate(), viewport))).collect::<Option<Vec<_>>>() else {
return Vec::new();
};
let ctx = PickCtx { mesh: &self.mesh, bvh: &self.bvh, camera: &camera, viewport };
spline_segments(&screen, closed, SURFACE_STEP_PX)
spline_segments_with_corners(&screen, corners, closed, SURFACE_STEP_PX)
.into_iter()
.zip(&screen)
.map(|(samples, first)| std::iter::once(*first).chain(samples).map(|q| pick(&ctx, q).map(|hit| hit.pos)).collect())
@@ -890,7 +1042,7 @@ impl Session {
let (camera, viewport) = paint_view(shape, &read_paint(shape).ok()?);
let path = state_of(shape);
Some(self.path_surface(&path.points, path.closed, camera, viewport))
Some(self.path_surface_with_corners(&path.points, &path.corners, path.closed, camera, viewport))
}
/// Paint the Path tool's curve with the current brush (or fill it when closed and filled)
@@ -898,14 +1050,17 @@ impl Session {
fn paint_path(&mut self, viewport: Vec2) -> Result<Value> {
let (uv, closed) = (self.tool.path.uv, self.tool.path.closed);
let fill = closed && self.tool.path.fill;
let pts: Vec<Vec2> = self.path_view_points(viewport).into_iter().flatten().collect();
let (pts, corners): (Vec<Vec2>, Vec<bool>) =
self.path_view_points(viewport).into_iter().enumerate().filter_map(|(i, p)| Some((p?, self.tool.path.is_corner(i)))).unzip();
if pts.is_empty() {
return Err(EngineError::Other("the path has no points: click the surface to add some".into()));
}
if fill && pts.len() < 3 {
return Err(EngineError::Other("a filled path needs at least three points".into()));
}
let curve = spline(&pts, closed, if uv { STEP_UV } else { STEP_PX });
let curve = spline_with_corners(&pts, &corners, closed, if uv { STEP_UV } else { STEP_PX });
Ok(if fill {
json!({ "filledTiles": self.lasso_fill(curve, uv, viewport)? })
} else if uv {
@@ -1032,7 +1187,8 @@ mod tests {
eid = r["committed"]["effect"].as_u64().unwrap();
}
let eid = texturecraft_core::LayerId(eid);
// Live edits of the middle path reuse the bottom path's pixels.
// Live edits of the middle path reuse the bottom path's pixels
execute(&mut s, "path.edit", &json!({"effect": eid.0, "index": 1})).unwrap();
for v in [0.4, 0.45] {
execute(&mut s, "tool.path", &json!({"uvPoints": [[0.1, v], [0.5, v], [0.9, v]]})).unwrap();
@@ -1045,6 +1201,32 @@ mod tests {
s.render_paths(eid, 0).unwrap();
assert_eq!(cached, pixels(&s, eid), "same pixels as painting every path");
assert!(!cached.is_empty());
execute(&mut s, "path.edit", &json!({"effect": eid.0, "index": 1})).unwrap();
execute(&mut s, "tool.path", &json!({"uvPoints": [[0.1, 0.35], [0.9, 0.4]]})).unwrap();
let cached_tiles = s.path_cache.as_ref().map_or(0, |cache| cache.layers.iter().map(|(_, image)| image.allocated_count()).sum::<usize>());
assert!(cached_tiles > 0);
execute(&mut s, "effect.remove", &json!({"effect": eid.0})).unwrap();
let remaining_tiles = s.path_cache.as_ref().map_or(0, |cache| cache.layers.iter().map(|(_, image)| image.allocated_count()).sum::<usize>());
assert_eq!(remaining_tiles, 0);
assert!(s.path_cache.is_none(), "deleting the path effect releases its cached tiles");
}
#[test]
fn failed_edit_releases_cached_path_tiles() {
let mut session = Session::new_project("t", texturecraft_geom::primitives::sphere(1.0, 12, 6), "builtin:test", None, 128).unwrap();
let mut image = TileImage::new(64, 64, 1);
let tile = Arc::new(vec![1u16; texturecraft_texel::TILE_AREA]);
let retained = Arc::downgrade(&tile);
image.set_tile(0, 0, Some(tile));
session.path_cache = Some(PathCache { eid: LayerId(0), key: (0, None), below: Vec::new(), mask: Some(image), layers: Vec::new() });
let result: Result<()> = session.edit("Rejected edit", |_| Err(EngineError::Other("rejected".into())));
assert!(result.is_err());
assert!(session.path_cache.is_none());
assert!(retained.upgrade().is_none(), "the discarded document cannot retain the cache's tile");
}
#[test]
+6 -1
View File
@@ -104,6 +104,10 @@ impl Session {
drag.last_box = Some((low, high));
let selected = self.box_selection(low, high);
let selected = match self.polygon_fill_drag.as_ref() {
Some(drag) => self.with_symmetry_copies(&drag.fill_groups, selected),
None => selected,
};
self.show_box_fill(selected)
}
@@ -178,11 +182,12 @@ impl Session {
}
}
/// Fill the fill-mode group holding `triangle` (one undo step)
/// Fill the fill-mode group holding `triangle` and its symmetry copies (one undo step)
fn fill_group_of(&mut self, triangle: u32) -> Result<usize> {
let ts = self.ts();
let groups = self.fill_partition(self.fill_material()?);
let triangles: BTreeSet<u32> = groups.group(triangle).unwrap_or_default().iter().copied().collect();
let triangles = self.with_symmetry_copies(&groups, triangles);
let (gbuf, mut canvas) = self.fill_canvas(ts)?;
fill_triangles(&mut canvas, &gbuf, &triangles);
+240
View File
@@ -0,0 +1,240 @@
//! Polygon fill with symmetry: the fill also reaches the faces the brush's mirror planes and radial copies map it onto.
use std::collections::{BTreeSet, HashSet};
use texturecraft_geom::glam::Mat3;
use crate::session::Session;
use crate::triangle_partition::TrianglePartition;
/// How far a mirrored face centre may be from the surface and still count as on it, as a fraction of the mesh's bounding-box diagonal
const MIRROR_TOLERANCE: f32 = 1e-3;
impl Session {
/// `selected` plus the faces the brush symmetry copies it onto: for each group of `groups` (the fill mode's grouping) in `selected`, the group holding the face its first triangle's centre maps to under each mirror plane and radial turn.
/// Copies that land on no face of the texture set (an asymmetric mesh, or the other side of a thin shell) are skipped
pub(crate) fn with_symmetry_copies(&self, groups: &TrianglePartition, selected: BTreeSet<u32>) -> BTreeSet<u32> {
let symmetry = self.tool.brush.sanitized().symmetry;
let copies: Vec<Mat3> = symmetry.transforms().into_iter().filter(|copy| *copy != Mat3::IDENTITY).collect();
if copies.is_empty() || selected.is_empty() {
return selected;
}
let mesh = &self.mesh;
let (low, high) = mesh.bounds();
let tolerance = (high - low).length() * MIRROR_TOLERANCE;
let origin = symmetry.origin((low + high) * 0.5);
let corners = |triangle: u32| {
let [first, second, third] = mesh.tri(triangle as usize)?;
Some([*mesh.positions.get(first)?, *mesh.positions.get(second)?, *mesh.positions.get(third)?])
};
let mut seen_groups = HashSet::new();
let mut result = selected.clone();
for seed in selected.iter().copied().filter(|triangle| groups.index_of(*triangle).is_some_and(|group| seen_groups.insert(group))) {
let Some([first, second, third]) = corners(seed) else { continue };
let centre = (first + second + third) / 3.0;
let normal = (second - first).cross(third - first);
for copy in &copies {
let target = origin + *copy * (centre - origin);
let target_normal = *copy * normal;
// A face on the same side: a thin shell's other face lies at the same point but looks the other way
let faces_alike = |triangle: u32| {
groups.index_of(triangle).is_some() && corners(triangle).is_some_and(|[a, b, c]| (b - a).cross(c - a).dot(target_normal) > 0.0)
};
if let Some(hit) = self.bvh.nearest(target, tolerance, &faces_alike) {
result.extend(groups.group(hit.tri).unwrap_or_default().iter().copied());
}
}
}
result
}
}
#[cfg(test)]
mod tests {
use texturecraft_core::Channel;
use texturecraft_geom::glam::{Vec2, Vec3};
use texturecraft_geom::mesh::Mesh;
use crate::fill_hit_test::FillHitTest;
use crate::fill_mode::FillMode;
use crate::session::{Session, Tool};
/// The roughness the test fills paint, to tell filled texels apart
const FILL_ROUGHNESS: f32 = 0.9;
/// The x ranges of the two quads on the right of the YZ plane; the left side mirrors them
const QUAD_RANGES: [(f32, f32); 2] = [(1.0, 2.0), (3.0, 4.0)];
/// Texture coordinate of the point `(x, y)` on the flat test mesh, each x its own place
fn uv_of(x: f32, y: f32) -> Vec2 {
Vec2::new((x + 4.0) / 8.0, 0.2 + 0.6 * y)
}
/// Four quads facing +Z (two triangles each): [`QUAD_RANGES`] on the right and their mirror images on the left, each with its own vertices and UV place
fn mirrored_quads() -> Mesh {
let (mut positions, mut uvs, mut indices) = (Vec::new(), Vec::new(), Vec::new());
for (low, high) in QUAD_RANGES {
for mirrored in [false, true] {
let sign = if mirrored { -1.0 } else { 1.0 };
let first = positions.len() as u32;
for (x, y) in [(low, 0.0), (high, 0.0), (high, 1.0), (low, 1.0)] {
positions.push(Vec3::new(sign * x, y, 0.0));
uvs.push(uv_of(sign * x, y));
}
// A mirror image has the opposite winding, so it keeps facing +Z
let corners = if mirrored { [0, 2, 1, 0, 3, 2] } else { [0, 1, 2, 0, 2, 3] };
indices.extend(corners.map(|corner| first + corner));
}
}
Mesh::from_parts(positions, None, uvs, indices, "m").unwrap()
}
/// A fill session on [`mirrored_quads`] mirroring across X
fn mirrored_session(fill_mode: FillMode) -> Session {
let mut session = Session::new_project("t", mirrored_quads(), "test", None, 128).unwrap();
session.tool.tool = Tool::PolygonFill;
session.tool.fill_mode = fill_mode;
session.tool.brush.symmetry.x = true;
session.tool.values.insert(Channel::Roughness, [FILL_ROUGHNESS; 3]);
session.update();
session
}
/// Whether the texel at the point `(x, y)` of the flat test mesh shows the fill
fn filled_at(session: &Session, x: f32, y: f32) -> bool {
let uv = uv_of(x, y);
let (width, height) = session.caches[0].size;
let roughness = session.caches[0].composite.value(Channel::Roughness, (uv.x * width as f32) as u32, (uv.y * height as f32) as u32);
(roughness[0] - FILL_ROUGHNESS).abs() < 0.01
}
/// Whether the quad over the x range starting at `low` (negative: its mirror image on the left) shows the fill
fn quad_filled(session: &Session, low: f32) -> bool {
filled_at(session, if low < 0.0 { low - 0.5 } else { low + 0.5 }, 0.5)
}
/// Which of the four quads show the fill: right near, left near, right far, left far
fn filled_quads(session: &Session) -> [bool; 4] {
[quad_filled(session, 1.0), quad_filled(session, -1.0), quad_filled(session, 3.0), quad_filled(session, -3.0)]
}
#[test]
fn a_triangle_click_also_fills_the_mirrored_triangle() {
let mut session = mirrored_session(FillMode::Triangle);
// The lower right triangle of the near quad
assert_eq!(session.polygon_fill_uv(uv_of(1.8, 0.2)).unwrap(), 2, "the triangle and its mirror image");
session.update();
assert!(filled_at(&session, 1.8, 0.2) && filled_at(&session, -1.8, 0.2), "the clicked triangle and the one across the plane");
assert!(!filled_at(&session, 1.2, 0.8) && !filled_at(&session, -1.2, 0.8), "the other triangle of each quad stays");
assert!(!quad_filled(&session, 3.0) && !quad_filled(&session, -3.0), "the far quads stay");
}
#[test]
fn a_uv_island_click_fills_the_mirrored_island() {
let mut session = mirrored_session(FillMode::UvIsland);
assert_eq!(session.polygon_fill_uv(uv_of(1.8, 0.2)).unwrap(), 4, "both triangles of the quad and of its mirror image");
session.update();
assert_eq!(filled_quads(&session), [true, true, false, false]);
}
#[test]
fn a_mesh_click_fills_the_mirrored_connected_part_only() {
let mut session = mirrored_session(FillMode::Mesh);
// Each quad is its own piece, as its vertices touch no other quad
assert_eq!(session.polygon_fill_uv(uv_of(3.5, 0.5)).unwrap(), 4);
session.update();
assert_eq!(filled_quads(&session), [false, false, true, true]);
}
#[test]
fn a_rectangle_fills_the_mirrored_side_too() {
let mut session = mirrored_session(FillMode::UvIsland);
session.tool.fill_hit_test = FillHitTest::ContainedCenter;
// Around the far right quad only
let filled = session.polygon_fill_box_uv(uv_of(2.9, -0.1), uv_of(4.1, 1.1)).unwrap();
session.update();
assert_eq!(filled, 4);
assert_eq!(filled_quads(&session), [false, false, true, true]);
}
#[test]
fn one_undo_takes_back_the_fill_and_its_mirror() {
let mut session = mirrored_session(FillMode::UvIsland);
let history = session.history_labels().len();
session.polygon_fill_uv(uv_of(1.8, 0.2)).unwrap();
session.update();
assert_eq!(filled_quads(&session), [true, true, false, false], "the fill and its copy show");
assert_eq!(session.history_labels().len(), history + 1, "one step for the fill and its copy");
session.undo().unwrap();
session.update();
assert_eq!(filled_quads(&session), [false; 4]);
}
#[test]
fn symmetry_off_fills_only_what_was_clicked() {
let mut session = mirrored_session(FillMode::UvIsland);
session.tool.brush.symmetry.enabled = false;
assert_eq!(session.polygon_fill_uv(uv_of(1.8, 0.2)).unwrap(), 2);
session.update();
assert_eq!(filled_quads(&session), [true, false, false, false]);
}
#[test]
fn faces_without_a_mirror_match_are_skipped() {
let mut session = mirrored_session(FillMode::UvIsland);
// Moving the plane to x = 10 sends every copy to x ~ 20, where there is no surface
session.tool.brush.symmetry.offset = [10.0, 0.0, 0.0];
assert_eq!(session.polygon_fill_uv(uv_of(1.8, 0.2)).unwrap(), 2, "only the clicked quad");
session.update();
assert_eq!(filled_quads(&session), [true, false, false, false]);
}
#[test]
fn a_face_is_not_its_own_mirror_across_its_plane() {
let mut session = mirrored_session(FillMode::Triangle);
session.tool.brush.symmetry.x = false;
session.tool.brush.symmetry.z = true;
// The flat mesh lies in the mirror plane z = 0: each triangle maps onto itself looking the other way
assert_eq!(session.polygon_fill_uv(uv_of(1.8, 0.2)).unwrap(), 1);
}
#[test]
fn a_radial_copy_turns_the_fill_around_the_axis() {
let mut session = mirrored_session(FillMode::UvIsland);
// Half a turn around Z through the mesh centre (0, 0.5) sends the quad onto the quad on the left
session.tool.brush.symmetry = texturecraft_paint::Symmetry { x: false, radial: 2, axis: 2, ..Default::default() };
assert_eq!(session.polygon_fill_uv(uv_of(1.8, 0.2)).unwrap(), 4, "the turned copy lands on the left quad");
session.update();
assert_eq!(filled_quads(&session), [true, true, false, false]);
}
#[test]
fn a_radial_copy_with_the_axis_moved_away_lands_on_no_face() {
let mut session = mirrored_session(FillMode::UvIsland);
session.tool.brush.symmetry = texturecraft_paint::Symmetry { x: false, radial: 2, axis: 2, offset: [0.0, 5.0, 0.0], ..Default::default() };
assert_eq!(session.polygon_fill_uv(uv_of(1.8, 0.2)).unwrap(), 2, "the turned copy is far above the mesh");
}
}
+12 -3
View File
@@ -23,13 +23,21 @@ pub struct UserPresets {
pub fn specs() -> Vec<CommandSpec> {
vec![
cmd!("export.presets", "Export presets", [], None, "{} → [{name, maps, builtin}]", always, list),
cmd!("export.preset.get", "Get an export preset", [], None, "{name} → {name, maps: [{file, format, bit_depth, channels}]}", always, get),
cmd!(
"export.preset.get",
"Get an export preset",
[],
None,
"{name} → {name, maps: [{file, format, bit_depth, channels, inverted?: [dest, ...]}]}",
always,
get
),
cmd!(
"export.preset.save",
"Save a user export preset",
[],
None,
"{preset: {name, maps}, unique?: true = add \" 2\", \" 3\"… on a name clash instead of failing, rename?: name of the user preset this one replaces} → {name}",
"{preset: {name, maps (a map may list `inverted` destinations such as [\"R\"] to write 1 minus the value)}, unique?: true = add \" 2\", \" 3\"… on a name clash instead of failing, rename?: name of the user preset this one replaces} → {name}",
always,
save
),
@@ -282,7 +290,8 @@ mod tests {
assert!((rough - 0.3).abs() < 0.01);
let set = s.doc.project.texture_sets[0].name.clone();
let dir = std::env::temp_dir().join(format!("tc_user_preset_export_{}", std::process::id()));
// By name and as an inline object: the same files.
// By name and as an inline object: the same files
for preset in [json!("packed"), packed] {
let _ = std::fs::remove_dir_all(&dir);
let r = run(&mut s, "file.exportTextures", json!({"dir": dir.display().to_string(), "preset": preset, "ts": 0})).unwrap();
+3 -2
View File
@@ -36,7 +36,7 @@ fn coords(n: Vec3) -> Coords {
fn source(s: &Source, proj: &Projection, c: &Coords) -> Option<[f32; 3]> {
match s {
Source::Uniform(v) => Some(*v),
Source::Procedural { pattern, low, high } => {
Source::Procedural { pattern, low, high, .. } => {
let t = procedural(pattern, proj, c);
Some([0, 1, 2].map(|k| low[k] + (high[k] - low[k]) * t))
}
@@ -110,7 +110,8 @@ pub fn filter(id: &str, size: usize) -> Option<Vec<Option<Sample>>> {
let gbuf = texturecraft_geom::UvGBuffer::new(&mesh, 0, res, res);
let mut p = Project::new("preview", "");
p.texture_sets.push(TextureSet::new("preview", 0, res));
let procedural = |kind, scale, low: [f32; 3], high: [f32; 3]| Source::Procedural { pattern: Procedural { scale, ..Procedural::new(kind) }, low, high };
let procedural =
|kind, scale, low: [f32; 3], high: [f32; 3]| Source::Procedural { pattern: Procedural { scale, ..Procedural::new(kind) }, low, high, ramp: Vec::new() };
let mut fill = Fill::default();
fill.sources.insert(Channel::BaseColor, procedural(ProceduralKind::Clouds, 2.0, [0.05, 0.2, 0.55], [0.95, 0.55, 0.1]));
fill.sources.insert(Channel::Roughness, procedural(ProceduralKind::Checker, 4.0, [0.25; 3], [0.7; 3]));
+2 -2
View File
@@ -27,7 +27,7 @@ pub fn specs() -> Vec<CommandSpec> {
"Add smart material",
[],
None,
"{material: id or label, above?: layer id, inside?: bool, index?: n} — above the selection by default; `above` (+ `inside` for a folder) or `index` in the top-level stack (0 = bottom) place it",
"{material: id or label, above?: layer id, inside?: bool, below?: layer id, top?: true, index?: n} — above the selection by default; `above` (+ `inside` for a folder), `below`, `top` or `index` in the top-level stack (0 = bottom) place it",
always,
material
),
@@ -82,7 +82,7 @@ pub fn sample_session(resolution: u32, bake_resolution: u32) -> Result<Session>
// Paint above the smart material so new strokes remain visible
for set_index in (0..session.set_count()).rev() {
session.active_set = set_index;
session.selected.remove(&set_index);
session.select_none(set_index);
crate::execute(&mut session, "layer.add.paint", &Value::Null)?;
}
session.undo.clear();
+128 -12
View File
@@ -14,6 +14,7 @@ use texturecraft_paint::{BrushSettings, EyeDepth, Stroke, StrokeCanvas};
use texturecraft_texel::DilationMap;
use crate::fill_mode::FillMode;
pub use crate::stencil_look::StencilLook;
use crate::{EngineError, Result};
/// Padding (texels) applied to composites for display.
@@ -182,7 +183,24 @@ pub struct StencilState {
impl StencilState {
pub fn new(image: &str) -> StencilState {
StencilState { image: image.to_string(), center: [0.0, 0.0], scale: 0.8, rotation: 0.0, tile: false, opacity: 0.5 }
StencilState::with_look(image, StencilLook::default())
}
/// A stencil of `image` placed as `look` says.
pub fn with_look(image: &str, look: StencilLook) -> StencilState {
StencilState { image: image.to_string(), center: look.center, scale: look.scale, rotation: look.rotation, tile: look.tile, opacity: look.opacity }
}
pub fn look(&self) -> StencilLook {
StencilLook { center: self.center, scale: self.scale, rotation: self.rotation, tile: self.tile, opacity: self.opacity }
}
/// Back to the placement a new stencil starts with (center, scale and rotation); the image, tiling and opacity stay.
pub fn reset_placement(&mut self) {
let start = StencilState::new(&self.image);
self.center = start.center;
self.scale = start.scale;
self.rotation = start.rotation;
}
/// Placement for a viewport aspect (width / height): center, half extents in NDC, radians.
@@ -201,6 +219,10 @@ pub struct ToolState {
/// Material painted per channel (linear values) and whether each channel is painted.
pub values: BTreeMap<Channel, [f32; 3]>,
pub enabled: BTreeSet<Channel>,
/// The simple material (shelf id) the brush paints the pattern of, with `values` as its plain
/// stand-in; `None` for plain values (any edit of a value clears it).
#[serde(default)]
pub material: Option<String>,
/// Gray painted into masks.
pub mask_value: f32,
pub fill_mode: FillMode,
@@ -213,12 +235,21 @@ pub struct ToolState {
/// Stencil used by the Projection tool.
#[serde(default)]
pub stencil: Option<StencilState>,
/// Placement the next stencil starts with: the last stencil's, kept when the stencil is
/// cleared or the project changes (its image belongs to the project, the placement does not).
#[serde(default)]
pub stencil_look: StencilLook,
/// Smudge tool: how much of the picked-up values each stamp deposits (0..1).
#[serde(default = "default_smudge_strength")]
pub smudge_strength: f32,
/// Clone tool source (V + click).
/// Clone tool source (V + click). It belongs to the active texture set: switching the set
/// (`textureSet.select`, `layer.select` into another set) clears it.
#[serde(default)]
pub clone_source: Option<CloneSource>,
/// Clone tool: keep the offset of the first stroke for the following strokes (aligned, the
/// default). Off, every stroke starts sampling at the source point.
#[serde(default = "default_clone_aligned")]
pub clone_aligned: bool,
/// What the Clone tool copies: the composite or the selected layer alone.
#[serde(default)]
pub clone_from: CloneFrom,
@@ -227,10 +258,14 @@ pub struct ToolState {
pub path: crate::path_tool::PathState,
}
fn default_smudge_strength() -> f32 {
pub(crate) fn default_smudge_strength() -> f32 {
0.5
}
fn default_clone_aligned() -> bool {
true
}
fn default_fill_visible_only() -> bool {
true
}
@@ -250,7 +285,7 @@ pub enum CloneFrom {
pub struct CloneSource {
pub uv: [f32; 2],
/// Source minus destination, fixed by the first stroke after the source was set and kept
/// for the following strokes (aligned cloning).
/// for the following strokes (aligned cloning; never set when the tool is not aligned).
pub offset: Option<[f32; 2]>,
}
@@ -262,13 +297,16 @@ impl Default for ToolState {
brush: BrushSettings::default(),
values,
enabled: [Channel::BaseColor, Channel::Metallic, Channel::Roughness, Channel::Height, Channel::Normal].into_iter().collect(),
material: None,
mask_value: 1.0,
fill_mode: FillMode::Triangle,
fill_hit_test: Default::default(),
fill_visible_only: default_fill_visible_only(),
stencil: None,
stencil_look: StencilLook::default(),
smudge_strength: default_smudge_strength(),
clone_source: None,
clone_aligned: true,
clone_from: CloneFrom::Composite,
path: Default::default(),
};
@@ -315,6 +353,48 @@ pub(crate) struct ActiveStroke {
/// A stroke visibility buffer and what it was rendered for: camera, size, mesh id.
pub(crate) type DepthCache = (OrbitCamera, (u32, u32), u64, Arc<EyeDepth>);
/// History labels that name a layer, a path number or a smart mask: the UI translates the
/// template and fills the value in (the control channel and `edit.history` keep the English label).
/// `{layer}` is a layer name, `{n}` a path number, `{name}` a smart mask name.
pub const HISTORY_TEMPLATES: &[&str] = &[
"Paint on {layer}",
"Erase on {layer}",
"Clone on {layer}",
"Smudge on {layer}",
"Projection on {layer}",
"Paint mask of {layer}",
"Erase mask of {layer}",
"Projection mask of {layer}",
EDIT_PATH_TEMPLATE,
APPLY_SMART_MASK_TEMPLATE,
];
pub(crate) const EDIT_PATH_TEMPLATE: &str = "Edit path {n}";
pub(crate) const APPLY_SMART_MASK_TEMPLATE: &str = "Apply smart mask {name}";
pub(crate) const QUICK_MASK_STROKE_LABEL: &str = "Quick mask stroke";
/// `template` with its one `{...}` placeholder replaced by `value`
pub fn history_label(template: &str, value: &str) -> String {
match (template.find('{'), template.find('}')) {
(Some(open), Some(close)) if open < close => format!("{}{}{}", &template[..open], value, &template[close + 1..]),
_ => template.to_string(),
}
}
/// The history template of a stroke by `tool`, on a layer or (`on_mask`) on its mask
pub fn stroke_template(tool: Tool, on_mask: bool) -> &'static str {
match (tool, on_mask) {
(Tool::Eraser, false) => "Erase on {layer}",
(Tool::Eraser, true) => "Erase mask of {layer}",
(Tool::Clone, _) => "Clone on {layer}",
(Tool::Smudge, _) => "Smudge on {layer}",
(Tool::Projection, false) => "Projection on {layer}",
(Tool::Projection, true) => "Projection mask of {layer}",
(_, false) => "Paint on {layer}",
(_, true) => "Paint mask of {layer}",
}
}
pub struct Session {
pub doc: Document,
pub mesh: Arc<Mesh>,
@@ -340,9 +420,14 @@ pub struct Session {
pub active_set: usize,
/// Selected layer per texture set.
pub selected: BTreeMap<usize, LayerId>,
/// Layers selected together with the selected one (Shift+click, Ctrl+click), per texture set.
/// Counts only while the selected layer is the one they were picked with (see [`Session::selected_layers`]).
pub(crate) multi: BTreeMap<usize, crate::layer_selection::MultiSelection>,
pub target: StackTarget,
pub camera: OrbitCamera,
pub view: ViewMode,
/// The layer shown alone in the viewport (not saved, not in the history; see [`crate::solo`]).
pub solo: Option<crate::Solo>,
/// The live bake preview while the app bakes (see [`crate::bake_preview`]).
pub bake_preview: Option<crate::bake_preview::BakePreview>,
/// Viewport size (pixels) used by scripted strokes.
@@ -415,9 +500,11 @@ impl Session {
tool: ToolState::default(),
active_set: 0,
selected,
multi: BTreeMap::new(),
target: StackTarget::Content,
camera,
view: ViewMode::Material,
solo: None,
bake_preview: None,
viewport: Vec2::new(1280.0, 800.0),
stroke: None,
@@ -451,8 +538,8 @@ impl Session {
Ok(session)
}
/// Replace this session with `next` (another project), keeping the viewport size and the
/// user's brush presets, export presets and project templates.
/// Replace this session with `next` (another project), keeping the viewport size, the
/// user's brush presets, export presets and project templates and the tool settings.
pub fn switch_to(&mut self, mut next: Session) {
// Invalidate caches even when both projects were loaded with the same revision
next.revision = self.revision.wrapping_add(1);
@@ -461,6 +548,7 @@ impl Session {
next.export_presets = std::mem::take(&mut self.export_presets);
next.brush_presets = std::mem::take(&mut self.brush_presets);
next.templates = std::mem::take(&mut self.templates);
crate::tool_settings::ToolSettings::of(&self.tool).apply(&mut next.tool);
*self = next;
}
@@ -536,21 +624,35 @@ impl Session {
/// [`Session::edit`] that, with `merge`, continues the previous undo step when it has the same label (a viewport drag is one step however many updates it makes).
pub fn edit_merging<T>(&mut self, label: &str, merge: bool, change: impl FnOnce(&mut Session) -> Result<T>) -> Result<T> {
self.edit_if_changed(label, merge, |s| change(s).map(|value| (value, true)))
}
/// A conditional edit shares the usual rollback and history snapshot with layer reorders.
pub(crate) fn edit_if_changed<T>(&mut self, label: &str, merge: bool, change: impl FnOnce(&mut Session) -> Result<(T, bool)>) -> Result<T> {
// A box fill under way becomes its own step first, so this edit isn't written over or folded into it
self.end_polygon_fill_box();
let before = self.doc.clone();
let result = change(self).and_then(|value| match self.doc.project.instance_cycle() {
Some(id) => Err(EngineError::Other(format!("instance layer {} would draw itself", id.0))),
None => Ok(value),
let result = change(self).and_then(|(value, changed)| {
if changed && let Some(id) = self.doc.project.instance_cycle() {
return Err(EngineError::Other(format!("instance layer {} would draw itself", id.0)));
}
Ok((value, changed))
});
match result {
Ok(value) => {
self.record(label, before, merge);
Ok((value, changed)) => {
if changed {
self.record(label, before, merge);
}
Ok(value)
}
Err(error) => {
self.doc = before;
// A failed repaint may have cached tiles from the discarded document
self.path_cache = None;
Err(error)
}
}
@@ -603,6 +705,11 @@ impl Session {
self.follow_uv_layouts(&previous_document.project);
self.sync_caches();
// Removed path effects must release their cached painted tiles
if self.path_cache.as_ref().is_some_and(|cache| self.paths(cache.eid).is_none()) {
self.path_cache = None;
}
// Removed or replaced resources may change any set's rendered content
let removed_or_replaced_resource =
previous_document.resources.iter().any(|(name, previous)| !self.doc.resources.get(name).is_some_and(|current| Arc::ptr_eq(previous, current)));
@@ -816,6 +923,9 @@ impl Session {
fn after_history(&mut self, other: &Document) {
self.modified = true;
// Layers picked together belong to the stack they were picked in
self.multi.clear();
self.revision = self.revision.wrapping_add(1);
self.invalidate_changed(other);
@@ -864,10 +974,16 @@ impl Session {
values: stroke.values.clone(),
mask_value: self.tool.mask_value,
stencil: stroke.stencil.clone(),
carried_mask: stroke.canvas.pickup.as_ref().and_then(|pickup| pickup.mask_values()).cloned(),
carried: stroke.canvas.pickup.as_ref().map(|pickup| pickup.values.clone()).unwrap_or_default(),
})
});
// A soloed layer's view of the project; a removed layer ends the solo
if self.solo.is_some_and(|solo| self.doc.project.locate(solo.layer).is_none()) {
self.set_solo(None);
}
let solo_view = if self.pending_tiles() > 0 { self.solo_view() } else { None };
let active = self.ts();
let order = std::iter::once(active).chain((0..self.caches.len()).filter(|ts| *ts != active));
let mut changed = false;
@@ -898,7 +1014,7 @@ impl Session {
let empty = BakedMaps::default();
let inputs = texturecraft_compose::Inputs {
project: &self.doc.project,
project: solo_view.as_ref().unwrap_or(&self.doc.project),
ts,
mesh: &self.mesh,
gbuf: &cache.gbuf,
+3
View File
@@ -90,6 +90,9 @@ pub(crate) fn select_set(s: &mut Session, ts: usize) -> Result<()> {
// Paths paint into the active set
if ts != s.ts() {
s.finish_path()?;
// The clone source is a point of the set it was picked in
s.tool.clone_source = None;
}
s.active_set = ts;
+178 -7
View File
@@ -1,10 +1,15 @@
//! Smart masks: procedural mask presets (generators and patterns driven by the baked mesh maps)
//! that replace a layer's mask in one step. Smart materials build their masks from the same
//! presets.
//! presets. A user smart mask is a layer's mask saved to a `.tcmask` file (the `.tcraft`
//! container holding one layer that carries the mask) and applied back like a preset.
use std::collections::BTreeMap;
use std::sync::Arc;
use serde_json::{Value, json};
use texturecraft_core::{
BlendMode, Effect, EffectKind, Filter, Generator, GeneratorKind, LayerId, Mask, MaskBackground, Procedural, ProceduralKind, Project, Projection, Source,
BlendMode, Effect, EffectKind, Filter, Generator, GeneratorKind, Layer, LayerId, LayerKind, Mask, MaskBackground, Procedural, ProceduralKind, Project,
Projection, Source,
};
use crate::commands::{CommandSpec, always, bad, has_layer, layer_param, strp};
@@ -13,13 +18,25 @@ use crate::{EngineError, Result, Session, cmd};
pub fn specs() -> Vec<CommandSpec> {
vec![
cmd!("mask.smart.apply", "Apply smart mask", [], None, "{name: smart mask id or label, layer?}", has_layer, apply_cmd),
cmd!("mask.smart.apply", "Apply smart mask", [], None, "{name: smart mask id or label, layer?} or {path: .tcmask file, layer?}", has_layer, apply_cmd),
cmd!(
"mask.smart.create",
"Create smart mask",
[],
None,
"{layer?, path: .tcmask file, name?} — saves the layer's mask (all effects, parameters, painted pixels and images) as a user smart mask",
has_layer,
create_cmd
),
cmd!("mask.smart.list", "List smart masks", [], None, "{}", always, |_, _| Ok(json!(
SMART_MASKS.iter().map(|m| json!({"id": m.id, "label": m.label})).collect::<Vec<_>>()
))),
]
}
/// Smart mask file extension.
pub const SMART_MASK_EXT: &str = "tcmask";
pub struct SmartMask {
pub id: &'static str,
pub label: &'static str,
@@ -75,7 +92,12 @@ pub(crate) fn directional(kind: GeneratorKind, direction: [f32; 3], level: f32,
/// A triplanar grayscale pattern fill.
pub(crate) fn pattern(kind: ProceduralKind, scale: f32, seed: u32, contrast: f32) -> EffectKind {
EffectKind::Fill {
source: Source::Procedural { pattern: Procedural { kind, scale, seed, contrast, balance: 0.0, invert: false }, low: [0.0; 3], high: [1.0; 3] },
source: Source::Procedural {
pattern: Procedural { kind, scale, seed, contrast, balance: 0.0, invert: false },
low: [0.0; 3],
high: [1.0; 3],
ramp: Vec::new(),
},
projection: Projection::Triplanar { scale: 1.0, sharpness: 8.0, offset: [0.0; 3] },
}
}
@@ -162,7 +184,7 @@ pub(crate) fn mask(p: &mut Project, id: &str, invert: bool) -> Result<Mask> {
/// Replace layer `layer`'s mask with smart mask `name` (one undo step).
pub fn apply(s: &mut Session, layer: LayerId, name: &str) -> Result<()> {
let sm = find(name).ok_or_else(|| EngineError::Other(format!("unknown smart mask `{name}`")))?;
s.edit(&format!("Apply smart mask {}", sm.label), |s| {
s.edit(&crate::session::history_label(crate::session::APPLY_SMART_MASK_TEMPLATE, sm.label), |s| {
let m = mask(&mut s.doc.project, sm.id, false)?;
let old = s.doc.project.layer_mut(layer)?.mask.replace(m);
for e in old.map(|m| m.effects).unwrap_or_default() {
@@ -173,13 +195,162 @@ pub fn apply(s: &mut Session, layer: LayerId, name: &str) -> Result<()> {
})
}
impl Session {
/// Serialize layer `layer`'s mask (an instance without its own mask has its source's) as a user smart mask file named `name`.
pub fn smart_mask_bytes(&self, layer: LayerId, name: &str) -> Result<Vec<u8>> {
let owner = self.doc.project.mask_owner(layer);
let mask = self.doc.project.layer(owner)?.mask.clone().ok_or_else(|| EngineError::Other("the layer has no mask".into()))?;
let (ts, _, _) = self.doc.project.locate(owner).ok_or_else(|| EngineError::Other("layer not in a stack".into()))?;
let set = self.doc.project.texture_set(ts)?;
let mut mini = crate::material_lib::one_set_document(set, name);
let id = mini.project.alloc_id();
let mut holder = Layer::new(id, name, LayerKind::Paint, &set.channel_list());
// The mask comes back switched on whatever state it was saved in
holder.mask = Some(Mask { enabled: true, ..copy_mask(&self.doc, &mask, &mut mini, set.size())? });
mini.project.insert_layer(0, holder, None, false)?;
self.file_bytes(mini, id)
}
/// Replace layer `layer`'s mask with the one in a user smart mask file (one undo step).
pub fn apply_smart_mask_bytes(&mut self, layer: LayerId, bytes: &[u8]) -> Result<()> {
let pf = texturecraft_formats::load_project_bytes(bytes).map_err(|e| EngineError::Other(e.to_string()))?;
self.apply_smart_mask_file(layer, pf)
}
fn apply_smart_mask_file(&mut self, layer: LayerId, pf: texturecraft_formats::ProjectFile) -> Result<()> {
let mask = pf
.project
.texture_sets
.first()
.and_then(|t| t.stack.last().copied())
.and_then(|root| pf.project.layers.get(&root))
.and_then(|l| l.mask.clone())
.ok_or_else(|| EngineError::Other("the smart mask file has no mask".into()))?;
let resources: BTreeMap<String, Arc<Vec<u8>>> = pf.resources.into_iter().map(|(k, v)| (k, Arc::new(v))).collect();
let src = crate::session::Document {
bake_paint: BTreeMap::new(),
project: pf.project,
pixels: pf.pixels,
baked: BTreeMap::new(),
resources: BTreeMap::new(),
};
let label = src.project.texture_sets.first().map(|t| t.name.clone()).unwrap_or_default();
self.edit(&format!("Apply smart mask {label}"), |s| {
let (ts, _, _) = s.doc.project.locate(layer).ok_or_else(|| EngineError::Other("layer not in a stack".into()))?;
let size = s.doc.project.texture_set(ts)?.size();
// An image whose name the project already uses for other bytes comes in under a new name
let mut renames = BTreeMap::new();
for (name, bytes) in &resources {
let mut taken = name.clone();
let mut number = 2;
while s.doc.resources.get(&taken).is_some_and(|have| have != bytes) {
let (stem, ext) = name.rsplit_once('.').map_or((name.as_str(), String::new()), |(stem, ext)| (stem, format!(".{ext}")));
taken = format!("{stem}_{number}{ext}");
number += 1;
}
s.doc.resources.entry(taken.clone()).or_insert_with(|| bytes.clone());
if taken != *name {
renames.insert(name.clone(), taken);
}
}
let mut new = copy_mask(&src, &mask, &mut s.doc, size)?;
for source in new.effects.iter_mut().flat_map(|effect| sources_mut(&mut effect.kind)) {
if let Source::Image { name, .. } = source
&& let Some(renamed) = renames.get(name.as_str())
{
*name = renamed.clone();
}
}
let old = s.doc.project.layer_mut(layer)?.mask.replace(new);
for e in old.map(|m| m.effects).unwrap_or_default() {
s.doc.pixels.masks.remove(&e.id);
}
s.target = StackTarget::Mask;
Ok(())
})?;
self.sync_images();
Ok(())
}
}
/// The sources an effect reads.
fn sources_mut(kind: &mut EffectKind) -> Vec<&mut Source> {
match kind {
EffectKind::Fill { source, .. } => vec![source],
EffectKind::Material(fill) => fill.sources.values_mut().collect(),
EffectKind::Generator(generator) => generator.inputs.values_mut().collect(),
_ => Vec::new(),
}
}
/// `mask` of document `src` with fresh effect ids from `dst` (anchor sources follow), its painted pixels moved to `dst` at `size`.
fn copy_mask(src: &crate::session::Document, mask: &Mask, dst: &mut crate::session::Document, size: (u32, u32)) -> Result<Mask> {
let mut copy = mask.clone();
let mut moved = BTreeMap::new();
for e in &mut copy.effects {
let old = e.id;
e.id = dst.project.alloc_id();
if matches!(e.kind, EffectKind::Anchor) {
moved.insert(old, e.id);
}
if let Some(img) = src.pixels.masks.get(&old) {
dst.pixels.masks.insert(e.id, crate::layer_ops::fit(img, size, &[0, 0]));
}
}
// Sources that read an anchor effect of this mask follow it to its new id
for source in copy.effects.iter_mut().flat_map(|effect| sources_mut(&mut effect.kind)) {
if let Source::Anchor { anchor, .. } = source {
*anchor = *moved.get(anchor).ok_or_else(|| EngineError::Other(format!("smart mask refers to anchor {} outside this mask", anchor.0)))?;
}
}
Ok(copy)
}
fn apply_cmd(s: &mut Session, p: &Value) -> Result<Value> {
let name = strp(p, "name").ok_or_else(|| bad("mask.smart.apply", "`name` is required"))?;
let layer = layer_param(s, "mask.smart.apply", p)?;
apply(s, layer, name)?;
if let Some(path) = strp(p, "path") {
apply_file(s, layer, path)?;
} else {
let name = strp(p, "name").ok_or_else(|| bad("mask.smart.apply", "`name` or `path` is required"))?;
apply(s, layer, name)?;
}
Ok(json!({ "layer": layer.0 }))
}
#[cfg(not(target_arch = "wasm32"))]
fn apply_file(s: &mut Session, layer: LayerId, path: &str) -> Result<()> {
let file = texturecraft_formats::load_project(std::path::Path::new(path)).map_err(|e| bad("mask.smart.apply", format!("cannot read {path}: {e}")))?;
s.apply_smart_mask_file(layer, file)
}
#[cfg(target_arch = "wasm32")]
fn apply_file(_: &mut Session, _: LayerId, _: &str) -> Result<()> {
Err(EngineError::Other("file paths are not available in the browser".into()))
}
#[cfg(not(target_arch = "wasm32"))]
fn create_cmd(s: &mut Session, p: &Value) -> Result<Value> {
let layer = layer_param(s, "mask.smart.create", p)?;
let path = strp(p, "path").ok_or_else(|| bad("mask.smart.create", "`path` is required"))?;
let name = strp(p, "name").map(str::to_string).unwrap_or_else(|| s.doc.project.layer(layer).map(|l| l.name.clone()).unwrap_or_default());
let bytes = s.smart_mask_bytes(layer, &name)?;
let path = if path.ends_with(&format!(".{SMART_MASK_EXT}")) { path.to_string() } else { format!("{path}.{SMART_MASK_EXT}") };
if let Some(dir) = std::path::Path::new(&path).parent().filter(|d| !d.as_os_str().is_empty()) {
std::fs::create_dir_all(dir).map_err(|e| bad("mask.smart.create", format!("cannot create {}: {e}", dir.display())))?;
}
texturecraft_formats::write_atomic(std::path::Path::new(&path), &bytes).map_err(|e| bad("mask.smart.create", format!("cannot write {path}: {e}")))?;
Ok(json!({ "path": path }))
}
#[cfg(target_arch = "wasm32")]
fn create_cmd(_: &mut Session, _: &Value) -> Result<Value> {
Err(EngineError::Other("file paths are not available in the browser".into()))
}
#[cfg(test)]
mod tests {
use super::*;
+88
View File
@@ -0,0 +1,88 @@
//! Solo: a view-only preview of one layer on its own. The compositor draws a copy of the project
//! in which the other layers of the soloed layer's texture set are hidden (see
//! [`texturecraft_compose::solo_project`]); the document, the undo history, saving, exporting and
//! baking never see it.
use serde_json::{Value, json};
use texturecraft_core::{LayerId, Project};
use crate::commands::{CommandSpec, always, bad, boolp, layer_param};
use crate::{Result, Session, cmd};
/// The layer shown alone and whether its mask is ignored (full coverage).
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub struct Solo {
pub layer: LayerId,
pub ignore_mask: bool,
}
pub(crate) fn specs() -> Vec<CommandSpec> {
vec![cmd!(
"view.solo",
"Solo layer",
[],
None,
"{layer?: id | null (default: the selected layer; null ends the solo), ignoreMask?: bool (show the layer at full coverage, default false)} → {layer: id | null, ignoreMask}. View only: nothing is saved, exported, baked or put in the undo history",
always,
solo
)]
}
fn solo(s: &mut Session, p: &Value) -> Result<Value> {
let next = match p.get("layer") {
Some(Value::Null) => None,
_ => {
let layer = layer_param(s, "view.solo", p)?;
if s.doc.project.locate(layer).is_none() {
return Err(bad("view.solo", "the layer is not in a stack"));
}
Some(Solo { layer, ignore_mask: boolp(p, "ignoreMask").unwrap_or(false) })
}
};
s.set_solo(next);
Ok(json!({ "layer": s.solo.map(|solo| solo.layer.0), "ignoreMask": s.solo.is_some_and(|solo| solo.ignore_mask) }))
}
impl Session {
/// Show `solo` alone (None: the whole stack again). Changes only the view: every covered
/// tile of every set is composited again, and the next frame draws it.
pub fn set_solo(&mut self, solo: Option<Solo>) {
if self.solo == solo {
return;
}
self.solo = solo;
for cache in &mut self.caches {
// What the cache holds was composited from the other stack
cache.below = Default::default();
cache.invalidate_all();
}
self.revision = self.revision.wrapping_add(1);
}
/// The project as the compositor draws it: the soloed layer's, or None for the document's own.
pub(crate) fn solo_view(&self) -> Option<Project> {
let solo = self.solo?;
texturecraft_compose::solo_project(&self.doc.project, solo.layer, solo.ignore_mask)
}
/// Sample document pixels while solo keeps its own composite in the viewport cache.
pub(crate) fn document_composite(&self, ts: usize, tiles: &[(u32, u32)]) -> Option<std::borrow::Cow<'_, texturecraft_compose::Composite>> {
use std::borrow::Cow;
use texturecraft_compose::{Composite, composite_tiles, pad_tiles};
let cache = self.caches.get(ts)?;
if self.solo.is_none() {
return Some(Cow::Borrowed(&cache.composite));
}
self.with_inputs(ts, |inputs| {
let set = inputs.project.texture_sets.get(ts)?;
let mut output = Composite { block_scales: inputs.block_scales.clone(), ..Composite::with_size(&set.channel_list(), cache.size.0, cache.size.1) };
composite_tiles(inputs, &mut output, tiles);
pad_tiles(&mut output, &cache.dilation, tiles);
Some(Cow::Owned(output))
})
}
}
+33
View File
@@ -0,0 +1,33 @@
use serde::{Deserialize, Serialize};
/// How a stencil sits on screen, without the image (which is a project resource)
#[derive(Clone, Copy, Debug, PartialEq, Serialize, Deserialize)]
pub struct StencilLook {
pub center: [f32; 2],
pub scale: f32,
pub rotation: f32,
pub tile: bool,
pub opacity: f32,
}
impl Default for StencilLook {
fn default() -> Self {
StencilLook { center: [0.0, 0.0], scale: 0.8, rotation: 0.0, tile: false, opacity: 0.5 }
}
}
impl StencilLook {
pub(crate) const MAX_CENTER_OFFSET: f32 = 4.0;
pub(crate) const MIN_SCALE: f32 = 0.01;
pub(crate) const MAX_SCALE: f32 = 10.0;
pub(crate) fn sanitized(mut self) -> Self {
let defaults = Self::default();
let finite = |value: f32, fallback| if value.is_finite() { value } else { fallback };
self.center = self.center.map(|v| finite(v, 0.0).clamp(-Self::MAX_CENTER_OFFSET, Self::MAX_CENTER_OFFSET));
self.scale = finite(self.scale, defaults.scale).clamp(Self::MIN_SCALE, Self::MAX_SCALE);
self.rotation = finite(self.rotation, defaults.rotation).rem_euclid(360.0);
self.opacity = finite(self.opacity, defaults.opacity).clamp(0.0, 1.0);
self
}
}
+2 -4
View File
@@ -26,11 +26,9 @@ impl Session {
let project = &self.doc.project;
let Some(layer) = self.selected_layer().and_then(|id| project.layers.get(&id)) else { return false };
// Smudge and Clone read layer content, so they can't yet paint mask values
let reads_content = matches!(tool, Tool::Smudge | Tool::Clone);
match self.target {
StackTarget::Content => matches!(layer.kind, LayerKind::Paint),
StackTarget::Mask => !reads_content,
StackTarget::Mask => true,
StackTarget::Effect(effect) => {
let Some((owner, found)) = project.effect(effect) else { return false };
let Some(owner_layer) = project.layers.get(&owner) else { return false };
@@ -41,7 +39,7 @@ impl Session {
// Paths saved in a fill layer before paths there were removed stay editable
EffectKind::Path(_) => tool == Tool::Path,
EffectKind::Paint if tool == Tool::Path => !in_fill_content,
EffectKind::Paint => in_content || !reads_content,
EffectKind::Paint => true,
_ => false,
}
}
+55 -7
View File
@@ -36,7 +36,7 @@ pub fn specs() -> Vec<CommandSpec> {
"Brush settings",
[],
None,
"{size?: 0..100, flow?: 0..100, opacity?: 0..100, spacing?: 1..1000, hardness?: 0..100, angle?, followPath?, alignment?: tangent|camera, lazy?, jitterSize?, jitterAngle?, jitterFlow?, jitterPosition?, alpha?: procedural name | {image: resource name} | {library: id (alpha.list)}, backfaceCulling?, symmetryOn? (the toolbar toggle; off keeps the settings), symmetryX?, symmetryY?, symmetryZ?, symmetryRadial?: 0..32 copies around symmetryAxis?: x|y|z (default y), symmetryOffset?: [x, y, z] (world units from the mesh center, where the mirror planes and radial axis cross), symmetryAngleSpan?: 0..360 degrees the radial copies spread over, minSize?, smudgeStrength?: 0..100, cloneSource?: composite|layer (what the Clone tool copies), particles?: {enabled?, count?: 1..16, lifetime?: 1..128 steps, gravity?: 0..2}}",
"{size?: 0..100, flow?: 0..100, opacity?: 0..100, spacing?: 1..1000, hardness?: 0..100, angle?, followPath?, alignment?: tangent|camera, lazy?, jitterSize?, jitterAngle?, jitterFlow?, jitterPosition?, alpha?: procedural name | {image: resource name} | {library: id (alpha.list)}, alphaSizeX?: 5..100 and alphaSizeY?: 5..100 (percent of the stamp the alpha fills), alphaRoundness?: 0..100 (Round alpha only: 100 circle, 0 square), alphaContrast?: 1..8, alphaInvert?, backfaceCulling?, symmetryOn? (the toolbar toggle; off keeps the settings), symmetryX?, symmetryY?, symmetryZ?, symmetryRadial?: 0..32 copies around symmetryAxis?: x|y|z (default y), symmetryOffset?: [x, y, z] (world units from the mesh center, where the mirror planes and radial axis cross), symmetryAngleSpan?: 0..360 degrees the radial copies spread over, minSize?, smudgeStrength?: 0..100, cloneSource?: composite|layer (what the Clone tool copies), cloneAligned? (default true: the first stroke fixes the offset to the source for the following strokes; false: every stroke starts sampling at the source point), particles?: {enabled?, count?: 1..16, lifetime?: 1..128 steps, gravity?: 0..2}}",
always,
brush
),
@@ -49,7 +49,7 @@ pub fn specs() -> Vec<CommandSpec> {
"Tool material",
[],
None,
"{channel, color?|value?, enabled?, solo?: true (paint this channel only)} or {maskValue?: 0..1}",
"{channel, color?|value?, enabled?, solo?: true (paint this channel only)} or {maskValue?: 0..1} or {material: id or label of a simple material (see material.list, smart: false)} — the brush paints that material's pattern (colour, metallic, roughness, height…, fixed to the surface, its size following the brush size) in the channels that are on; no layer is added, smart materials are refused (add them with material.apply)",
always,
material
),
@@ -199,6 +199,19 @@ fn brush(session: &mut Session, params: &Value) -> Result<Value> {
(settings.alpha_image, settings.alpha_library) = (None, Some(alpha.id.clone()));
}
let alpha_params = &mut settings.alpha_params;
for (key, slot) in [("alphaSizeX", &mut alpha_params.size_x), ("alphaSizeY", &mut alpha_params.size_y), ("alphaRoundness", &mut alpha_params.roundness)] {
if let Some(value) = percent(key) {
*slot = value;
}
}
if let Some(value) = f32p(params, "alphaContrast") {
alpha_params.contrast = value;
}
if let Some(value) = boolp(params, "alphaInvert") {
alpha_params.invert = value;
}
if let Some(value) = boolp(params, "backfaceCulling") {
settings.backface_culling = value;
}
@@ -258,6 +271,16 @@ fn brush(session: &mut Session, params: &Value) -> Result<Value> {
session.tool.brush = settings.sanitized();
session.tool.clone_from = clone_from;
if let Some(aligned) = boolp(params, "cloneAligned")
&& aligned != session.tool.clone_aligned
{
session.tool.clone_aligned = aligned;
// A new mode starts without the offset of an earlier stroke
if let Some(source) = session.tool.clone_source.as_mut() {
source.offset = None;
}
}
if let Some(value) = f32p(params, "smudgeStrength") {
session.tool.smudge_strength = (value / 100.0).clamp(0.0, 1.0);
}
@@ -277,11 +300,14 @@ pub(crate) fn brush_json(session: &Session) -> Value {
(None, Some(id)) => json!({ "library": id }),
(None, None) => json!(settings.alpha.label()),
},
"alphaSizeX": settings.alpha_params.size_x * 100.0, "alphaSizeY": settings.alpha_params.size_y * 100.0,
"alphaRoundness": settings.alpha_params.roundness * 100.0, "alphaContrast": settings.alpha_params.contrast, "alphaInvert": settings.alpha_params.invert,
"backfaceCulling": settings.backface_culling, "symmetry": [settings.symmetry.x, settings.symmetry.y, settings.symmetry.z],
"radialSymmetry": { "copies": settings.symmetry.radial, "axis": (["x", "y", "z"].get(settings.symmetry.axis as usize)) },
"symmetryOffset": settings.symmetry.offset, "symmetryOn": settings.symmetry.enabled, "symmetryAngleSpan": settings.symmetry.angle_span,
"smudgeStrength": session.tool.smudge_strength * 100.0, "particles": settings.particles,
"material": session.tool.material, "smudgeStrength": session.tool.smudge_strength * 100.0, "particles": settings.particles,
"cloneSource": if session.tool.clone_from == CloneFrom::Layer { "layer" } else { "composite" },
"cloneAligned": session.tool.clone_aligned,
})
}
@@ -289,6 +315,23 @@ fn material(s: &mut Session, p: &Value) -> Result<Value> {
let channel = channel_param("tool.material", p, "channel")?;
let color = color_param("tool.material", p, "color")?;
let value = color_param("tool.material", p, "value")?;
if let Some(id) = strp(p, "material") {
let values = crate::materials::brush_values(id).ok_or_else(|| {
bad("tool.material", format!("`{id}` is not a simple material (a brush paints plain values; add smart materials with material.apply)"))
})?;
// Reset omitted channels so values from the previous brush material do not persist
// Normal maps remain flat
for channel in Channel::ALL {
if channel.kind() == texturecraft_core::ChannelKind::NormalMap {
continue;
}
let value = values.iter().find(|(set, _)| *set == channel).map_or(channel.default_value(), |(_, value)| *value);
s.tool.values.insert(channel, value);
}
s.tool.material = Some(crate::materials::find(id).map_or_else(|| id.to_string(), |m| m.id.to_string()));
}
if let Some(v) = f32p(p, "maskValue") {
s.tool.mask_value = v.clamp(0.0, 1.0);
}
@@ -297,6 +340,7 @@ fn material(s: &mut Session, p: &Value) -> Result<Value> {
let v = if c == Channel::Height { v.map(|x| x.clamp(-1.0, 1.0)) } else { v.map(|x| x.clamp(0.0, 1.0)) };
s.tool.values.insert(c, v);
s.tool.enabled.insert(c);
s.tool.material = None;
}
match boolp(p, "enabled") {
Some(true) => {
@@ -313,6 +357,7 @@ fn material(s: &mut Session, p: &Value) -> Result<Value> {
}
s.revision = s.revision.wrapping_add(1);
Ok(json!({
"material": s.tool.material,
"values": s.tool.values.iter().map(|(c, v)| (c.id().to_string(), json!(v))).collect::<serde_json::Map<_, _>>(),
"enabled": s.tool.enabled.iter().map(|c| c.id()).collect::<Vec<_>>(),
"maskValue": s.tool.mask_value,
@@ -345,7 +390,9 @@ fn swap_mask_value(session: &mut Session, _: &Value) -> Result<Value> {
fn stencil(session: &mut Session, params: &Value) -> Result<Value> {
if boolp(params, "clear") == Some(true) {
session.tool.stencil = None;
if let Some(cleared) = session.tool.stencil.take() {
session.tool.stencil_look = cleared.look();
}
return Ok(Value::Null);
}
@@ -355,19 +402,20 @@ fn stencil(session: &mut Session, params: &Value) -> Result<Value> {
}
let previous_stencil = session.tool.stencil.take();
let mut stencil_state = crate::session::StencilState::new(name);
let mut stencil_state = crate::session::StencilState::with_look(name, session.tool.stencil_look);
if let Some(previous_stencil) = previous_stencil {
stencil_state = crate::session::StencilState { image: name.to_string(), ..previous_stencil };
}
session.tool.stencil = Some(stencil_state);
}
use crate::session::StencilLook;
let stencil_state = session.tool.stencil.as_mut().ok_or_else(|| bad("tool.stencil", "no stencil: give `image`"))?;
if let Some(center) = pair(params, "center").or_else(|| params.get("center").and_then(color_of).map(|color| [color[0], color[1]])) {
stencil_state.center = center.map(|value| value.clamp(-4.0, 4.0));
stencil_state.center = center.map(|value| value.clamp(-StencilLook::MAX_CENTER_OFFSET, StencilLook::MAX_CENTER_OFFSET));
}
if let Some(scale) = f32p(params, "scale") {
stencil_state.scale = scale.clamp(0.01, 10.0);
stencil_state.scale = scale.clamp(StencilLook::MIN_SCALE, StencilLook::MAX_SCALE);
}
if let Some(rotation) = f32p(params, "rotation") {
stencil_state.rotation = rotation.rem_euclid(360.0);
+65
View File
@@ -0,0 +1,65 @@
//! The tool settings that outlive a project: they are kept when another project opens and are
//! saved with the UI state, so the next session starts with the same brush.
use serde::{Deserialize, Serialize};
use crate::session::{CloneFrom, StencilLook, ToolState};
use texturecraft_paint::BrushSettings;
/// Brush, symmetry, stencil placement, smudge strength, clone mode and alignment and path switches. Left out
/// because they belong to one project: the clone source point, the stencil image, the points of
/// the path being drawn and the brush's image alpha (an image resource of that project).
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub struct ToolSettings {
pub brush: BrushSettings,
pub stencil: StencilLook,
pub smudge_strength: f32,
pub clone_from: CloneFrom,
/// Settings saved before the Aligned switch existed keep its default (on)
#[serde(default = "aligned_by_default")]
pub clone_aligned: bool,
pub path_closed: bool,
pub path_fill: bool,
}
fn aligned_by_default() -> bool {
true
}
impl Default for ToolSettings {
fn default() -> Self {
ToolSettings::of(&ToolState::default())
}
}
impl ToolSettings {
/// The settings `tool` has now.
pub fn of(tool: &ToolState) -> ToolSettings {
let mut brush = tool.brush.clone();
brush.alpha_image = None;
ToolSettings {
brush,
stencil: tool.stencil.as_ref().map_or(tool.stencil_look, |stencil| stencil.look()),
smudge_strength: tool.smudge_strength,
clone_from: tool.clone_from,
clone_aligned: tool.clone_aligned,
path_closed: tool.path.closed,
path_fill: tool.path.fill,
}
}
/// Make `tool` use these settings, leaving what belongs to its project alone.
pub fn apply(&self, tool: &mut ToolState) {
let alpha_image = tool.brush.alpha_image.take();
tool.brush = self.brush.clone().sanitized();
// An image alpha names a resource of the project that was open; the library alpha is global
tool.brush.alpha_image = alpha_image;
tool.stencil_look = self.stencil.sanitized();
tool.smudge_strength = if self.smudge_strength.is_finite() { self.smudge_strength.clamp(0.0, 1.0) } else { crate::session::default_smudge_strength() };
tool.clone_from = self.clone_from;
tool.clone_aligned = self.clone_aligned;
tool.path.closed = self.path_closed;
tool.path.fill = self.path_fill;
}
}
+6
View File
@@ -0,0 +1,6 @@
//! Symmetry for strokes painted in the 2D view: a dab's copies land where the 3D view's copies would
mod frame;
mod uv_mirror;
pub(crate) use uv_mirror::UvMirror;
+10
View File
@@ -0,0 +1,10 @@
use texturecraft_geom::glam::Vec3;
/// A point on a triangle with the 3D directions of one UV unit along U and along V
pub(super) struct Frame {
pub(super) pos: Vec3,
pub(super) along_u: Vec3,
pub(super) along_v: Vec3,
/// Surface length of one UV unit, for the distance a copy may be from the mirrored point
pub(super) scale: f32,
}
+141
View File
@@ -0,0 +1,141 @@
use texturecraft_geom::glam::{Mat3, Vec2, Vec3};
use texturecraft_geom::{Bvh, Mesh, NO_TRI, UvGBuffer, surface_at};
use texturecraft_paint::{StampSource, Symmetry, UvStamp};
use super::frame::Frame;
/// The mirror and radial maps of one stroke, applied to dabs through the mesh surface
pub(crate) struct UvMirror<'a> {
mesh: &'a Mesh,
bvh: &'a Bvh,
gbuf: &'a UvGBuffer,
/// The texture set's material: copies land on its triangles only, the ones the texture covers
material: usize,
origin: Vec3,
/// Linear maps of the copies as `origin + map * (p - origin)`, without the identity
maps: Vec<Mat3>,
}
impl<'a> UvMirror<'a> {
/// The copies' maps for `symmetry` about a mesh centered at `center`, `None` when it paints no copies
pub(crate) fn new(symmetry: &Symmetry, center: Vec3, mesh: &'a Mesh, bvh: &'a Bvh, gbuf: &'a UvGBuffer, material: usize) -> Option<Self> {
if !symmetry.any() {
return None;
}
// The identity comes first: it is the dab itself
let maps: Vec<Mat3> = symmetry.transforms().into_iter().skip(1).collect();
(!maps.is_empty()).then(|| UvMirror { mesh, bvh, gbuf, material, origin: symmetry.origin(center), maps })
}
/// Add the copies of `stamp` to `out`
pub(crate) fn add_copies(&self, stamp: &UvStamp, out: &mut Vec<UvStamp>) {
let Some(frame) = self.frame_at(stamp.center) else { return };
// The stamp's x axis (turned by its angle, y up on screen) on the surface; v grows down, so an angle turns towards -V
let (sin, cos) = stamp.angle.to_radians().sin_cos();
let x_axis = frame.along_u * cos - frame.along_v * sin;
let reach = stamp.radius * frame.scale;
for map in &self.maps {
let target = self.origin + *map * (frame.pos - self.origin);
let Some(hit) = self.bvh.nearest(target, reach, &|triangle| self.mesh.material_of(triangle as usize) == Some(self.material)) else { continue };
let Some(surface) = surface_at(self.mesh, hit.tri, hit.u, hit.v) else { continue };
let Some(landing) = self.frame_of(hit.tri, hit.u, hit.v) else { continue };
// Keep the dab's orientation as the 3D view does: its direction is mapped, its shape is not mirrored
let angle = turn_towards(&landing, *map * x_axis).map_or(stamp.angle, f32::to_degrees);
let source = Some(StampSource { origin: self.origin, to_source: map.transpose() });
out.push(UvStamp { center: surface.uv, angle, source, ..*stamp });
}
}
/// The surface under texture coordinate `uv`, `None` off the texture or where no triangle covers it
fn frame_at(&self, uv: Vec2) -> Option<Frame> {
let (width, height) = (self.gbuf.width as f32, self.gbuf.height as f32);
if !(0.0..1.0).contains(&uv.x) || !(0.0..1.0).contains(&uv.y) {
return None;
}
let texel = (uv.y * height) as usize * self.gbuf.width as usize + (uv.x * width) as usize;
let triangle = *self.gbuf.tri.get(texel).filter(|triangle| **triangle != NO_TRI)?;
let [a, b, c] = self.mesh.tri(triangle as usize)?;
let (ua, ub, uc) = (*self.mesh.uvs.get(a)?, *self.mesh.uvs.get(b)?, *self.mesh.uvs.get(c)?);
// Exact barycentrics of the dab's center, not the texel center's the G-buffer holds
let (to_b, to_c, to_point) = (ub - ua, uc - ua, uv - ua);
let double_area = to_b.x * to_c.y - to_c.x * to_b.y;
if double_area.abs() < f32::EPSILON {
return None;
}
let b1 = (to_point.x * to_c.y - to_c.x * to_point.y) / double_area;
let b2 = (to_b.x * to_point.y - to_point.x * to_b.y) / double_area;
self.frame_of(triangle, b1, b2)
}
/// The point of `triangle` with barycentrics `b1` and `b2` of its second and third corners, with its UV directions
fn frame_of(&self, triangle: u32, b1: f32, b2: f32) -> Option<Frame> {
let [a, b, c] = self.mesh.tri(triangle as usize)?;
let (pa, pb, pc) = (*self.mesh.positions.get(a)?, *self.mesh.positions.get(b)?, *self.mesh.positions.get(c)?);
let (ua, ub, uc) = (*self.mesh.uvs.get(a)?, *self.mesh.uvs.get(b)?, *self.mesh.uvs.get(c)?);
let (edge_b, edge_c, to_b, to_c) = (pb - pa, pc - pa, ub - ua, uc - ua);
let double_area = to_b.x * to_c.y - to_c.x * to_b.y;
if double_area.abs() < f32::EPSILON {
return None;
}
let along_u = (edge_b * to_c.y - edge_c * to_b.y) / double_area;
let along_v = (edge_c * to_b.x - edge_b * to_c.x) / double_area;
let scale = (edge_b.cross(edge_c).length() / double_area.abs()).sqrt();
let pos = pa + edge_b * b1 + edge_c * b2;
(pos.is_finite() && along_u.is_finite() && along_v.is_finite() && scale.is_finite()).then_some(Frame { pos, along_u, along_v, scale })
}
}
/// The angle (radians) a stamp's x axis needs in the UV frame of `landing` to point along `direction` on the surface
fn turn_towards(landing: &Frame, direction: Vec3) -> Option<f32> {
// Least squares for direction = along_u * cos - along_v * sin, with (cos, -sin) the unknowns
let (uu, uv, vv) = (landing.along_u.dot(landing.along_u), landing.along_u.dot(landing.along_v), landing.along_v.dot(landing.along_v));
let (u_dot, v_dot) = (landing.along_u.dot(direction), landing.along_v.dot(direction));
let det = uu * vv - uv * uv;
if det.abs() < f32::EPSILON {
return None;
}
let (cos, minus_sin) = ((u_dot * vv - v_dot * uv) / det, (v_dot * uu - u_dot * uv) / det);
let sin = -minus_sin;
(cos != 0.0 || sin != 0.0).then(|| sin.atan2(cos)).filter(|angle| angle.is_finite())
}
#[cfg(test)]
#[allow(clippy::unwrap_used)]
mod tests {
use super::*;
#[test]
fn a_quarter_turn_copy_turns_the_dab_angle_the_same_way() {
// A square in the XY plane: U along +X, V down along -Y
let positions = vec![Vec3::new(-1.0, -1.0, 0.0), Vec3::new(1.0, -1.0, 0.0), Vec3::new(1.0, 1.0, 0.0), Vec3::new(-1.0, 1.0, 0.0)];
let uvs = vec![Vec2::new(0.0, 1.0), Vec2::new(1.0, 1.0), Vec2::new(1.0, 0.0), Vec2::new(0.0, 0.0)];
let mesh = Mesh::from_parts(positions, None, uvs, vec![0, 1, 2, 0, 2, 3], "square").unwrap();
let (bvh, gbuf) = (Bvh::new(&mesh), UvGBuffer::new(&mesh, 0, 64, 64));
let symmetry = Symmetry { radial: 4, axis: 2, ..Symmetry::default() };
let mirror = UvMirror::new(&symmetry, Vec3::ZERO, &mesh, &bvh, &gbuf, 0).unwrap();
// The dab at world (0.5, 0) points 30 degrees up from +X
let stamp = UvStamp { center: Vec2::new(0.75, 0.5), radius: 0.05, angle: 30.0, flow: 1.0, hardness: 1.0, seed: 0, source: None };
let mut copies = Vec::new();
mirror.add_copies(&stamp, &mut copies);
assert_eq!(copies.len(), 3);
// A quarter turn about +Z puts the copy at world (0, 0.5), pointing 120 degrees from +X
let quarter = copies.iter().find(|copy| (copy.center - Vec2::new(0.5, 0.25)).length() < 0.01).unwrap();
assert!((quarter.angle - 120.0).abs() < 0.1, "angle {}", quarter.angle);
// Each copy is told apart from the stroke and the other copies (a smudge gives each its own trail)
let sources: Vec<_> = copies.iter().map(|copy| copy.source).collect();
assert!(sources.iter().all(Option::is_some), "copies carry their source");
assert!(sources.iter().enumerate().all(|(i, a)| sources.iter().skip(i + 1).all(|b| a != b)), "every copy has its own source");
}
}
+37 -3
View File
@@ -6,12 +6,30 @@ use texturecraft_core::{BakedMap, Channel, ToneMapping};
use texturecraft_geom::glam::Vec3;
use crate::commands::{CommandSpec, always, bad, boolp, can_redo, can_undo, color_param, f32p, strp, u64p};
use crate::frame_target::FrameTarget;
use crate::session::ViewMode;
use crate::{Result, Session, cmd};
pub fn specs() -> Vec<CommandSpec> {
vec![
cmd!("viewport.frame", "Show entire mesh", ["Viewport"], Some("F"), "{}", always, frame),
cmd!(
"viewport.frame",
"Show entire mesh",
["Viewport"],
Some("F"),
"{target?: \"all\" (default: the whole mesh, helper geometry included) | \"selection\" (the active texture set's geometry)} → the camera; the orbit turns around the framed center",
always,
frame
),
cmd!(
"viewport.frameSelection",
"Frame texture set",
["Viewport"],
Some("Shift+F"),
"{} → the camera, framing the active texture set's geometry",
always,
|s, _| frame_target(s, FrameTarget::Selection)
),
cmd!("viewport.displayMaterial", "Display material", ["Viewport"], Some("M"), "{}", always, |s, _| set_view(s, ViewMode::Material)),
cmd!("viewport.nextChannel", "Display next channel", ["Viewport"], Some("C"), "{}", always, |s, _| cycle_channel(s, 1)),
cmd!("viewport.previousChannel", "Display previous channel", ["Viewport"], Some("Shift+C"), "{}", always, |s, _| cycle_channel(s, -1)),
@@ -80,8 +98,24 @@ fn repeat(s: &mut Session, p: &Value, step: fn(&mut Session) -> Result<String>)
Ok((last, n))
}
fn frame(s: &mut Session, _: &Value) -> Result<Value> {
let (lo, hi) = s.mesh.bounds();
fn frame(s: &mut Session, p: &Value) -> Result<Value> {
let target = match strp(p, "target") {
None | Some("all") => FrameTarget::All,
Some("selection") => FrameTarget::Selection,
Some(other) => return Err(bad("viewport.frame", format!("unknown target `{other}` (all or selection)"))),
};
frame_target(s, target)
}
/// Frame the whole mesh, or only the triangles of the active texture set's material (the thing
/// being painted, without a floor plane or other helper geometry), and orbit around that center.
fn frame_target(s: &mut Session, target: FrameTarget) -> Result<Value> {
let selection = match target {
FrameTarget::Selection => s.doc.project.texture_sets.get(s.ts()).and_then(|set| s.mesh.bounds_of_material(set.material)),
FrameTarget::All => None,
};
let (lo, hi) = selection.unwrap_or_else(|| s.mesh.bounds());
s.camera.frame(lo, hi);
s.revision = s.revision.wrapping_add(1);
Ok(camera_json(s))
@@ -113,6 +113,7 @@ fn imported_mesh_maps_display_and_export_the_entire_overridden_tile() {
format: FileFormat::Png,
bit_depth: 8,
channels: vec![(Dest::L, SourceRef::Baked { map, component: 0 })],
inverted: Vec::new(),
}],
});
let files = session.export_files(&[0], &options).unwrap();
+195
View File
@@ -0,0 +1,195 @@
//! A simple shelf material can be the brush's material (`tool.material {material}`): no layer, and the
//! next stroke paints it. Shelf drops place new layers with `below` and `top`.
use serde_json::{Value, json};
use texturecraft_engine::core::{Channel, LayerId};
use texturecraft_engine::geom::glam::Vec2;
use texturecraft_engine::geom::primitives;
use texturecraft_engine::materials::{MATERIALS, brush_values};
use texturecraft_engine::{Session, execute};
fn session() -> Session {
let mut s = Session::new_project("t", primitives::sphere(1.0, 48, 24), "builtin:sphere", None, 256).unwrap();
s.viewport = Vec2::new(400.0, 400.0);
s.camera.yaw = 0.0;
s.camera.pitch = 0.0;
s.update();
s
}
fn stack(s: &Session) -> Vec<LayerId> {
s.doc.project.texture_set(0).unwrap().stack.clone()
}
#[test]
fn every_simple_material_has_brush_values_and_no_smart_material_has() {
for material in MATERIALS {
let values = brush_values(material.id);
assert_eq!(values.is_some(), !material.smart, "{}", material.id);
if let Some(values) = values {
let channels: Vec<Channel> = values.iter().map(|(channel, _)| *channel).collect();
for channel in [Channel::BaseColor, Channel::Metallic, Channel::Roughness] {
assert!(channels.contains(&channel), "{} has no {channel:?}", material.id);
}
}
}
assert!(brush_values("nope").is_none());
}
#[test]
fn a_material_set_on_the_brush_adds_no_layer_and_no_history() {
let mut s = session();
let (layers, history) = (stack(&s), s.history_labels());
execute(&mut s, "tool.material", &json!({"material": "copper_hammered"})).unwrap();
assert_eq!(stack(&s), layers);
assert_eq!(s.history_labels(), history);
for (channel, value) in brush_values("copper_hammered").unwrap() {
assert_eq!(s.tool.values[&channel], value, "{channel:?}");
}
assert!(s.tool.values[&Channel::Height][0] < 0.0, "the material's height comes along");
assert!(s.tool.enabled.contains(&Channel::Roughness), "the channel toggles stay as they were");
}
#[test]
fn a_material_without_height_resets_the_height_of_the_previous_one() {
let mut s = session();
execute(&mut s, "tool.material", &json!({"material": "copper_hammered"})).unwrap();
assert!(s.tool.values[&Channel::Height][0] < 0.0);
execute(&mut s, "tool.material", &json!({"material": "copper"})).unwrap();
assert_eq!(s.tool.values[&Channel::Height], Channel::Height.default_value());
}
#[test]
fn a_smart_material_or_an_unknown_one_cannot_be_the_brush_material() {
let mut s = session();
let before = s.tool.values.clone();
for id in ["iron_rusted", "nope"] {
assert!(execute(&mut s, "tool.material", &json!({"material": id})).is_err(), "{id}");
}
assert_eq!(s.tool.values, before);
}
/// Texel of the sphere point under screen position `(x, y)`
fn texel(s: &Session, x: f32, y: f32) -> (u32, u32) {
let hit = s.pick(Vec2::new(x, y), s.viewport).unwrap();
((hit.uv.x * 256.0) as u32, (hit.uv.y * 256.0) as u32)
}
/// A session with `material` as the brush material, brush `size` (0..100), the stroke along y = 200 over `xs`
fn painted(material: &str, size: u32, xs: [f32; 2]) -> Session {
let mut s = session();
paint(&mut s, material, size, xs);
s
}
fn paint(s: &mut Session, material: &str, size: u32, xs: [f32; 2]) {
execute(s, "tool.material", &json!({"material": material})).unwrap();
execute(s, "tool.brush", &json!({"size": size, "hardness": 100})).unwrap();
execute(s, "tool.stroke", &json!({"points": [[xs[0], 200], [xs[1], 200]]})).unwrap();
s.update();
}
/// What a fill layer of `material` (projection scale `scale`) shows over the sphere
fn fill_of(material: &str, scale: f32) -> Session {
let mut s = session();
let layer = LayerId(execute(&mut s, "material.apply", &json!({"material": material})).unwrap()["layer"].as_u64().unwrap());
execute(&mut s, "layer.fill.projection", &json!({"layer": layer.0, "projection": "triplanar", "scale": scale})).unwrap();
s.update();
s
}
fn at(s: &Session, channel: Channel, (x, y): (u32, u32)) -> f32 {
s.caches[0].composite.value(channel, x, y)[0]
}
#[test]
fn a_stroke_after_picking_a_material_paints_its_pattern_like_a_fill_of_it() {
// Brush size 40 is the pattern's natural size: the same as a fill layer with the material
let (stroke, fill) = (painted("cobblestone", 40, [150.0, 250.0]), fill_of("cobblestone", 1.0));
let samples: Vec<f32> = (0..24).map(|i| 170.0 + 3.0 * i as f32).collect();
let mut colours = Vec::new();
for x in samples {
let texel = texel(&stroke, x, 200.0);
for channel in [Channel::BaseColor, Channel::Roughness, Channel::Height] {
let (painted, expected) = (at(&stroke, channel, texel), at(&fill, channel, texel));
assert!((painted - expected).abs() < 0.02, "{channel:?} at x = {x}: {painted} vs {expected}");
}
colours.push(at(&stroke, Channel::BaseColor, texel));
}
let (low, high) = colours.iter().fold((f32::MAX, f32::MIN), |(low, high), v| (low.min(*v), high.max(*v)));
assert!(high - low > 0.05, "the colour varies along the stroke: {colours:?}");
}
#[test]
fn overlapping_strokes_agree_where_they_overlap() {
let mut s = painted("cobblestone", 40, [150.0, 215.0]);
let samples: Vec<(u32, u32)> = (0..8).map(|i| texel(&s, 190.0 + 3.0 * i as f32, 200.0)).collect();
let first: Vec<f32> = samples.iter().map(|t| at(&s, Channel::BaseColor, *t)).collect();
paint(&mut s, "cobblestone", 40, [185.0, 250.0]);
for (i, t) in samples.iter().enumerate() {
assert!((at(&s, Channel::BaseColor, *t) - first[i]).abs() < 0.005, "sample {i}");
}
}
#[test]
fn the_pattern_follows_the_brush_size() {
// A quarter of the natural brush size is a pattern four times as fine
let (stroke, fill) = (painted("cobblestone", 10, [194.0, 206.0]), fill_of("cobblestone", 4.0));
let natural = fill_of("cobblestone", 1.0);
let (mut fine, mut coarse) = (0.0_f32, 0.0_f32);
for x in [197.0, 199.0, 201.0, 203.0] {
let texel = texel(&stroke, x, 200.0);
let painted = at(&stroke, Channel::BaseColor, texel);
fine = fine.max((painted - at(&fill, Channel::BaseColor, texel)).abs());
coarse = coarse.max((painted - at(&natural, Channel::BaseColor, texel)).abs());
}
assert!(fine < 0.02, "matches the pattern at 4x: {fine}");
assert!(coarse > 0.02, "differs from the natural size: {coarse}");
}
#[test]
fn editing_a_brush_value_ends_the_pattern() {
let mut s = session();
execute(&mut s, "tool.material", &json!({"material": "cobblestone"})).unwrap();
assert_eq!(s.tool.material.as_deref(), Some("cobblestone"));
execute(&mut s, "tool.material", &json!({"channel": "baseColor", "color": [1.0, 0.0, 0.0]})).unwrap();
assert_eq!(s.tool.material, None);
}
/// Add copper with `place` params (above, below, top, index)
fn apply(s: &mut Session, place: Value) -> LayerId {
let mut params = json!({"material": "copper"});
params.as_object_mut().unwrap().extend(place.as_object().unwrap().clone());
LayerId(execute(s, "material.apply", &params).unwrap()["layer"].as_u64().unwrap())
}
#[test]
fn a_material_dropped_on_a_row_goes_directly_below_it_and_one_dropped_on_the_view_goes_on_top() {
let mut s = session();
let paint = stack(&s)[0];
let upper = apply(&mut s, json!({}));
let lower = apply(&mut s, json!({"index": 0}));
assert_eq!(stack(&s), vec![lower, paint, upper]);
let below_paint = apply(&mut s, json!({"below": paint.0}));
assert_eq!(stack(&s), vec![lower, below_paint, paint, upper]);
let below_bottom = apply(&mut s, json!({"below": lower.0}));
assert_eq!(stack(&s)[0], below_bottom, "below the bottom row is the bottom");
s.selected.insert(0, lower);
let top = apply(&mut s, json!({"top": true}));
assert_eq!(stack(&s).last(), Some(&top), "the top, wherever the selection is");
assert_eq!(s.selected_layer(), Some(top));
s.doc.project.validate().unwrap();
}
+110
View File
@@ -0,0 +1,110 @@
//! Frame texture set (Shift+F) and Show entire mesh (F): a floor plane must not decide the camera
use serde_json::{Value, json};
use texturecraft_engine::geom::glam::Vec3;
use texturecraft_engine::{Session, execute};
/// A small "Hydrant" (set 0) near the origin and a huge "Floor" (set 1) below and around it
const SCENE_OBJ: &str = "o Hydrant\nusemtl Hydrant\nv 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\
o Floor\nusemtl Floor\nv -100 -1 -100\nv 100 -1 -100\nv 0 -1 100\nvt 0 0\nvt 1 0\nvt 0 1\nf 4/4 5/5 6/6\n";
fn scene() -> Session {
let session = Session::from_mesh_bytes("scene.obj", SCENE_OBJ.as_bytes(), 256, "scene").unwrap();
let sets: Vec<_> = session.doc.project.texture_sets.iter().map(|set| session.mesh.materials[set.material].as_str()).collect();
assert_eq!(sets, ["Hydrant", "Floor"], "the sets follow the parts");
session
}
fn target(session: &Session) -> Vec3 {
session.camera.target
}
fn near(a: Vec3, b: Vec3) -> bool {
(a - b).length() < 1e-4
}
#[test]
fn frame_texture_set_frames_only_the_active_set() {
let mut session = scene();
let all = session.camera.distance;
execute(&mut session, "viewport.frameSelection", &Value::Null).unwrap();
assert!(near(target(&session), Vec3::new(0.5, 0.5, 0.0)), "the camera looks at the hydrant, not the floor: {:?}", target(&session));
assert!(session.camera.distance < all * 0.05, "the hydrant is about 1 unit across, the whole scene about 280: {} vs {all}", session.camera.distance);
}
#[test]
fn frame_texture_set_follows_the_selected_set() {
let mut session = scene();
execute(&mut session, "textureSet.select", &json!({"ts": 1})).unwrap();
execute(&mut session, "viewport.frameSelection", &Value::Null).unwrap();
assert!(near(target(&session), Vec3::new(0.0, -1.0, 0.0)), "{:?}", target(&session));
assert!(session.camera.distance > 100.0, "the floor is wide: {}", session.camera.distance);
}
#[test]
fn orbit_turns_around_the_framed_center() {
let mut session = scene();
execute(&mut session, "viewport.frameSelection", &Value::Null).unwrap();
let (center, distance) = (target(&session), session.camera.distance);
for (dx, dy) in [(90.0, 0.0), (0.0, 30.0), (-45.0, -10.0)] {
execute(&mut session, "camera.orbit", &json!({"dx": dx, "dy": dy})).unwrap();
assert!(near(target(&session), center), "orbiting keeps the pivot");
assert!(((session.camera.eye() - center).length() - distance).abs() < 1e-3, "and the eye stays that far from the framed center");
}
}
#[test]
fn show_entire_mesh_restores_the_whole_scene() {
let mut session = scene();
let whole = (target(&session), session.camera.distance);
execute(&mut session, "viewport.frameSelection", &Value::Null).unwrap();
assert!(!near(target(&session), whole.0));
execute(&mut session, "viewport.frame", &Value::Null).unwrap();
assert!(near(target(&session), whole.0), "{:?}", target(&session));
assert!((session.camera.distance - whole.1).abs() < 1e-3);
}
#[test]
fn viewport_frame_takes_a_target() {
let mut session = scene();
let whole = session.camera.distance;
let selection = execute(&mut session, "viewport.frame", &json!({"target": "selection"})).unwrap();
assert!(session.camera.distance < whole * 0.05);
assert_eq!(selection["target"], json!([0.5, 0.5, 0.0]));
execute(&mut session, "viewport.frame", &json!({"target": "all"})).unwrap();
assert!((session.camera.distance - whole).abs() < 1e-3);
assert!(execute(&mut session, "viewport.frame", &json!({"target": "floor"})).is_err());
}
#[test]
fn a_set_without_triangles_frames_the_whole_mesh() {
let mut session = scene();
let whole = (target(&session), session.camera.distance);
session.doc.project.texture_sets[0].material = 7;
execute(&mut session, "viewport.frameSelection", &Value::Null).unwrap();
assert!(near(target(&session), whole.0) && (session.camera.distance - whole.1).abs() < 1e-3);
}
#[test]
fn a_saved_overview_camera_is_restored_after_framing_a_set() {
let mut session = scene();
execute(&mut session, "camera.add", &json!({"name": "Overview"})).unwrap();
let overview = session.camera.distance;
execute(&mut session, "viewport.frameSelection", &Value::Null).unwrap();
execute(&mut session, "camera.select", &json!({"name": "Overview"})).unwrap();
assert!((session.camera.distance - overview).abs() < 1e-3, "{} vs {overview}", session.camera.distance);
}
+223
View File
@@ -0,0 +1,223 @@
//! Gradient maps on a fill's base color: color stops for a procedural or an anchor point,
//! through `layer.fill.set {colors}`, undo, inspect and a project round trip.
use serde_json::{Value, json};
use texturecraft_engine::core::{Channel, LayerId, LayerKind, Source};
use texturecraft_engine::geom::primitives;
use texturecraft_engine::{Session, execute};
fn session() -> Session {
let mut s = Session::new_project("t", primitives::sphere(1.0, 48, 24), "builtin:sphere", None, 256).unwrap();
s.viewport = texturecraft_engine::geom::glam::Vec2::new(400.0, 400.0);
s.camera.yaw = 0.0;
s.camera.pitch = 0.0;
s.update();
s
}
/// Composited value of `c` under the viewport center.
fn center(s: &mut Session, c: Channel) -> [f32; 3] {
s.update();
let hit = s.pick(texturecraft_engine::geom::glam::Vec2::new(200.0, 200.0), s.viewport).unwrap();
s.caches[0].composite.value(c, (hit.uv.x * 256.0) as u32, (hit.uv.y * 256.0) as u32)
}
fn close(a: [f32; 3], b: [f32; 3]) -> bool {
(0..3).all(|i| (a[i] - b[i]).abs() < 2e-3)
}
fn id(v: Value, key: &str) -> u64 {
v[key].as_u64().unwrap()
}
/// The stops on `layer`'s base color source.
fn ramp(s: &Session, layer: u64) -> Vec<[f32; 3]> {
match &s.doc.project.layer(LayerId(layer)).unwrap().kind {
LayerKind::Fill(fill) => fill.source(Channel::BaseColor).ramp().to_vec(),
_ => panic!("not a fill layer"),
}
}
const RGB: [[f32; 3]; 3] = [[1.0, 0.0, 0.0], [0.0, 1.0, 0.0], [0.0, 0.0, 1.0]];
#[test]
fn an_anchor_gradient_map_recolors_the_gray_below_and_undoes() {
let mut s = session();
execute(&mut s, "layer.add.fill", &json!({"color": [0.5, 0.5, 0.5]})).unwrap();
let anchor = id(execute(&mut s, "effect.add.anchor", &json!({})).unwrap(), "effect");
let top = id(execute(&mut s, "layer.add.fill", &json!({"color": [1.0, 1.0, 1.0], "roughness": 0.3, "metallic": 0.6})).unwrap(), "layer");
execute(&mut s, "layer.fill.set", &json!({"layer": top, "channel": "baseColor", "anchor": anchor})).unwrap();
assert!(close(center(&mut s, Channel::BaseColor), [0.5; 3]), "{:?}", center(&mut s, Channel::BaseColor));
// Mid gray picks the middle stop; the other channels keep their values
execute(&mut s, "layer.fill.set", &json!({"layer": top, "channel": "baseColor", "colors": RGB})).unwrap();
assert!(close(center(&mut s, Channel::BaseColor), [0.0, 1.0, 0.0]), "{:?}", center(&mut s, Channel::BaseColor));
assert!(close(center(&mut s, Channel::Roughness), [0.3; 3]));
assert!(close(center(&mut s, Channel::Metallic), [0.6; 3]));
let inspect = execute(&mut s, "project.inspect", &Value::Null).unwrap();
let row = inspect["layers"].as_array().unwrap().iter().find(|l| l["id"] == top).unwrap().clone();
assert_eq!(row["fill"]["sources"]["baseColor"]["colors"], json!(RGB), "{row}");
// One undo step each way
execute(&mut s, "edit.undo", &Value::Null).unwrap();
assert!(ramp(&s, top).is_empty());
assert!(close(center(&mut s, Channel::BaseColor), [0.5; 3]));
execute(&mut s, "edit.redo", &Value::Null).unwrap();
assert_eq!(ramp(&s, top), RGB.to_vec());
assert!(close(center(&mut s, Channel::BaseColor), [0.0, 1.0, 0.0]));
// Picking the anchor again keeps the stops; hex colors work; an empty list removes them
execute(&mut s, "layer.fill.set", &json!({"layer": top, "channel": "baseColor", "colors": ["#000000", "#ff0000"]})).unwrap();
execute(&mut s, "layer.fill.set", &json!({"layer": top, "channel": "baseColor", "anchor": anchor})).unwrap();
assert!(close(center(&mut s, Channel::BaseColor), [0.5, 0.0, 0.0]), "{:?}", center(&mut s, Channel::BaseColor));
execute(&mut s, "layer.fill.set", &json!({"layer": top, "channel": "baseColor", "colors": []})).unwrap();
assert!(ramp(&s, top).is_empty());
assert!(close(center(&mut s, Channel::BaseColor), [0.5; 3]));
}
#[test]
fn a_procedural_gradient_map_saves_and_loads() {
let mut s = session();
let layer = id(execute(&mut s, "layer.add.fill", &json!({"color": [1.0, 1.0, 1.0], "roughness": 0.4})).unwrap(), "layer");
execute(&mut s, "layer.fill.set", &json!({"layer": layer, "channel": "baseColor", "procedural": "Checker", "low": [0.2, 0.2, 0.2], "high": [0.8, 0.8, 0.8], "colors": [[1, 0, 0], [0, 0, 1]]})).unwrap();
let value = center(&mut s, Channel::BaseColor);
assert!(close(value, [1.0, 0.0, 0.0]) || close(value, [0.0, 0.0, 1.0]), "a stop, not low or high: {value:?}");
assert!(close(center(&mut s, Channel::Roughness), [0.4; 3]));
// Changing the pattern's settings without `colors` (as its sliders do) keeps the stops
execute(
&mut s,
"layer.fill.set",
&json!({"layer": layer, "channel": "baseColor", "procedural": "Checker", "scale": 8.0, "low": [0.2, 0.2, 0.2], "high": [0.8, 0.8, 0.8]}),
)
.unwrap();
assert_eq!(ramp(&s, layer), vec![[1.0, 0.0, 0.0], [0.0, 0.0, 1.0]]);
let back = Session::from_project_bytes(&s.to_project_bytes().unwrap()).unwrap();
assert_eq!(back.doc.project, s.doc.project);
assert_eq!(ramp(&back, layer), vec![[1.0, 0.0, 0.0], [0.0, 0.0, 1.0]]);
match &back.doc.project.layer(LayerId(layer)).unwrap().kind {
LayerKind::Fill(fill) => assert!(matches!(fill.source(Channel::BaseColor), Source::Procedural { .. })),
_ => panic!("not a fill layer"),
}
}
#[test]
fn gradient_map_colors_are_refused_where_they_cannot_apply() {
let mut s = session();
let layer = id(execute(&mut s, "layer.add.fill", &json!({"color": [1.0, 1.0, 1.0], "roughness": 0.4})).unwrap(), "layer");
let set = |s: &mut Session, extra: Value| {
let mut p = json!({"layer": layer});
for (k, v) in extra.as_object().unwrap() {
p[k] = v.clone();
}
execute(s, "layer.fill.set", &p)
};
assert!(set(&mut s, json!({"channel": "baseColor", "colors": RGB})).is_err(), "a uniform color has no gray to map");
assert!(set(&mut s, json!({"channel": "roughness", "procedural": "Clouds", "colors": RGB})).is_err(), "only color channels");
assert!(set(&mut s, json!({"channel": "baseColor", "procedural": "Clouds", "colors": vec![[0.5; 3]; 17]})).is_err(), "at most 16 stops");
assert!(set(&mut s, json!({"channel": "baseColor", "procedural": "Clouds", "colors": ["red"]})).is_err());
assert!(ramp(&s, layer).is_empty(), "a refused edit changes nothing");
// Removing stops where there are none (a uniform color) changes nothing either
let before = s.doc.project.clone();
set(&mut s, json!({"channel": "baseColor", "colors": []})).unwrap();
assert_eq!(s.doc.project, before);
set(&mut s, json!({"channel": "baseColor", "procedural": "Clouds", "colors": [[2.0, -1.0, 0.5]]})).unwrap();
assert_eq!(ramp(&s, layer), vec![[1.0, 0.0, 0.5]], "stops clamp to 0..1");
}
#[test]
fn a_scalar_channel_drops_stuck_stops_when_its_source_is_set() {
let mut s = session();
let layer = id(execute(&mut s, "layer.add.fill", &json!({"roughness": 0.4})).unwrap(), "layer");
// Replacing a scalar source must discard color stops hidden by the panel
let stuck = |s: &mut Session| {
let LayerKind::Fill(fill) = &mut s.doc.project.layer_mut(LayerId(layer)).unwrap().kind else { panic!("not a fill layer") };
let pattern = texturecraft_engine::core::Procedural::new(texturecraft_engine::core::ProceduralKind::Clouds);
fill.sources.insert(Channel::Roughness, Source::Procedural { pattern, low: [0.0; 3], high: [1.0; 3], ramp: RGB.to_vec() });
};
let roughness_ramp = |s: &Session| match &s.doc.project.layer(LayerId(layer)).unwrap().kind {
LayerKind::Fill(fill) => fill.source(Channel::Roughness).ramp().to_vec(),
_ => panic!("not a fill layer"),
};
stuck(&mut s);
execute(&mut s, "layer.fill.set", &json!({"layer": layer, "channel": "roughness", "procedural": "Clouds", "scale": 8.0})).unwrap();
assert!(roughness_ramp(&s).is_empty(), "a new pattern on roughness keeps no stops");
stuck(&mut s);
execute(&mut s, "layer.fill.set", &json!({"layer": layer, "channel": "roughness", "colors": []})).unwrap();
assert!(roughness_ramp(&s).is_empty(), "`colors: []` removes them");
}
#[test]
fn removing_stops_from_an_absent_channel_adds_no_channel() {
let mut s = session();
// A content fill effect that supplies only roughness: a default gray base color would cover the layer
let effect = id(execute(&mut s, "effect.add.fill", &json!({"target": "content", "roughness": 0.7})).unwrap(), "effect");
let before = s.doc.project.clone();
execute(&mut s, "layer.fill.set", &json!({"effect": effect, "channel": "baseColor", "colors": []})).unwrap();
assert_eq!(s.doc.project, before, "no base color source appears on the effect");
// The same on a fill layer that has no base color channel
let layer = id(execute(&mut s, "layer.add.fill", &json!({"roughness": 0.4})).unwrap(), "layer");
let before = s.doc.project.clone();
execute(&mut s, "layer.fill.set", &json!({"layer": layer, "channel": "baseColor", "colors": []})).unwrap();
assert_eq!(s.doc.project, before, "no base color channel appears on the layer");
// Turning the channel on still adds it
execute(&mut s, "layer.fill.set", &json!({"effect": effect, "channel": "baseColor", "enabled": true})).unwrap();
let (_, x) = s.doc.project.effect(texturecraft_engine::core::LayerId(effect)).unwrap();
match &x.kind {
texturecraft_engine::core::EffectKind::Material(f) => assert!(f.sources.contains_key(&Channel::BaseColor), "enabled adds the channel"),
_ => panic!("not a content fill effect"),
}
}
#[test]
fn gradient_map_true_starts_the_stops_from_the_current_source() {
let mut s = session();
let layer = id(execute(&mut s, "layer.add.fill", &json!({})).unwrap(), "layer");
let set = |s: &mut Session, p: Value| {
let mut p = p;
p["layer"] = json!(layer);
p["channel"] = json!("baseColor");
execute(s, "layer.fill.set", &p)
};
// A uniform color has nothing to start from
assert!(set(&mut s, json!({"gradientMap": true})).is_err());
// A procedural starts at low, halfway and high, so its look holds
set(&mut s, json!({"procedural": "Clouds", "low": [0.0, 0.25, 0.5], "high": [1.0, 0.75, 0.5]})).unwrap();
set(&mut s, json!({"gradientMap": true})).unwrap();
assert_eq!(ramp(&s, layer), vec![[0.0, 0.25, 0.5], [0.5; 3], [1.0, 0.75, 0.5]]);
// Stops already there stay
set(&mut s, json!({"colors": RGB})).unwrap();
set(&mut s, json!({"gradientMap": true})).unwrap();
assert_eq!(ramp(&s, layer), RGB.to_vec());
// Set together with a new pattern, the stops stay
set(&mut s, json!({"procedural": "Voronoi", "gradientMap": true})).unwrap();
assert_eq!(ramp(&s, layer), RGB.to_vec());
// It cannot go with `colors`, and it undoes in one step
assert!(set(&mut s, json!({"gradientMap": true, "colors": RGB})).is_err());
set(&mut s, json!({"colors": []})).unwrap();
set(&mut s, json!({"gradientMap": true})).unwrap();
execute(&mut s, "edit.undo", &Value::Null).unwrap();
assert!(ramp(&s, layer).is_empty());
// An anchor starts at black, gray and white
execute(&mut s, "layer.add.fill", &json!({})).unwrap();
let anchor = id(execute(&mut s, "effect.add.anchor", &json!({})).unwrap(), "effect");
let top = id(execute(&mut s, "layer.add.fill", &json!({})).unwrap(), "layer");
execute(&mut s, "layer.fill.set", &json!({"layer": top, "channel": "baseColor", "anchor": anchor})).unwrap();
execute(&mut s, "layer.fill.set", &json!({"layer": top, "channel": "baseColor", "gradientMap": true})).unwrap();
assert_eq!(ramp(&s, top), vec![[0.0; 3], [0.5; 3], [1.0; 3]]);
// A scalar channel has no stops
assert!(execute(&mut s, "layer.fill.set", &json!({"layer": top, "channel": "roughness", "gradientMap": true})).is_err());
}
@@ -0,0 +1,525 @@
//! Several selected layers, as in the reference app: Shift+click selects a range of rows,
//! Ctrl/Cmd+click adds or takes out one layer, and remove, duplicate, group, visibility and move
//! act on every selected layer in one undo step.
use serde_json::{Value, json};
use texturecraft_engine::core::{LayerId, LayerKind};
use texturecraft_engine::geom::primitives;
use texturecraft_engine::layer_selection::stack_rows;
use texturecraft_engine::{Session, execute};
fn session() -> Session {
Session::new_project("t", primitives::material_ball(), "builtin:material_ball", None, 256).unwrap()
}
fn id(v: Value, key: &str) -> LayerId {
LayerId(v[key].as_u64().unwrap())
}
fn add(s: &mut Session, name: &str) -> LayerId {
id(execute(s, "layer.add.paint", &json!({ "name": name })).unwrap(), "layer")
}
/// Paint layers A (bottom) to D (top) on texture set 0, D selected.
fn four(s: &mut Session) -> [LayerId; 4] {
execute(s, "textureSet.select", &json!({"ts": 0})).unwrap();
[add(s, "A"), add(s, "B"), add(s, "C"), add(s, "D")]
}
/// The names of set 0's rows from the top (folder contents included).
fn rows(s: &Session) -> Vec<String> {
stack_rows(&s.doc.project, 0, false).iter().map(|id| s.doc.project.layer(*id).unwrap().name.clone()).collect()
}
fn names(s: &Session, ids: &[LayerId]) -> Vec<String> {
ids.iter().map(|id| s.doc.project.layer(*id).unwrap().name.clone()).collect()
}
fn selected(s: &Session) -> Vec<String> {
names(s, &s.selected_layers())
}
fn click(s: &mut Session, layer: LayerId, how: &str) {
let params = match how {
"shift" => json!({"layer": layer.0, "range": true}),
"ctrl" => json!({"layer": layer.0, "toggle": true}),
_ => json!({"layer": layer.0}),
};
execute(s, "layer.select", &params).unwrap();
}
#[test]
fn shift_click_selects_the_rows_from_the_last_clicked_layer() {
let mut s = session();
let [a, b, _, d] = four(&mut s);
click(&mut s, b, "plain");
click(&mut s, d, "shift");
assert_eq!(selected(&s), ["D", "C", "B"]);
assert_eq!(s.selected_layer(), Some(d), "the clicked layer is the active one");
// The range still starts at B, not at the active D
click(&mut s, a, "shift");
assert_eq!(selected(&s), ["B", "A"]);
assert_eq!(s.selected_layer(), Some(a));
assert_eq!(texturecraft_engine::inspect::session(&s)["selectedLayers"], json!([b.0, a.0]));
// A plain click selects one layer again
click(&mut s, d, "plain");
assert_eq!(selected(&s), ["D"]);
}
#[test]
fn ctrl_click_adds_and_takes_out_one_layer() {
let mut s = session();
let [a, _, c, _] = four(&mut s);
click(&mut s, a, "plain");
click(&mut s, c, "ctrl");
assert_eq!(selected(&s), ["C", "A"]);
assert_eq!(s.selected_layer(), Some(c));
click(&mut s, c, "ctrl");
assert_eq!(selected(&s), ["A"], "a second Ctrl+click takes the layer out");
assert_eq!(s.selected_layer(), Some(a), "the remaining layer becomes the active one");
click(&mut s, a, "ctrl");
assert!(selected(&s).is_empty(), "Ctrl+click on the only selected layer leaves an empty selection");
assert_eq!(s.selected_layer(), None);
// The next Shift+click has no anchor and starts over at the clicked layer
click(&mut s, c, "shift");
assert_eq!(selected(&s), ["C"]);
click(&mut s, a, "ctrl");
assert_eq!(selected(&s), ["C", "A"]);
}
#[test]
fn ctrl_click_on_another_selected_layer_keeps_the_active_one_and_the_range_start() {
let mut s = session();
let [a, b, c, d] = four(&mut s);
click(&mut s, b, "plain");
click(&mut s, d, "shift");
click(&mut s, c, "ctrl");
assert_eq!(selected(&s), ["D", "B"]);
assert_eq!(s.selected_layer(), Some(d), "D stays the active layer");
click(&mut s, a, "shift");
assert_eq!(selected(&s), ["B", "A"], "the range still starts at B");
}
#[test]
fn a_range_covers_the_shown_rows_only() {
let mut s = session();
let [a, b, c, d] = four(&mut s);
execute(&mut s, "layer.select", &json!({"layers": [b.0, c.0]})).unwrap();
let folder = id(execute(&mut s, "layer.group", &Value::Null).unwrap(), "layer");
assert_eq!(rows(&s)[..5], ["D", "Folder 1", "C", "B", "A"]);
click(&mut s, d, "plain");
click(&mut s, a, "shift");
assert_eq!(selected(&s), ["D", "Folder 1", "C", "B", "A"], "an open folder's layers are in the range");
if let LayerKind::Group { collapsed, .. } = &mut s.doc.project.layer_mut(folder).unwrap().kind {
*collapsed = true;
}
click(&mut s, d, "plain");
click(&mut s, a, "shift");
assert_eq!(selected(&s), ["D", "Folder 1", "A"], "a collapsed folder's layers are not");
}
#[test]
fn another_selected_layer_ends_the_multiple_selection() {
let mut s = session();
let [a, _, c, _] = four(&mut s);
click(&mut s, a, "plain");
click(&mut s, c, "ctrl");
add(&mut s, "E");
assert_eq!(selected(&s), ["E"], "a new layer is selected alone");
}
#[test]
fn delete_removes_every_selected_layer_in_one_undo_step() {
let mut s = session();
let [a, b, _, d] = four(&mut s);
execute(&mut s, "layer.select", &json!({"layers": [b.0, d.0]})).unwrap();
let depth = s.history_labels().len();
let r = execute(&mut s, "layer.remove", &Value::Null).unwrap();
assert_eq!(r["removed"], json!([d.0, b.0]));
assert_eq!(rows(&s)[..2], ["C", "A"]);
assert_eq!(selected(&s), ["A"], "the layer under the lowest removed one is selected");
assert_eq!(s.selected_layer(), Some(a));
assert_eq!(s.history_labels().len(), depth + 1, "one undo step");
s.undo().unwrap();
assert_eq!(rows(&s)[..4], ["D", "C", "B", "A"]);
}
#[test]
fn a_folder_and_its_own_layer_selected_remove_together() {
let mut s = session();
let [a, b, _, _] = four(&mut s);
let folder = id(execute(&mut s, "layer.group", &json!({"layer": b.0})).unwrap(), "layer");
execute(&mut s, "layer.select", &json!({"layers": [folder.0, b.0, a.0]})).unwrap();
execute(&mut s, "layer.remove", &Value::Null).unwrap();
assert_eq!(rows(&s)[..2], ["D", "C"]);
assert!(s.doc.project.layer(b).is_err() && s.doc.project.layer(a).is_err());
}
#[test]
fn duplicate_puts_the_copies_in_one_block_above_the_topmost_selected_layer() {
let mut s = session();
let [_, b, _, d] = four(&mut s);
execute(&mut s, "layer.select", &json!({"layers": [d.0, b.0], "layer": b.0})).unwrap();
execute(&mut s, "layer.duplicate", &Value::Null).unwrap();
assert_eq!(rows(&s)[..6], ["D copy", "B copy", "D", "C", "B", "A"], "the block sits directly above D, in stack order");
assert_eq!(selected(&s), ["D copy", "B copy"], "the copies are selected");
assert_eq!(names(&s, &[s.selected_layer().unwrap()]), ["B copy"], "the active layer's copy is the active one");
s.undo().unwrap();
assert_eq!(rows(&s)[..4], ["D", "C", "B", "A"]);
}
#[test]
fn duplicate_block_lands_at_the_topmost_layers_level_also_for_a_layer_from_a_folder() {
let mut s = session();
let [a, _, c, _] = four(&mut s);
let folder = id(execute(&mut s, "layer.add.group", &Value::Null).unwrap(), "layer");
execute(&mut s, "layer.move", &json!({"layers": [a.0], "above": folder.0, "inside": true})).unwrap();
assert_eq!(rows(&s)[..5], ["Folder 1", "A", "D", "C", "B"]);
// The topmost selected row is A, inside the folder, so the block goes there
execute(&mut s, "layer.select", &json!({"layers": [c.0, a.0]})).unwrap();
execute(&mut s, "layer.duplicate", &Value::Null).unwrap();
assert_eq!(rows(&s)[..7], ["Folder 1", "A copy", "C copy", "A", "D", "C", "B"]);
assert_eq!(selected(&s), ["A copy", "C copy"], "the copies are the selection");
}
#[test]
fn duplicate_of_a_root_layer_and_a_folder_layer_with_the_root_one_higher() {
let mut s = session();
let [a, b, _, d] = four(&mut s);
let folder = id(execute(&mut s, "layer.add.group", &Value::Null).unwrap(), "layer");
execute(&mut s, "layer.move", &json!({"layers": [a.0], "above": folder.0, "inside": true})).unwrap();
execute(&mut s, "layer.move", &json!({"layers": [folder.0], "above": b.0})).unwrap();
// Rows from the top: D, C, Folder 1 (A), B... select D (root, topmost) and A (in the folder)
assert_eq!(rows(&s)[..5], ["D", "C", "Folder 1", "A", "B"]);
execute(&mut s, "layer.select", &json!({"layers": [d.0, a.0]})).unwrap();
execute(&mut s, "layer.duplicate", &Value::Null).unwrap();
assert_eq!(rows(&s)[..4], ["D copy", "A copy", "D", "C"], "the block is at the root, above D");
}
#[test]
fn group_puts_the_selected_layers_into_one_folder_in_their_order() {
let mut s = session();
let [a, _, c, _] = four(&mut s);
execute(&mut s, "layer.select", &json!({"layers": [a.0, c.0]})).unwrap();
let folder = id(execute(&mut s, "layer.group", &Value::Null).unwrap(), "layer");
assert_eq!(rows(&s)[..5], ["D", "Folder 1", "C", "A", "B"], "the folder takes the top layer's place");
assert_eq!(s.doc.project.layer(folder).unwrap().children(), [a, c], "bottom to top inside the folder");
assert_eq!(s.selected_layers(), [folder]);
s.undo().unwrap();
assert_eq!(rows(&s)[..4], ["D", "C", "B", "A"]);
}
#[test]
fn group_puts_the_folder_at_the_topmost_selected_layer_with_gaps_between() {
let mut s = session();
execute(&mut s, "textureSet.select", &json!({"ts": 0})).unwrap();
let [l1, l2, l3, l4, l5] = ["L1", "L2", "L3", "L4", "L5"].map(|n| add(&mut s, n));
execute(&mut s, "layer.select", &json!({"layers": [l2.0, l4.0]})).unwrap();
let folder = id(execute(&mut s, "layer.group", &Value::Null).unwrap(), "layer");
assert_eq!(rows(&s)[..6], ["L5", "Folder 1", "L4", "L2", "L3", "L1"], "the folder sits where L4 was, L3 stays below it");
assert_eq!(s.doc.project.layer(folder).unwrap().children(), [l2, l4], "L2 stays below L4 inside");
let stack = &s.doc.project.texture_sets[0].stack;
assert_eq!(stack[stack.len() - 4..], [l1, l3, folder, l5], "L5 stays above the folder");
// Same result when the layers are picked in the other order
s.undo().unwrap();
execute(&mut s, "layer.select", &json!({"layers": [l4.0, l2.0]})).unwrap();
execute(&mut s, "layer.group", &Value::Null).unwrap();
assert_eq!(rows(&s)[..6], ["L5", "Folder 1", "L4", "L2", "L3", "L1"]);
}
#[test]
fn group_of_a_layer_inside_a_folder_and_one_outside_keeps_the_topmost_place() {
let mut s = session();
execute(&mut s, "textureSet.select", &json!({"ts": 0})).unwrap();
let [x, y, z] = ["X", "Y", "Z"].map(|n| add(&mut s, n));
let outer = id(execute(&mut s, "layer.add.group", &Value::Null).unwrap(), "layer");
execute(&mut s, "layer.move", &json!({"layers": [y.0, z.0], "above": outer.0, "inside": true})).unwrap();
// Rows from the top: Folder 1 (Z, Y), X
assert_eq!(rows(&s)[..4], ["Folder 1", "Z", "Y", "X"]);
// The topmost selected layer Z is inside the folder: the new folder replaces it there
execute(&mut s, "layer.select", &json!({"layers": [z.0, x.0]})).unwrap();
let folder = id(execute(&mut s, "layer.group", &Value::Null).unwrap(), "layer");
assert_eq!(rows(&s)[..5], ["Folder 1", "Folder 2", "Z", "X", "Y"]);
assert_eq!(s.doc.project.layer(outer).unwrap().children(), [y, folder], "Z's place in the outer folder");
assert_eq!(s.doc.project.layer(folder).unwrap().children(), [x, z], "X keeps its place below Z");
s.undo().unwrap();
assert_eq!(rows(&s)[..4], ["Folder 1", "Z", "Y", "X"]);
// X is outside and Y inside: Y is the topmost, so the folder appears inside the outer folder
execute(&mut s, "layer.select", &json!({"layers": [x.0, y.0]})).unwrap();
let folder = id(execute(&mut s, "layer.group", &Value::Null).unwrap(), "layer");
assert_eq!(rows(&s)[..5], ["Folder 1", "Z", "Folder 2", "Y", "X"]);
assert_eq!(s.doc.project.texture_sets[0].stack.last(), Some(&outer), "the outer folder stays on top");
assert_eq!(s.doc.project.layer(outer).unwrap().children(), [folder, z]);
assert_eq!(s.doc.project.layer(folder).unwrap().children(), [x, y]);
}
#[test]
fn group_with_the_topmost_layer_at_the_root_takes_the_folder_layer_out_of_its_folder() {
let mut s = session();
execute(&mut s, "textureSet.select", &json!({"ts": 0})).unwrap();
let [_x, fa, fb] = ["X", "Fill A", "Fill B"].map(|n| add(&mut s, n));
let outer = id(execute(&mut s, "layer.add.group", &Value::Null).unwrap(), "layer");
execute(&mut s, "layer.move", &json!({"layers": [fa.0, fb.0], "above": outer.0, "inside": true})).unwrap();
// Folder 1 (Fill B, Fill A) at the root above X; add Fill 3 above the folder
let f3 = add(&mut s, "Fill 3");
execute(&mut s, "layer.move", &json!({"layers": [f3.0], "above": outer.0})).unwrap();
assert_eq!(rows(&s)[..5], ["Fill 3", "Folder 1", "Fill B", "Fill A", "X"]);
execute(&mut s, "layer.select", &json!({"layers": [f3.0, fa.0]})).unwrap();
let folder = id(execute(&mut s, "layer.group", &Value::Null).unwrap(), "layer");
assert_eq!(rows(&s)[..6], ["Folder 2", "Fill 3", "Fill A", "Folder 1", "Fill B", "X"], "the new folder is at the root slot of Fill 3");
assert_eq!(s.doc.project.layer(folder).unwrap().children(), [fa, f3], "stack order inside: the folder's own layer is lower");
assert_eq!(s.doc.project.layer(outer).unwrap().children(), [fb], "Fill A left its folder");
}
#[test]
fn shift_range_counts_the_folder_row_and_skips_the_layers_of_a_collapsed_folder() {
let mut s = session();
let [a, b, c, d] = four(&mut s);
let folder = id(execute(&mut s, "layer.add.group", &Value::Null).unwrap(), "layer");
execute(&mut s, "layer.move", &json!({"layers": [b.0, c.0], "above": folder.0, "inside": true})).unwrap();
// Rows from the top: Folder 1 (C, B), D, A... move the folder between D and A
execute(&mut s, "layer.move", &json!({"layers": [folder.0], "above": a.0})).unwrap();
assert_eq!(rows(&s)[..5], ["D", "Folder 1", "C", "B", "A"]);
click(&mut s, d, "plain");
click(&mut s, a, "shift");
assert_eq!(selected(&s), ["D", "Folder 1", "C", "B", "A"], "an open folder: the row and its layers");
if let LayerKind::Group { collapsed, .. } = &mut s.doc.project.layer_mut(folder).unwrap().kind {
*collapsed = true;
}
click(&mut s, d, "plain");
click(&mut s, a, "shift");
assert_eq!(selected(&s), ["D", "Folder 1", "A"], "a collapsed folder: the row, not its layers");
}
#[test]
fn select_all_takes_the_folder_rows_and_the_layers_of_open_folders_only() {
let mut s = session();
let [a, b, c, d] = four(&mut s);
let folder = id(execute(&mut s, "layer.add.group", &Value::Null).unwrap(), "layer");
execute(&mut s, "layer.move", &json!({"layers": [a.0, b.0], "above": folder.0, "inside": true})).unwrap();
click(&mut s, c, "plain");
let depth = s.history_labels().len();
// Open folder: the folder row and its layers
let r = execute(&mut s, "layer.select", &json!({"all": true})).unwrap();
let shown = stack_rows(&s.doc.project, 0, true);
assert_eq!(selected(&s)[..5], ["Folder 1", "B", "A", "D", "C"]);
assert_eq!(s.selected_layers(), shown, "every row of the set");
assert_eq!(r["layers"].as_array().unwrap().len(), shown.len());
assert_eq!(s.selected_layer(), Some(c), "the active layer stays");
assert_eq!(s.history_labels().len(), depth, "selecting is no undo step");
// Collapsed folder: the folder row, not its layers
if let LayerKind::Group { collapsed, .. } = &mut s.doc.project.layer_mut(folder).unwrap().kind {
*collapsed = true;
}
execute(&mut s, "layer.select", &json!({"layer": d.0})).unwrap();
execute(&mut s, "layer.select", &json!({"all": true})).unwrap();
assert_eq!(selected(&s)[..3], ["Folder 1", "D", "C"]);
assert!(!s.is_layer_selected(a) && !s.is_layer_selected(b), "the collapsed folder's layers stay unselected");
assert_eq!(s.selected_layer(), Some(d), "the active layer stays when it is picked again");
}
#[test]
fn the_visibility_of_one_layer_leaves_the_other_selected_layers_alone() {
let mut s = session();
let [a, _, c, _] = four(&mut s);
execute(&mut s, "layer.select", &json!({"layers": [a.0, c.0]})).unwrap();
execute(&mut s, "layer.visible", &json!({"layer": c.0})).unwrap();
assert!(!s.doc.project.layer(c).unwrap().visible && s.doc.project.layer(a).unwrap().visible, "only C is hidden");
assert_eq!(s.selected_layers().len(), 2, "the selection stays");
}
#[test]
fn visibility_of_several_layers_follows_the_layer_given_as_lead() {
let mut s = session();
let [a, b, c, _] = four(&mut s);
execute(&mut s, "layer.visible", &json!({"layer": a.0, "visible": false})).unwrap();
// The active layer is C (shown), but the eye of A (hidden) was clicked: all are shown
execute(&mut s, "layer.select", &json!({"layers": [a.0, b.0, c.0], "layer": c.0})).unwrap();
execute(&mut s, "layer.visible", &json!({"layers": [a.0, b.0, c.0], "layer": a.0})).unwrap();
let shown = |s: &Session| [a, b, c].map(|l| s.doc.project.layer(l).unwrap().visible);
assert_eq!(shown(&s), [true; 3], "A was hidden, so all are shown");
}
#[test]
fn visibility_toggles_every_selected_layer_the_way_of_the_active_one() {
let mut s = session();
let [a, b, c, _] = four(&mut s);
execute(&mut s, "layer.visible", &json!({"layer": a.0, "visible": false})).unwrap();
execute(&mut s, "layer.select", &json!({"layers": [a.0, b.0, c.0], "layer": c.0})).unwrap();
let depth = s.history_labels().len();
execute(&mut s, "layer.visible", &Value::Null).unwrap();
let shown = |s: &Session| [a, b, c].map(|l| s.doc.project.layer(l).unwrap().visible);
assert_eq!(shown(&s), [false; 3], "C was shown, so all are hidden");
assert_eq!(s.history_labels().len(), depth + 1, "one undo step");
execute(&mut s, "layer.visible", &json!({"layers": [a.0, b.0], "visible": true})).unwrap();
assert_eq!(shown(&s), [true, true, false]);
s.undo().unwrap();
s.undo().unwrap();
assert_eq!(shown(&s), [false, true, true]);
}
#[test]
fn selected_layers_move_together_keeping_their_order() {
let mut s = session();
let [a, b, c, d] = four(&mut s);
execute(&mut s, "layer.move", &json!({"layers": [a.0, c.0], "above": d.0})).unwrap();
assert_eq!(rows(&s)[..4], ["C", "A", "D", "B"]);
s.undo().unwrap();
assert_eq!(rows(&s)[..4], ["D", "C", "B", "A"]);
// Into a folder
let folder = id(execute(&mut s, "layer.add.group", &Value::Null).unwrap(), "layer");
execute(&mut s, "layer.move", &json!({"layers": [d.0, b.0], "above": folder.0, "inside": true})).unwrap();
assert_eq!(s.doc.project.layer(folder).unwrap().children(), [b, d]);
assert!(execute(&mut s, "layer.move", &json!({"layers": [a.0, c.0], "above": c.0})).is_err(), "not above one of themselves");
}
#[test]
fn selected_layers_moved_to_an_index_keep_their_order() {
for (pair, expected) in [("B", ["C", "D", "B", "A", "Layer 1"]), ("A", ["C", "D", "A", "B", "Layer 1"])] {
let mut s = session();
let [a, b, _, d] = four(&mut s);
let lower = if pair == "A" { a } else { b };
execute(&mut s, "layer.move", &json!({"layers": [d.0, lower.0], "index": 2})).unwrap();
assert_eq!(rows(&s)[..5], expected, "D and {pair} to index 2");
}
}
#[test]
fn extreme_move_deltas_clamp_to_the_stack_ends() {
let mut session = session();
let [_, layer, ..] = four(&mut session);
execute(&mut session, "layer.move", &json!({"layer": layer.0, "delta": i64::MAX})).unwrap();
assert_eq!(rows(&session)[0], "B", "a large positive delta moves to the top");
execute(&mut session, "layer.move", &json!({"layer": layer.0, "delta": i64::MIN})).unwrap();
assert_eq!(rows(&session).last().map(String::as_str), Some("B"), "a large negative delta moves to the bottom");
}
#[test]
fn layers_in_and_out_of_a_folder_dropped_below_the_stack_stay_together_at_its_bottom() {
let mut s = session();
let [_, b, _, d] = four(&mut s);
let folder = id(execute(&mut s, "layer.group", &json!({"layer": b.0})).unwrap(), "layer");
execute(&mut s, "layer.move", &json!({"layers": [d.0, b.0], "index": 0})).unwrap();
assert_eq!(s.doc.project.texture_sets[0].stack[..2], [b, d], "B at the bottom, D right above it");
assert!(s.doc.project.layer(folder).unwrap().children().is_empty(), "B left its folder");
}
#[test]
fn a_move_that_changes_nothing_is_not_an_undo_step() {
let mut s = session();
let [a, b, c, _] = four(&mut s);
let depth = s.history_labels().len();
execute(&mut s, "layer.move", &json!({"layer": b.0, "above": a.0})).unwrap();
execute(&mut s, "layer.move", &json!({"layers": [c.0, b.0], "above": a.0})).unwrap();
assert_eq!(s.history_labels().len(), depth, "B already sits above A, and C above B");
execute(&mut s, "layer.move", &json!({"layer": a.0, "above": c.0})).unwrap();
assert_eq!(s.history_labels().len(), depth + 1);
}
#[test]
fn an_explicit_layer_acts_on_that_layer_only_while_several_are_selected() {
let select = |s: &mut Session, b: LayerId, d: LayerId| execute(s, "layer.select", &json!({"layers": [b.0, d.0]})).unwrap();
let mut s = session();
let [_, b, _, d] = four(&mut s);
select(&mut s, b, d);
execute(&mut s, "layer.remove", &json!({"layer": b.0})).unwrap();
assert_eq!(rows(&s)[..3], ["D", "C", "A"], "remove");
let mut s = session();
let [_, b, _, d] = four(&mut s);
select(&mut s, b, d);
execute(&mut s, "layer.duplicate", &json!({"layer": b.0})).unwrap();
assert_eq!(rows(&s)[..5], ["D", "C", "B copy", "B", "A"], "duplicate");
let mut s = session();
let [_, b, _, d] = four(&mut s);
select(&mut s, b, d);
let folder = id(execute(&mut s, "layer.group", &json!({"layer": b.0})).unwrap(), "layer");
assert_eq!(s.doc.project.layer(folder).unwrap().children(), [b], "group");
let mut s = session();
let [_, b, _, d] = four(&mut s);
select(&mut s, b, d);
execute(&mut s, "layer.visible", &json!({"layer": b.0})).unwrap();
assert!(!s.doc.project.layer(b).unwrap().visible && s.doc.project.layer(d).unwrap().visible, "visible");
}
#[test]
fn undo_and_redo_end_the_multiple_selection() {
let mut s = session();
let [_, b, ..] = four(&mut s);
let e = add(&mut s, "E");
execute(&mut s, "layer.select", &json!({"layers": [b.0, e.0]})).unwrap();
s.undo().unwrap();
s.redo().unwrap();
assert_eq!(selected(&s), ["E"], "E is back alone, B is not picked again");
add(&mut s, "F");
assert_eq!(s.selected_layers().len(), 1);
assert!(!s.is_layer_selected(b));
}
#[test]
fn reselecting_an_earlier_active_layer_does_not_bring_back_its_multiple_selection() {
let mut s = session();
let [_, b, c, d] = four(&mut s);
click(&mut s, c, "plain");
let effect = execute(&mut s, "effect.add.filter", &json!({"target": "content", "filter": "invert"})).unwrap()["effect"].as_u64().unwrap();
execute(&mut s, "effect.copy", &json!({ "effect": effect })).unwrap();
execute(&mut s, "layer.select", &json!({"layers": [b.0, d.0], "layer": d.0})).unwrap();
add(&mut s, "E");
// Pasting the effect onto D selects D again, alone
execute(&mut s, "effect.paste", &json!({"layer": d.0})).unwrap();
assert_eq!(selected(&s), ["D"]);
}
#[test]
fn bad_layer_lists_are_errors() {
let mut s = session();
let [a, ..] = four(&mut s);
let other = id(execute(&mut s, "textureSet.select", &json!({"ts": 1})).and_then(|_| execute(&mut s, "layer.add.paint", &Value::Null)).unwrap(), "layer");
for command in ["layer.select", "layer.remove", "layer.duplicate", "layer.group", "layer.visible", "layer.move"] {
for layers in [json!("x"), json!([]), json!([u64::MAX]), json!([a.0, other.0]), json!([a.0, "x"])] {
assert!(execute(&mut s, command, &json!({"layers": layers, "above": null})).is_err(), "{command} {layers}");
}
}
assert!(execute(&mut s, "layer.select", &json!({"layers": [a.0], "layer": other.0})).is_err(), "the active layer must be listed");
}
#[test]
fn moving_layers_into_a_folder_in_another_set_preserves_the_document() {
let mut s = texturecraft_engine::sample_session(128, 64).unwrap();
let source = s.doc.project.texture_sets[0].stack[0];
execute(&mut s, "textureSet.select", &json!({"ts": 1})).unwrap();
let folder = id(execute(&mut s, "layer.add.group", &json!({})).unwrap(), "layer");
let before = s.doc.project.clone();
let history = s.history_labels();
for params in [json!({"layer": source.0, "above": folder.0, "inside": true}), json!({"layers": [source.0], "above": folder.0, "inside": true})] {
assert!(execute(&mut s, "layer.move", &params).is_err());
assert_eq!(s.doc.project, before);
assert_eq!(s.history_labels(), history);
}
}
+9
View File
@@ -6,15 +6,21 @@ mod bake_checks;
mod bake_resolution;
mod bake_settings;
mod bake_tiles;
mod brush_material;
mod closed_session;
mod color_selection;
mod content_effects;
mod export_colour_space;
mod filter_swap;
mod filters;
mod frame_selection;
mod generator_inputs;
mod gradient_map;
mod high_poly_missed;
mod instances;
mod layer_multi_select;
mod mask_clone_smudge;
mod mask_export;
mod materialcraft_link;
mod materialx;
mod materialx_import;
@@ -27,10 +33,13 @@ mod perf;
mod polygon_fill;
mod project_recovery;
mod sample;
mod solo;
mod thumbs;
mod tool_availability;
mod tool_settings;
mod tools;
mod udim;
mod user_smart_mask;
mod uv_strokes;
mod symmetry;
+158
View File
@@ -0,0 +1,158 @@
//! Clone and Smudge strokes on a layer mask read and write the mask's own values
use serde_json::json;
use texturecraft_engine::core::Channel;
use texturecraft_engine::geom::primitives;
use texturecraft_engine::{Session, execute};
const SIZE: u32 = 256;
/// A paint layer with a black mask selected, a 2D-view brush of about 13 texels radius
fn session_on_mask() -> (Session, u64) {
let mut session = Session::new_project("mask", primitives::plane(2.0, 4), "builtin:plane", None, SIZE).unwrap();
session.update();
let layer = execute(&mut session, "layer.add.paint", &json!({})).unwrap()["layer"].as_u64().unwrap();
execute(&mut session, "mask.add.black", &json!({"layer": layer})).unwrap();
execute(&mut session, "layer.select", &json!({"layer": layer, "target": "mask"})).unwrap();
execute(&mut session, "tool.brush", &json!({"size": 10, "hardness": 100, "spacing": 10})).unwrap();
execute(&mut session, "tool.material", &json!({"maskValue": 1.0})).unwrap();
(session, layer)
}
fn paint_white_blob(session: &mut Session, uv: [f32; 2]) {
execute(session, "tool.paint", &serde_json::Value::Null).unwrap();
execute(session, "tool.strokeUv", &json!({"points": [uv, uv]})).unwrap();
}
fn mask_at(session: &Session, layer: u64, uv: [f32; 2]) -> f32 {
let texel = ((uv[0] * SIZE as f32) as u32, (uv[1] * SIZE as f32) as u32);
session.mask_at(texturecraft_engine::core::LayerId(layer), &[texel]).unwrap()[0]
}
/// A stroke of `tool` that changes the mask next to the white blob at u = 0.25: clone copies the
/// blob to u = 0.75, smudge drags it to the right
fn stroke_with(session: &mut Session, tool: &str) {
execute(session, tool, &serde_json::Value::Null).unwrap();
execute(session, "tool.cloneSource", &json!({"uv": [0.25, 0.5]})).unwrap();
let points = if tool == "tool.clone" { json!([[0.75, 0.5], [0.75, 0.5]]) } else { json!([[0.25, 0.5], [0.3, 0.5], [0.35, 0.5], [0.4, 0.5], [0.45, 0.5]]) };
execute(session, "tool.strokeUv", &json!({"points": points})).unwrap();
}
/// Mask values at probes inside the blob, where smudge drags it and where clone copies it
const PROBES: [[f32; 2]; 3] = [[0.25, 0.5], [0.4, 0.5], [0.75, 0.5]];
#[test]
fn clone_on_a_mask_copies_the_mask_values_from_the_source() {
let (mut session, layer) = session_on_mask();
paint_white_blob(&mut session, [0.25, 0.5]);
assert!(mask_at(&session, layer, [0.25, 0.5]) > 0.95);
assert!(mask_at(&session, layer, [0.75, 0.5]) < 0.05);
execute(&mut session, "tool.clone", &serde_json::Value::Null).unwrap();
execute(&mut session, "tool.cloneSource", &json!({"uv": [0.25, 0.5]})).unwrap();
execute(&mut session, "tool.strokeUv", &json!({"points": [[0.75, 0.5], [0.75, 0.5]]})).unwrap();
assert!(mask_at(&session, layer, [0.75, 0.5]) > 0.95, "the white blob is cloned");
assert!(mask_at(&session, layer, [0.75, 0.8]) < 0.05, "only the stroke is painted");
assert!(mask_at(&session, layer, [0.25, 0.5]) > 0.95, "the source stays");
}
#[test]
fn clone_on_a_mask_copies_black_over_white_too() {
let (mut session, layer) = session_on_mask();
paint_white_blob(&mut session, [0.75, 0.5]);
execute(&mut session, "tool.clone", &serde_json::Value::Null).unwrap();
execute(&mut session, "tool.cloneSource", &json!({"uv": [0.25, 0.5]})).unwrap();
execute(&mut session, "tool.strokeUv", &json!({"points": [[0.75, 0.5], [0.75, 0.5]]})).unwrap();
assert!(mask_at(&session, layer, [0.75, 0.5]) < 0.05, "the black source erases the white blob");
}
#[test]
fn smudge_on_a_mask_drags_values_along_the_stroke() {
let (mut session, layer) = session_on_mask();
paint_white_blob(&mut session, [0.25, 0.5]);
assert!(mask_at(&session, layer, [0.4, 0.5]) < 0.05);
execute(&mut session, "tool.smudge", &serde_json::Value::Null).unwrap();
execute(&mut session, "tool.strokeUv", &json!({"points": [[0.25, 0.5], [0.3, 0.5], [0.35, 0.5], [0.4, 0.5], [0.45, 0.5]]})).unwrap();
assert!(mask_at(&session, layer, [0.4, 0.5]) > 0.3, "white is dragged to the right");
assert!(mask_at(&session, layer, [0.4, 0.8]) < 0.05, "nothing beside the stroke");
}
#[test]
fn a_clone_or_smudge_stroke_on_a_mask_leaves_the_channels_alone() {
for tool in ["tool.clone", "tool.smudge"] {
let (mut session, _) = session_on_mask();
paint_white_blob(&mut session, [0.25, 0.5]);
let channels_before = session.doc.pixels.layers.clone();
let colour_before = session.caches[0].composite.value(Channel::BaseColor, 192, 128);
stroke_with(&mut session, tool);
session.update();
assert_eq!(session.doc.pixels.layers.len(), channels_before.len(), "{tool}: no channel image is created");
assert!(session.doc.pixels.layers.keys().all(|key| channels_before.contains_key(key)), "{tool}");
assert_eq!(session.caches[0].composite.value(Channel::BaseColor, 192, 128), colour_before, "{tool}: the composite colour is unchanged");
}
}
#[test]
fn one_undo_restores_the_mask_after_a_clone_or_smudge_stroke() {
for tool in ["tool.clone", "tool.smudge"] {
let (mut session, layer) = session_on_mask();
paint_white_blob(&mut session, [0.25, 0.5]);
let steps = session.history_labels().len();
let before: Vec<f32> = PROBES.iter().map(|uv| mask_at(&session, layer, *uv)).collect();
stroke_with(&mut session, tool);
assert_eq!(session.history_labels().len(), steps + 1, "{tool}: one undo step per stroke");
let after: Vec<f32> = PROBES.iter().map(|uv| mask_at(&session, layer, *uv)).collect();
assert_ne!(before, after, "{tool}: the stroke changed the mask");
session.undo().unwrap();
let restored: Vec<f32> = PROBES.iter().map(|uv| mask_at(&session, layer, *uv)).collect();
assert_eq!(restored, before, "{tool}");
}
}
#[test]
fn clone_works_on_a_folder_mask() {
let mut session = Session::new_project("mask", primitives::plane(2.0, 4), "builtin:plane", None, SIZE).unwrap();
session.update();
let folder = execute(&mut session, "layer.add.group", &json!({})).unwrap()["layer"].as_u64().unwrap();
execute(&mut session, "mask.add.black", &json!({"layer": folder})).unwrap();
execute(&mut session, "layer.select", &json!({"layer": folder, "target": "mask"})).unwrap();
execute(&mut session, "tool.brush", &json!({"size": 10, "hardness": 100, "spacing": 10})).unwrap();
paint_white_blob(&mut session, [0.25, 0.5]);
execute(&mut session, "tool.clone", &serde_json::Value::Null).unwrap();
execute(&mut session, "tool.cloneSource", &json!({"uv": [0.25, 0.5]})).unwrap();
execute(&mut session, "tool.strokeUv", &json!({"points": [[0.75, 0.5], [0.75, 0.5]]})).unwrap();
assert!(mask_at(&session, folder, [0.75, 0.5]) > 0.95, "a folder mask clones too");
}
#[test]
fn clone_from_the_layer_reads_the_mask_on_a_folder_mask_and_a_paint_layer_mask() {
for group in [true, false] {
let mut session = Session::new_project("mask", primitives::plane(2.0, 4), "builtin:plane", None, SIZE).unwrap();
session.update();
let command = if group { "layer.add.group" } else { "layer.add.paint" };
let layer = execute(&mut session, command, &json!({})).unwrap()["layer"].as_u64().unwrap();
execute(&mut session, "mask.add.black", &json!({"layer": layer})).unwrap();
execute(&mut session, "layer.select", &json!({"layer": layer, "target": "mask"})).unwrap();
execute(&mut session, "tool.brush", &json!({"size": 10, "hardness": 100, "spacing": 10, "cloneSource": "layer"})).unwrap();
paint_white_blob(&mut session, [0.25, 0.5]);
execute(&mut session, "tool.clone", &serde_json::Value::Null).unwrap();
execute(&mut session, "tool.cloneSource", &json!({"uv": [0.25, 0.5]})).unwrap();
execute(&mut session, "tool.strokeUv", &json!({"points": [[0.75, 0.5], [0.75, 0.5]]})).unwrap();
assert!(mask_at(&session, layer, [0.75, 0.5]) > 0.95, "group {group}");
}
}
+146
View File
@@ -0,0 +1,146 @@
//! `mask.export` and `Session::mask_bitmaps`: the evaluated mask as a bitmap at the texture
//! set's resolution, oriented like the exported textures.
use std::path::PathBuf;
use serde_json::{Value, json};
use texturecraft_engine::core::{Channel, LayerId};
use texturecraft_engine::geom::{NO_TRI, primitives};
use texturecraft_engine::{Session, execute};
/// A new folder for one test's files.
fn temp_dir(test: &str) -> PathBuf {
let dir = std::env::temp_dir().join(format!("texturecraft-mask-export-{test}-{}", std::process::id()));
std::fs::create_dir_all(&dir).unwrap();
dir
}
/// A session of `mesh` with a fill layer whose mask is `value` wherever the mesh covers the texture.
fn session_with_mask(mesh: texturecraft_engine::geom::Mesh, name: &str, resolution: u32, value: f32) -> (Session, LayerId) {
let mut s = Session::new_project("t", mesh, name, None, resolution).unwrap();
let layer = LayerId(execute(&mut s, "layer.add.fill", &json!({"color": [1.0, 1.0, 1.0]})).unwrap()["layer"].as_u64().unwrap());
execute(&mut s, "mask.add.black", &Value::Null).unwrap();
execute(&mut s, "effect.add.fill", &json!({"value": value})).unwrap();
s.update();
(s, layer)
}
fn covered(s: &Session, x: u32, y: u32) -> bool {
let g = &s.caches[0].gbuf;
g.tri[(y * g.width + x) as usize] != NO_TRI
}
#[test]
fn the_bitmap_is_the_mask_the_composite_is_drawn_with_in_the_same_orientation() {
let mut s = Session::new_project("t", primitives::material_ball(), "builtin:material_ball", None, 256).unwrap();
let layer = LayerId(execute(&mut s, "layer.add.fill", &json!({"color": [1.0, 1.0, 1.0]})).unwrap()["layer"].as_u64().unwrap());
// A white layer gives output = base + (1 - base) * mask, so its mask can be recovered
execute(&mut s, "layer.visible", &json!({"layer": layer.0, "visible": false})).unwrap();
s.update();
let base: Vec<f32> = (0..256 * 256).map(|i| s.caches[0].composite.value(Channel::BaseColor, i % 256, i / 256)[0]).collect();
execute(&mut s, "layer.visible", &json!({"layer": layer.0, "visible": true})).unwrap();
execute(&mut s, "mask.add.black", &Value::Null).unwrap();
execute(&mut s, "effect.add.fill", &json!({"procedural": "clouds", "seed": 3})).unwrap();
s.update();
let bitmaps = s.mask_bitmaps(layer, true).unwrap();
assert_eq!(bitmaps.len(), 1, "a classic set gives one bitmap");
let bitmap = &bitmaps[0];
assert_eq!((bitmap.tile, bitmap.width, bitmap.height), (None, 256, 256));
assert_eq!(bitmap.values.len(), 256 * 256);
let (mut covered_texels, mut distinct) = (0, std::collections::BTreeSet::new());
for y in 0..256u32 {
for x in 0..256u32 {
let value = bitmap.values[(y * 256 + x) as usize];
if !covered(&s, x, y) {
assert_eq!(value, 0.0, "uncovered texel ({x}, {y}) is black");
continue;
}
covered_texels += 1;
distinct.insert((value * 100.0) as u32);
let base = base[(y * 256 + x) as usize];
let shown = s.caches[0].composite.value(Channel::BaseColor, x, y)[0];
assert!((base + (1.0 - base) * value - shown).abs() < 3e-3, "texel ({x}, {y}): mask {value} does not give the composite {shown} over {base}");
}
}
assert!(covered_texels > 1000, "the mesh covers part of the texture");
assert!(distinct.len() > 20, "the mask varies across the texture, so a mirrored bitmap would not match the composite");
}
#[test]
fn inverting_changes_the_bitmap_and_a_switched_off_or_missing_mask_is_an_error() {
let (mut s, layer) = session_with_mask(primitives::material_ball(), "builtin:material_ball", 128, 0.25);
execute(&mut s, "mask.invert", &json!({"layer": layer.0})).unwrap();
let bitmap = s.mask_bitmaps(layer, false).unwrap().remove(0);
let (x, y) = (0..128 * 128).map(|i| (i % 128, i / 128)).find(|&(x, y)| covered(&s, x, y)).unwrap();
assert!((bitmap.values[(y * 128 + x) as usize] - 0.75).abs() < 1e-3, "inverting 0.25 gives 0.75");
execute(&mut s, "mask.toggle", &json!({"layer": layer.0, "enabled": false})).unwrap();
assert!(s.mask_bitmaps(layer, false).is_err(), "a switched-off mask has nothing to export");
execute(&mut s, "mask.remove", &json!({"layer": layer.0})).unwrap();
assert!(s.mask_bitmaps(layer, false).is_err(), "so has a layer without a mask");
}
#[test]
fn mask_export_writes_a_16_bit_gray_png() {
let (mut s, layer) = session_with_mask(primitives::material_ball(), "builtin:material_ball", 128, 0.5);
let dir = temp_dir("png");
let path = dir.join("ball_mask.png");
let done = execute(&mut s, "mask.export", &json!({"layer": layer.0, "path": path.display().to_string()})).unwrap();
assert_eq!(done["files"], json!([path.display().to_string()]));
let image = image::open(&path).unwrap();
assert!(matches!(image, image::DynamicImage::ImageLuma16(_)), "16-bit grayscale, got {:?}", image.color());
let gray = image.into_luma16();
assert_eq!(gray.dimensions(), (128, 128));
let expected = s.mask_bitmaps(layer, true).unwrap().remove(0).gray16();
assert_eq!(gray.as_raw(), &expected, "the file holds the bitmap, top row first");
// 0.5 is a level 8-bit files cannot hold exactly
assert!(gray.pixels().any(|p| p.0[0] == 32768), "the 16-bit level of 0.5");
// The extension is added, and the layer defaults to the selected one
let done = execute(&mut s, "mask.export", &json!({"path": dir.join("other").display().to_string()})).unwrap();
assert_eq!(done["files"], json!([dir.join("other.png").display().to_string()]));
assert!(dir.join("other.png").exists());
assert!(execute(&mut s, "mask.export", &json!({"layer": layer.0})).is_err(), "a path is required");
let _ = std::fs::remove_dir_all(dir);
}
#[test]
fn a_tiled_set_exports_one_file_per_tile_at_each_tiles_size() {
let (mut s, layer) = session_with_mask(primitives::udim_plane(), "builtin:udim_plane", 256, 0.5);
execute(&mut s, "textureSet.tile.resolution", &json!({"ts": 0, "tile": 1002, "resolution": 128})).unwrap();
s.update();
let (width, height) = s.caches[0].size;
assert_eq!((width, height), (512, 256), "two blocks of the larger tile's size");
let bitmaps = s.mask_bitmaps(layer, true).unwrap();
assert_eq!(bitmaps.iter().map(|b| (b.tile, b.width, b.height)).collect::<Vec<_>>(), [(Some(1001), 256, 256), (Some(1002), 128, 128)]);
// The smaller tile fills the top-left corner of its block
for (bitmap, block_x) in bitmaps.iter().zip([0, 256]) {
for y in 0..bitmap.height {
for x in 0..bitmap.width {
let expected = if covered(&s, block_x + x, y) { 0.5 } else { 0.0 };
let value = bitmap.values[(y * bitmap.width + x) as usize];
assert!((value - expected).abs() < 1e-3, "tile {:?} texel ({x}, {y}): {value}", bitmap.tile);
}
}
}
assert!(bitmaps.iter().all(|b| b.values.iter().any(|v| *v > 0.4)), "both tiles have mask");
let atlas = s.mask_bitmaps(layer, false).unwrap();
assert_eq!(atlas.len(), 1);
assert_eq!((atlas[0].tile, atlas[0].width, atlas[0].height), (None, 512, 256), "the clipboard copy is the whole atlas");
let dir = temp_dir("tiles");
let path = dir.join("plane_mask.png");
let done = execute(&mut s, "mask.export", &json!({"layer": layer.0, "path": path.display().to_string()})).unwrap();
assert_eq!(done["files"], json!([dir.join("plane_mask.1001.png").display().to_string(), dir.join("plane_mask.1002.png").display().to_string()]));
assert_eq!(image::open(dir.join("plane_mask.1001.png")).unwrap().into_luma16().dimensions(), (256, 256));
assert_eq!(image::open(dir.join("plane_mask.1002.png")).unwrap().into_luma16().dimensions(), (128, 128));
let _ = std::fs::remove_dir_all(dir);
}
+297 -6
View File
@@ -3,7 +3,7 @@
//! maps from images and fill projection transforms, through engine commands.
use serde_json::{Value, json};
use texturecraft_engine::core::{Channel, EffectKind, Filter, LayerId, LayerKind, Projection};
use texturecraft_engine::core::{Channel, Decal, EffectKind, Filter, LayerId, LayerKind, Projection, Source};
use texturecraft_engine::geom::NO_TRI;
use texturecraft_engine::geom::glam::Vec2;
use texturecraft_engine::geom::primitives;
@@ -171,7 +171,8 @@ fn solo_keeps_one_material_channel() {
#[test]
fn decals_project_an_image_from_a_frame_placed_on_the_surface() {
let mut s = session();
// A red disc on a transparent background.
// A red disc on a transparent background
let name = s
.import_resource_bytes("logo.png", png(32, 32, |x, y| if (x as i32 - 16).pow(2) + (y as i32 - 16).pow(2) < 196 { [255, 0, 0, 255] } else { [0; 4] }))
.unwrap();
@@ -184,9 +185,11 @@ fn decals_project_an_image_from_a_frame_placed_on_the_surface() {
assert!(matches!(f.projection, Projection::Decal(_)));
assert!(red(at(&mut s, Channel::BaseColor, 200.0, 200.0)), "the decal shows where it was placed");
assert!(!red(at(&mut s, Channel::BaseColor, 120.0, 200.0)), "and only there");
// The image's transparent corners leave the surface as it was.
// The image's transparent corners leave the surface as it was
assert!(!red(at(&mut s, Channel::BaseColor, 200.0 + 30.0, 200.0 - 30.0)));
// Bigger, then moved along its plane, then re-placed with a click.
// Bigger, then moved along its plane, then re-placed with a click
execute(&mut s, "layer.decal.set", &json!({"size": 1.2})).unwrap();
assert!(red(at(&mut s, Channel::BaseColor, 160.0, 200.0)));
execute(&mut s, "layer.decal.set", &json!({"size": 0.4, "offset": [0.6, 0.0], "rotation": 45})).unwrap();
@@ -196,7 +199,8 @@ fn decals_project_an_image_from_a_frame_placed_on_the_surface() {
assert!(red(at(&mut s, Channel::BaseColor, 170.0, 180.0)));
let inspect = execute(&mut s, "project.inspect", &Value::Null).unwrap().to_string();
assert!(inspect.contains("Decal projection") && inspect.contains("\"rotation\":45"), "inspect shows the decal");
// Not a decal; one undo step per edit.
// Not a decal; one undo step per edit
let plain = id(execute(&mut s, "layer.add.fill", &Value::Null).unwrap(), "layer");
assert!(execute(&mut s, "layer.decal.set", &json!({"layer": plain.0, "size": 1})).is_err());
execute(&mut s, "edit.undo", &Value::Null).unwrap();
@@ -204,6 +208,106 @@ fn decals_project_an_image_from_a_frame_placed_on_the_surface() {
assert!(!red(at(&mut s, Channel::BaseColor, 170.0, 180.0)));
}
/// The decal of mask fill effect `effect`
fn effect_decal(s: &Session, effect: LayerId) -> Decal {
let EffectKind::Fill { projection: Projection::Decal(decal), .. } = &s.doc.project.effect(effect).unwrap().1.kind else { panic!("a decal fill effect") };
*decal
}
#[test]
fn a_mask_fill_effects_decal_is_edited_like_a_layer_decal() {
let mut s = session();
let name = s.import_resource_bytes("logo.png", png(8, 8, |_, _| [255, 255, 255, 255])).unwrap();
let added = execute(&mut s, "layer.add.decal", &json!({"image": name, "channel": "mask", "x": 200, "y": 200, "size": 0.5})).unwrap();
let (layer, effect) = (id(added.clone(), "layer"), id(added, "maskEffect"));
let layer_decal = id(execute(&mut s, "layer.add.decal", &json!({"image": name, "x": 200, "y": 200, "size": 0.5})).unwrap(), "layer");
let before = effect_decal(&s, effect);
let steps = s.history_labels().len();
// Only the effect id, with no layer selected
s.selected.clear();
assert!(s.selected_layer().is_none());
let r = execute(&mut s, "layer.decal.set", &json!({"effect": effect.0, "size": [0.3, 0.2], "offset": [0.1, -0.05], "rotation": 30, "depth": 0.2})).unwrap();
assert_eq!(r["layer"], json!(layer.0), "the owning layer is reported");
let after = effect_decal(&s, effect);
assert_eq!((after.size, after.offset, after.rotation), ([0.3, 0.2], [0.1, -0.05], 30.0));
assert_eq!(after.center, before.center, "the other fields stay");
assert_eq!(s.history_labels().len(), steps + 1, "one undo step per edit");
// Re-placing with a click
execute(&mut s, "layer.decal.set", &json!({"effect": effect.0, "layer": layer.0, "x": 170, "y": 180})).unwrap();
assert_eq!(effect_decal(&s, effect).offset, [0.0, 0.0]);
execute(&mut s, "edit.undo", &Value::Null).unwrap();
execute(&mut s, "edit.undo", &Value::Null).unwrap();
assert_eq!(effect_decal(&s, effect), before, "undo restores the effect's decal");
// The layer decal is untouched by all of it
let LayerKind::Fill(f) = &s.doc.project.layer(layer_decal).unwrap().kind else { panic!("a fill layer") };
assert!(matches!(&f.projection, Projection::Decal(d) if d.size[1] == 0.5 && d.rotation == 0.0));
// Errors: unknown effect, an effect that is not a decal, an effect of another layer
assert!(execute(&mut s, "layer.decal.set", &json!({"effect": 999_999, "size": 1})).is_err());
execute(&mut s, "layer.select", &json!({"layer": layer.0})).unwrap();
let levels = id(execute(&mut s, "effect.add.filter", &json!({"layer": layer.0, "filter": "levels"})).unwrap(), "effect");
assert!(execute(&mut s, "layer.decal.set", &json!({"effect": levels.0, "size": 1})).is_err());
assert!(execute(&mut s, "layer.decal.set", &json!({"effect": effect.0, "layer": layer_decal.0, "size": 1})).is_err());
assert_eq!(effect_decal(&s, effect), before);
// A new image replaces the effect's source, not a layer channel
let other = s.import_resource_bytes("other.png", png(4, 4, |_, _| [0, 0, 0, 255])).unwrap();
execute(&mut s, "layer.decal.set", &json!({"effect": effect.0, "image": other})).unwrap();
assert!(matches!(&s.doc.project.effect(effect).unwrap().1.kind, EffectKind::Fill { source: Source::Image { name, .. }, .. } if *name == other));
}
#[test]
fn decals_keep_the_image_aspect_and_flip_their_image() {
let mut s = session();
// Twice as wide as tall, left half red and right half blue
let name = s.import_resource_bytes("wide.png", png(8, 4, |x, _| if x < 4 { [255, 0, 0, 255] } else { [0, 0, 255, 255] })).unwrap();
let r = execute(&mut s, "layer.add.decal", &json!({"image": name, "x": 200, "y": 200, "size": 0.5})).unwrap();
let layer = id(r.clone(), "layer");
assert_eq!(r["decal"]["size"], json!([1.0, 0.5]), "a new decal follows its image");
assert!(r["decal"].get("flip").is_none(), "nothing flipped saves nothing extra");
let size = |s: &mut Session| {
let LayerKind::Fill(f) = &s.doc.project.layer(layer).unwrap().kind else { panic!("a fill layer") };
let Projection::Decal(d) = &f.projection else { panic!("a decal") };
(d.size, d.flip)
};
// A pair of sides is taken as given, unless the proportions are kept: then the width wins
execute(&mut s, "layer.decal.set", &json!({"size": [0.6, 0.6]})).unwrap();
assert_eq!(size(&mut s).0, [0.6, 0.6]);
execute(&mut s, "layer.decal.set", &json!({"size": [0.8, 0.8], "keepProportions": true})).unwrap();
assert_eq!(size(&mut s).0, [0.8, 0.4], "the width sets the height by the image's aspect");
execute(&mut s, "layer.decal.set", &json!({"size": 0.2, "keepProportions": true})).unwrap();
assert_eq!(size(&mut s).0, [0.4, 0.2], "a height sets the width");
execute(&mut s, "layer.decal.set", &json!({"size": [0.6, 0.6]})).unwrap();
execute(&mut s, "layer.decal.set", &json!({"keepProportions": true})).unwrap();
assert_eq!(size(&mut s).0, [0.6, 0.3], "turning the lock on fits the height to the width");
execute(&mut s, "edit.undo", &Value::Null).unwrap();
assert_eq!(size(&mut s).0, [0.6, 0.6], "one undo step");
// Flip U and V each on their own, kept by later edits, undone one step at a time
execute(&mut s, "layer.decal.set", &json!({"size": [1.0, 0.5]})).unwrap();
assert!(red(at(&mut s, Channel::BaseColor, 190.0, 200.0)) && !red(at(&mut s, Channel::BaseColor, 210.0, 200.0)));
let r = execute(&mut s, "layer.decal.set", &json!({"flipU": true})).unwrap();
assert_eq!(r["decal"]["flip"], json!([true, false]));
assert!(!red(at(&mut s, Channel::BaseColor, 190.0, 200.0)) && red(at(&mut s, Channel::BaseColor, 210.0, 200.0)), "Flip U mirrors the image in its frame");
execute(&mut s, "layer.decal.set", &json!({"flipV": true, "rotation": 10})).unwrap();
assert_eq!(size(&mut s).1, [true, true]);
execute(&mut s, "layer.decal.set", &json!({"flipU": false})).unwrap();
assert_eq!(size(&mut s).1, [false, true], "the other flip stays");
execute(&mut s, "edit.undo", &Value::Null).unwrap();
assert_eq!(size(&mut s).1, [true, true]);
// A new image in the same call sets the aspect: a tall one (1:2)
let tall = s.import_resource_bytes("tall.png", png(4, 8, |_, _| [255, 0, 0, 255])).unwrap();
execute(&mut s, "layer.decal.set", &json!({"image": tall, "size": 0.4, "keepProportions": true})).unwrap();
assert_eq!(size(&mut s).0, [0.2, 0.4]);
}
#[test]
fn a_decal_takes_its_up_from_the_params_or_a_rule_that_never_degenerates() {
let mut s = session();
@@ -616,7 +720,8 @@ fn directx_normal_images_flip_green() {
assert!(fill(&mut s, json!({"normalFormat": "sideways"})).is_err());
assert!(fill(&mut s, json!({"image": name, "normalFormat": 1})).is_err(), "not a string");
assert!(fill(&mut s, json!({"value": [0.5, 0.5, 1.0], "normalFormat": "directX"})).is_err(), "not an image");
// Marking an image on a channel that is off leaves it off.
// Marking an image on a channel that is off leaves it off
fill(&mut s, json!({"enabled": false})).unwrap();
fill(&mut s, json!({"normalFormat": "directX"})).unwrap();
assert!(!s.doc.project.layer(layer).unwrap().channels.contains_key(&Channel::Normal));
@@ -626,3 +731,189 @@ fn directx_normal_images_flip_green() {
let old: texturecraft_engine::core::Source = serde_json::from_value(json!({"Image": {"name": "n"}})).unwrap();
assert_eq!(old, texturecraft_engine::core::Source::image("n"));
}
/// Red texels of the cube's -X face (turned away from where the decals are placed) whose position satisfies `inside`
fn red_on_minus_x(s: &mut Session, inside: impl Fn(f32, f32) -> bool) -> usize {
s.update();
let cache = &s.caches[0];
let (w, h) = cache.size;
(0..w * h)
.filter(|&i| {
let Some(surface) = cache.gbuf.surface(&s.mesh, i as usize) else { return false };
surface.nrm.x < -0.99 && inside(surface.pos.y, surface.pos.z) && red(cache.composite.value(Channel::BaseColor, i % w, i / w))
})
.count()
}
fn decal_of(s: &Session, layer: LayerId) -> texturecraft_engine::core::Decal {
let LayerKind::Fill(fill) = &s.doc.project.layer(layer).unwrap().kind else { panic!("a fill layer") };
let Projection::Decal(decal) = fill.projection else { panic!("a decal") };
decal
}
#[test]
fn a_decal_with_symmetry_also_covers_the_mirrored_side_and_follows_its_edits() {
use texturecraft_engine::core::{DecalFlip, DecalSymmetry};
let mut s = Session::new_project("t", primitives::cube(2.0), "builtin:cube", None, 256).unwrap();
let name = s.import_resource_bytes("logo.png", png(8, 8, |_, _| [255, 0, 0, 255])).unwrap();
let place = json!({"image": name, "position": [1.0, 0.0, 0.0], "normal": [1.0, 0.0, 0.0], "up": [0.0, 1.0, 0.0], "size": 0.6});
let layer = id(execute(&mut s, "layer.add.decal", &place).unwrap(), "layer");
assert_eq!(decal_of(&s, layer).symmetry, None, "no copy unless asked for");
assert_eq!(red_on_minus_x(&mut s, |_, _| true), 0);
assert!(execute(&mut s, "layer.decal.set", &json!({"symmetry": "w"})).is_err());
assert!(execute(&mut s, "layer.decal.set", &json!({"symmetryFlip": "up"})).is_err());
let depth = s.history_labels().len();
let r = execute(&mut s, "layer.decal.set", &json!({"symmetry": "x", "symmetryFlip": "u"})).unwrap();
assert_eq!(r["decal"]["symmetry"], json!({"axis": 0, "flip": "u"}));
assert_eq!(s.history_labels().len(), depth + 1, "one undo step");
let centered = red_on_minus_x(&mut s, |y, z| y.abs() < 0.2 && z.abs() < 0.2);
assert!(centered > 20, "the mirrored copy shows opposite the decal: {centered}");
// The copy follows the decal when it moves (offset along its up) and when it grows
execute(&mut s, "layer.decal.set", &json!({"offset": [0.0, 0.5]})).unwrap();
assert!(red_on_minus_x(&mut s, |y, _| y > 0.3) > 20, "moved up with the decal");
assert_eq!(red_on_minus_x(&mut s, |y, _| y.abs() < 0.1), 0, "and left the middle");
execute(&mut s, "layer.decal.set", &json!({"size": 1.6})).unwrap();
assert!(red_on_minus_x(&mut s, |y, _| y.abs() < 0.1) > 20, "bigger with the decal");
execute(&mut s, "layer.decal.set", &json!({"size": 0.6})).unwrap();
// A flip alone keeps the axis; off removes the copy
execute(&mut s, "layer.decal.set", &json!({"symmetryFlip": "v"})).unwrap();
assert_eq!(decal_of(&s, layer).symmetry, Some(DecalSymmetry { axis: 0, flip: DecalFlip::V, offset: 0.0 }));
execute(&mut s, "layer.decal.set", &json!({"symmetry": "z"})).unwrap();
assert_eq!(decal_of(&s, layer).symmetry, Some(DecalSymmetry { axis: 2, flip: DecalFlip::V, offset: 0.0 }), "a new axis keeps the flip");
execute(&mut s, "layer.decal.set", &json!({"symmetry": "x"})).unwrap();
// The mirror plane's position is kept across axis changes, stays within the mesh and is saved
let r = execute(&mut s, "layer.decal.set", &json!({"symmetryOffset": 0.5})).unwrap();
assert_eq!(r["decal"]["symmetry"]["offset"], json!(0.5));
assert_eq!(red_on_minus_x(&mut s, |_, _| true), 0, "a plane at x = 0.5 puts the copy out of reach of the -X face");
let r = execute(&mut s, "layer.decal.set", &json!({"symmetryOffset": 9.0})).unwrap();
assert_eq!(r["decal"]["symmetry"]["offset"], json!(1.0), "the cube is 2 wide: at most 1 from its center");
assert_eq!(r["decal"]["symmetry"]["axis"], json!(0), "the axis is kept");
execute(&mut s, "layer.decal.set", &json!({"symmetryOffset": 0.5})).unwrap();
// Saved with the project
let reopened = Session::from_project_bytes(&s.to_project_bytes().unwrap()).unwrap();
assert_eq!(reopened.doc.project, s.doc.project);
assert_eq!(decal_of(&reopened, layer).symmetry, Some(DecalSymmetry { axis: 0, flip: DecalFlip::V, offset: 0.5 }));
// Ten edits since the copy was asked for: undoing them all leaves the decal as placed
for _ in 0..10 {
execute(&mut s, "edit.undo", &Value::Null).unwrap();
}
assert_eq!(decal_of(&s, layer).symmetry, None);
assert_eq!(red_on_minus_x(&mut s, |_, _| true), 0);
execute(&mut s, "edit.redo", &Value::Null).unwrap();
assert!(red_on_minus_x(&mut s, |_, _| true) > 20, "redo brings the copy back");
execute(&mut s, "layer.decal.set", &json!({"symmetry": "off"})).unwrap();
assert_eq!(decal_of(&s, layer).symmetry, None);
assert_eq!(red_on_minus_x(&mut s, |_, _| true), 0, "off: the other side is bare again");
// A decal can be added with a copy right away
let both = execute(&mut s, "layer.add.decal", &json!({"image": name, "position": [0.0, 1.0, 0.0], "normal": [0.0, 1.0, 0.0], "symmetry": "y"})).unwrap();
assert_eq!(both["decal"]["symmetry"], json!({"axis": 1, "flip": "none"}), "no offset is written while it is 0");
let shifted = execute(
&mut s,
"layer.add.decal",
&json!({"image": name, "position": [0.0, 1.0, 0.0], "normal": [0.0, 1.0, 0.0], "symmetry": "y", "symmetryOffset": -0.4}),
)
.unwrap();
assert!((shifted["decal"]["symmetry"]["offset"].as_f64().unwrap() + 0.4).abs() < 1e-6);
}
/// A decal's up as the projection shows it: the stored up inside the surface plane.
fn plane_up(decal: &Value) -> texturecraft_engine::geom::glam::Vec3 {
use texturecraft_engine::geom::glam::Vec3;
let v = |key: &str| Vec3::new(decal[key][0].as_f64().unwrap() as f32, decal[key][1].as_f64().unwrap() as f32, decal[key][2].as_f64().unwrap() as f32);
let normal = v("normal").normalize();
(v("up") - normal * normal.dot(v("up"))).normalize_or_zero()
}
#[test]
fn a_decal_moved_onto_another_facing_surface_keeps_a_valid_frame_with_the_carried_up() {
use texturecraft_engine::geom::glam::Vec3;
let mut s = Session::new_project("t", primitives::cube(2.0), "builtin:cube", None, 256).unwrap();
s.viewport = Vec2::new(400.0, 400.0);
let name = s.import_resource_bytes("logo.png", png(8, 4, |_, _| [255, 0, 0, 255])).unwrap();
// On the +Z face, its up turned halfway between world X and Y, size and turn set by the user
let place = json!({"image": name, "position": [0.0, 0.0, 1.0], "normal": [0.0, 0.0, 1.0], "up": [1.0, 1.0, 0.0], "size": [0.6, 0.3], "rotation": 25});
let layer = id(execute(&mut s, "layer.add.decal", &place).unwrap(), "layer");
// Onto the +Y face: the up turns with the surface and follows the old up's direction in it
let r = execute(&mut s, "layer.decal.set", &json!({"layer": layer.0, "position": [0.2, 1.0, 0.1], "normal": [0.0, 1.0, 0.0]})).unwrap();
let up = plane_up(&r["decal"]);
assert!((up.length() - 1.0).abs() < 1e-4 && up.dot(Vec3::Y).abs() < 1e-4, "an up inside the +Y face: {up}");
assert!(up.x > 0.5, "the old up's X side stays on the X side: {up}");
assert_eq!(r["decal"]["rotation"], json!(25.0), "the user's turn stays");
assert_eq!(r["decal"]["size"], json!([0.6_f32, 0.3_f32]), "and the size");
// Straight up the face with the old up along the new normal: no degenerate frame, nothing arbitrary
let r =
execute(&mut s, "layer.decal.set", &json!({"layer": layer.0, "position": [0.0, 0.0, 1.0], "normal": [0.0, 0.0, 1.0], "up": [0.0, 1.0, 0.0]})).unwrap();
assert_eq!(plane_up(&r["decal"]), Vec3::Y);
let r = execute(&mut s, "layer.decal.set", &json!({"layer": layer.0, "position": [0.0, 1.0, 0.0], "normal": [0.0, 1.0, 0.0]})).unwrap();
assert!((plane_up(&r["decal"]) - Vec3::NEG_Z).length() < 1e-4, "the up that pointed up the +Z face points away over the edge: {:?}", r["decal"]["up"]);
// Onto the opposite face there is no smallest turn: the frame is still valid and follows the camera rule
let r = execute(&mut s, "layer.decal.set", &json!({"layer": layer.0, "position": [0.0, -1.0, 0.0], "normal": [0.0, -1.0, 0.0]})).unwrap();
let up = plane_up(&r["decal"]);
assert!((up.length() - 1.0).abs() < 1e-4 && up.dot(Vec3::Y).abs() < 1e-4, "{up}");
// An explicit up still wins
let r =
execute(&mut s, "layer.decal.set", &json!({"layer": layer.0, "position": [1.0, 0.0, 0.0], "normal": [1.0, 0.0, 0.0], "up": [0.0, 0.0, 1.0]})).unwrap();
assert_eq!(plane_up(&r["decal"]), Vec3::Z);
let r = execute(&mut s, "layer.decal.set", &json!({"layer": layer.0, "up": [0.0, 1.0, 0.0]})).unwrap();
assert_eq!(plane_up(&r["decal"]), Vec3::Y, "an up without a move too");
}
#[test]
fn a_decal_dragged_over_the_sphere_never_flips_its_up_between_steps() {
use texturecraft_engine::geom::glam::Vec3;
let mut s = session();
let name = s.import_resource_bytes("logo.png", png(8, 8, |_, _| [255, 0, 0, 255])).unwrap();
let place = json!({"image": name, "position": [0.0, 0.0, 1.0], "normal": [0.0, 0.0, 1.0], "up": [0.0, 1.0, 0.0], "size": 0.3});
let layer = id(execute(&mut s, "layer.add.decal", &place).unwrap(), "layer");
// Over the pole (the old up lies along the normal there) and down the far side, in 5 degree steps
let mut last = Vec3::Y;
for step in 0..=72 {
let angle = (step as f32 * 5.0).to_radians();
let normal = [0.0, angle.sin(), angle.cos()];
let r = execute(&mut s, "layer.decal.set", &json!({"layer": layer.0, "position": normal, "normal": normal, "merge": step > 0})).unwrap();
let up = plane_up(&r["decal"]);
assert!((up.length() - 1.0).abs() < 1e-4, "step {step}: no frame at {normal:?}");
assert!(up.dot(last) > 0.0, "step {step}: up turned from {last} to {up}");
last = up;
}
// The same drag through viewport points (what the 3D view sends), from the middle to the edge
for step in 0..25 {
let r = execute(&mut s, "layer.decal.set", &json!({"layer": layer.0, "x": 200.0 + step as f32 * 2.0, "y": 200.0 - step as f32 * 2.0, "merge": true}))
.unwrap();
let up = plane_up(&r["decal"]);
assert!((up.length() - 1.0).abs() < 1e-4 && up.dot(last) > 0.0, "viewport step {step}: {last} to {up}");
last = up;
}
}
#[test]
fn a_saved_decal_with_an_out_of_range_axis_is_repaired_on_load_and_can_be_edited() {
let mut session = session();
let image = session.import_resource_bytes("decal.png", png(4, 4, |_, _| [255; 4])).unwrap();
let layer = id(execute(&mut session, "layer.add.decal", &json!({"image": image, "symmetry": "x"})).unwrap(), "layer");
let LayerKind::Fill(fill) = &mut session.doc.project.layer_mut(layer).unwrap().kind else { panic!("expected fill") };
let Projection::Decal(decal) = &mut fill.projection else { panic!("expected decal") };
decal.symmetry.as_mut().unwrap().axis = u8::MAX;
let bytes = session.to_project_bytes().unwrap();
let mut loaded = Session::from_project_bytes(&bytes).unwrap();
assert_eq!(decal_of(&loaded, layer).symmetry.unwrap().axis, 2);
execute(&mut loaded, "layer.decal.set", &json!({"layer": layer.0, "rotation": 12})).unwrap();
assert_eq!(decal_of(&loaded, layer).symmetry.unwrap().axis, 2);
}
+121
View File
@@ -709,3 +709,124 @@ fn removing_the_final_stored_point_removes_the_path_and_undo_restores_it() {
assert_eq!(session.doc.project, before.project);
assert_eq!(session.doc.pixels.layers, before.pixels.layers);
}
const SQUARE_UV: [[f32; 2]; 4] = [[0.2, 0.2], [0.8, 0.2], [0.8, 0.8], [0.2, 0.8]];
/// A closed path of corner points runs straight along its edges; the smooth one bulges past them
#[test]
fn corner_points_make_a_path_with_straight_edges() {
let mut s = session(wall());
execute(&mut s, "tool.path", &json!({"uvPoints": SQUARE_UV, "closed": true, "commit": true})).unwrap();
assert!(red_uv(&s, 0.5, 0.125), "a smooth closed path bulges outside the square's edge");
assert!(!red_uv(&s, 0.5, 0.2));
let mut s = session(wall());
execute(&mut s, "tool.path", &json!({"uvPoints": SQUARE_UV, "corners": [true, true, true, true], "closed": true, "commit": true})).unwrap();
assert!(red_uv(&s, 0.5, 0.2) && red_uv(&s, 0.8, 0.5) && red_uv(&s, 0.5, 0.8) && red_uv(&s, 0.2, 0.5), "the edges are straight");
assert!(!red_uv(&s, 0.5, 0.125) && !red_uv(&s, 0.875, 0.5), "no bulge past the edges");
// The fill of a corner path is the quadrilateral too
let mut s = session(wall());
execute(&mut s, "tool.path", &json!({"uvPoints": SQUARE_UV, "corners": [true, true, true, true], "closed": true, "fill": true, "commit": true})).unwrap();
assert!(red_uv(&s, 0.5, 0.21) && !red_uv(&s, 0.5, 0.15));
assert!(execute(&mut s, "tool.path", &json!({"corners": [true, 3]})).is_err());
}
#[test]
fn invalid_corner_flags_leave_the_current_curve_unchanged() {
let mut session = session(wall());
execute(&mut session, "tool.path", &json!({"uvPoints": [[0.2, 0.2], [0.5, 0.8], [0.8, 0.2]], "corners": [true, false, true]})).unwrap();
let before = session.tool.path.clone();
assert!(execute(&mut session, "tool.path", &json!({"uvPoints": SQUARE_UV, "corners": [true, 3]})).is_err());
assert_eq!(session.tool.path, before, "malformed flags leave the curve intact");
assert!(execute(&mut session, "tool.path", &json!({"corners": [true, true, true, true]})).is_err());
assert_eq!(session.tool.path, before, "extra flags cannot outlive their points");
}
/// Toggling a corner repaints the edited path, is one undo step that also restores the pixels, and is saved with the project
#[test]
fn toggling_a_corner_is_one_undo_step_and_is_saved() {
let mut s = session(wall());
let report = execute(&mut s, "tool.path", &json!({"uvPoints": [[0.2, 0.2], [0.5, 0.8], [0.8, 0.2]], "commit": true})).unwrap();
let effect = texturecraft_engine::core::LayerId(report["committed"]["effect"].as_u64().unwrap());
execute(&mut s, "path.edit", &json!({"effect": effect.0, "index": 0})).unwrap();
let smooth_pixels = s.doc.pixels.clone();
let history = s.history_labels().len();
assert!(s.paths(effect).unwrap()[0].corners.is_empty());
assert!(execute(&mut s, "path.corner", &json!({"index": 3})).is_err(), "no such point");
assert!(execute(&mut s, "path.corner", &json!({})).is_err(), "no point selected");
let report = execute(&mut s, "path.corner", &json!({"index": 1})).unwrap();
assert_eq!(report["corner"], true);
assert_eq!(s.paths(effect).unwrap()[0].corners, vec![false, true, false]);
assert_ne!(s.doc.pixels.layers, smooth_pixels.layers, "the sharp turn repaints the path");
let corner_pixels = s.doc.pixels.clone();
assert_eq!(s.history_labels().len(), history + 1);
// Saved: the flags survive a project round trip
let saved = serde_json::to_string(&s.doc.project).unwrap();
let loaded: texturecraft_engine::core::Project = serde_json::from_str(&saved).unwrap();
s.doc.project = loaded;
assert_eq!(s.paths(effect).unwrap()[0].corners, vec![false, true, false]);
// One undo returns to the smooth curve and its pixels, one redo to the corner
execute(&mut s, "edit.undo", &Value::Null).unwrap();
assert!(s.tool.path.corners.is_empty() && !s.tool.path.is_corner(1));
assert!(s.paths(effect).unwrap()[0].corners.is_empty());
assert_eq!(s.doc.pixels.layers, smooth_pixels.layers);
execute(&mut s, "edit.redo", &Value::Null).unwrap();
assert_eq!(s.paths(effect).unwrap()[0].corners, vec![false, true, false]);
assert_eq!(s.doc.pixels.layers, corner_pixels.layers);
// The selected point toggles back to smooth; the stored flags are empty again
s.select_path_point(1);
let report = execute(&mut s, "path.corner", &json!({})).unwrap();
assert_eq!(report["corner"], false);
assert!(s.paths(effect).unwrap()[0].corners.is_empty(), "an all-smooth path is stored like an old one");
assert_eq!(s.doc.pixels.layers, smooth_pixels.layers);
}
/// Inserting and removing points keeps the corner flags on their points
#[test]
fn corner_flags_follow_their_points_when_points_are_inserted_or_removed() {
let mut s = session(wall());
execute(&mut s, "tool.path", &json!({"uvPoints": [[0.2, 0.2], [0.5, 0.8], [0.8, 0.2]], "corners": [false, true, false]})).unwrap();
s.insert_path_corner(1, Vec3::new(0.35, 0.5, 0.0)).unwrap();
assert_eq!(s.tool.path.corner_flags(), vec![false, true, true, false]);
s.insert_path_point(0, Vec3::new(0.1, 0.1, 0.0)).unwrap();
assert_eq!(s.tool.path.corner_flags(), vec![false, false, true, true, false]);
s.select_path_point(2);
s.remove_selected_path_point();
assert_eq!(s.tool.path.corner_flags(), vec![false, false, true, false]);
s.append_path_point(Vec3::new(0.9, 0.9, 0.0), true).unwrap();
assert_eq!(s.tool.path.corner_flags(), vec![false, false, true, false, false]);
assert!(s.toggle_selected_path_corner(), "the appended point is selected");
assert_eq!(s.tool.path.corner_flags(), vec![false, false, true, false, true]);
// Undo steps through each change with its flags
execute(&mut s, "edit.undo", &Value::Null).unwrap();
assert_eq!(s.tool.path.corner_flags(), vec![false, false, true, false, false]);
}
/// A path saved before corner points existed has no `corners` key: it loads smooth and unchanged
#[test]
fn paths_saved_without_corner_flags_load_smooth() {
let mut s = session(wall());
let report = execute(&mut s, "tool.path", &json!({"uvPoints": [[0.2, 0.2], [0.5, 0.8], [0.8, 0.2]], "commit": true})).unwrap();
let effect = texturecraft_engine::core::LayerId(report["committed"]["effect"].as_u64().unwrap());
let stored = s.paths(effect).unwrap()[0].clone();
let mut json = serde_json::to_value(&stored).unwrap();
assert!(json.get("corners").is_none(), "a smooth path writes the same JSON as before");
json.as_object_mut().unwrap().remove("corners");
let old: texturecraft_engine::core::PathShape = serde_json::from_value(json).unwrap();
assert_eq!(old, stored);
let pixels = s.doc.pixels.clone();
execute(&mut s, "path.edit", &json!({"effect": effect.0, "index": 0})).unwrap();
assert!(s.tool.path.corners.is_empty());
assert!(!s.path_live().unwrap(), "a loaded smooth path matches what is stored");
assert_eq!(s.doc.pixels.layers, pixels.layers);
}
+152
View File
@@ -0,0 +1,152 @@
//! Solo: a view-only preview of one layer. The composite shows that layer alone (optionally at
//! full coverage); saving, exporting and the history never see it.
use serde_json::{Value, json};
use texturecraft_engine::core::{Channel, LayerId};
use texturecraft_engine::geom::primitives;
use texturecraft_engine::{Session, Solo, execute};
fn session() -> Session {
let mut s = Session::new_project("t", primitives::sphere(1.0, 48, 24), "builtin:sphere", None, 128).unwrap();
s.update();
s
}
fn add_fill(s: &mut Session, color: [f32; 3], roughness: f32) -> LayerId {
let r = execute(s, "layer.add.fill", &json!({"color": color, "roughness": roughness})).unwrap();
LayerId(r["layer"].as_u64().unwrap())
}
/// A red fill below a green fill that a black mask hides everywhere, and the green one.
fn masked_stack() -> (Session, LayerId, LayerId) {
let mut s = session();
let red = add_fill(&mut s, [1.0, 0.0, 0.0], 0.2);
let green = add_fill(&mut s, [0.0, 1.0, 0.0], 0.8);
execute(&mut s, "mask.add.black", &json!({"layer": green.0})).unwrap();
s.update();
(s, red, green)
}
/// A texel the mesh covers.
fn covered(s: &Session) -> (u32, u32) {
let g = &s.caches[0].gbuf;
let i = g.tri.iter().position(|t| *t != texturecraft_engine::geom::NO_TRI).unwrap();
(i as u32 % g.width, i as u32 / g.width)
}
fn base(s: &mut Session) -> [f32; 3] {
s.update();
let (x, y) = covered(s);
s.caches[0].composite.value(Channel::BaseColor, x, y)
}
fn close(a: [f32; 3], b: [f32; 3]) -> bool {
(0..3).all(|i| (a[i] - b[i]).abs() < 2e-3)
}
#[test]
fn solo_shows_only_that_layer_and_ignoring_the_mask_shows_it_everywhere() {
let (mut s, red, green) = masked_stack();
assert!(close(base(&mut s), [1.0, 0.0, 0.0]), "the black mask hides the green layer");
s.set_solo(Some(Solo { layer: green, ignore_mask: false }));
assert!(close(base(&mut s), Channel::BaseColor.default_value()), "alone and masked away: nothing is left");
s.set_solo(Some(Solo { layer: green, ignore_mask: true }));
assert!(close(base(&mut s), [0.0, 1.0, 0.0]), "the mask is ignored: the whole material shows");
s.set_solo(Some(Solo { layer: red, ignore_mask: true }));
assert!(close(base(&mut s), [1.0, 0.0, 0.0]), "the other layer alone");
}
#[test]
fn the_solo_composite_equals_the_layer_alone_without_its_mask() {
let (mut s, _, green) = masked_stack();
s.set_solo(Some(Solo { layer: green, ignore_mask: true }));
s.update();
// The same layer in a project of its own, without mask and without the layer below
let mut alone = session();
add_fill(&mut alone, [0.0, 1.0, 0.0], 0.8);
alone.update();
assert!(s.caches[0].composite == alone.caches[0].composite, "every channel, every texel");
}
#[test]
fn the_solo_changes_neither_the_document_nor_the_history_nor_the_saved_file() {
let (mut s, _, green) = masked_stack();
let (project, labels, saved) =
(s.doc.project.clone(), s.history_labels(), Session::from_project_bytes(&s.to_project_bytes().unwrap()).unwrap().doc.project);
s.set_solo(Some(Solo { layer: green, ignore_mask: true }));
s.update();
assert_eq!(s.doc.project, project);
assert_eq!(s.history_labels(), labels);
assert_eq!(Session::from_project_bytes(&s.to_project_bytes().unwrap()).unwrap().doc.project, saved, "the file holds every layer and the mask");
}
#[test]
fn exports_hold_the_whole_stack_while_a_layer_is_soloed_and_the_solo_stays() {
let (mut s, _, green) = masked_stack();
let opts = texturecraft_engine::file_cmds::export_options(&s, &json!({"preset": "Document channels + Normal + AO", "format": "png"}), "t").unwrap();
let whole = s.export_files(&[0], &opts).unwrap();
s.set_solo(Some(Solo { layer: green, ignore_mask: true }));
s.update();
let revision = s.caches[0].revision;
let soloed = s.export_files(&[0], &opts).unwrap();
assert_eq!(s.pending_tiles(), 0, "export leaves the viewport cache ready to draw");
assert_eq!(s.caches[0].revision, revision);
assert_eq!(soloed.len(), whole.len());
assert!(soloed.iter().zip(&whole).all(|(a, b)| a.name == b.name && a.bytes == b.bytes), "the files are the whole stack's");
assert_eq!(s.solo, Some(Solo { layer: green, ignore_mask: true }), "the view keeps showing the solo");
assert!(close(base(&mut s), [0.0, 1.0, 0.0]), "and the viewport composite is the solo again");
}
#[test]
fn turning_the_solo_off_restores_the_original_composite() {
let (mut s, _, green) = masked_stack();
let before = s.caches[0].composite.clone();
s.set_solo(Some(Solo { layer: green, ignore_mask: true }));
s.update();
assert!(s.caches[0].composite != before);
s.set_solo(None);
s.update();
assert!(s.caches[0].composite == before);
}
#[test]
fn edits_while_soloed_show_in_the_solo_and_in_the_whole_stack_afterwards() {
let (mut s, red, _) = masked_stack();
s.set_solo(Some(Solo { layer: red, ignore_mask: false }));
s.update();
execute(&mut s, "layer.fill.set", &json!({"layer": red.0, "channel": "baseColor", "color": [0.0, 0.0, 1.0]})).unwrap();
assert!(close(base(&mut s), [0.0, 0.0, 1.0]), "the edited layer, alone");
s.set_solo(None);
assert!(close(base(&mut s), [0.0, 0.0, 1.0]), "the stack still hides the green layer behind its mask: blue shows");
}
#[test]
fn removing_the_soloed_layer_ends_the_solo() {
let (mut s, _, green) = masked_stack();
s.set_solo(Some(Solo { layer: green, ignore_mask: true }));
execute(&mut s, "layer.remove", &json!({"layer": green.0})).unwrap();
s.update();
assert_eq!(s.solo, None);
assert!(close(base(&mut s), [1.0, 0.0, 0.0]), "the whole stack again");
}
#[test]
fn the_view_solo_command_sets_reports_and_ends_the_solo() {
let (mut s, _, green) = masked_stack();
let r = execute(&mut s, "view.solo", &json!({"layer": green.0, "ignoreMask": true})).unwrap();
assert_eq!(r, json!({"layer": green.0, "ignoreMask": true}));
assert_eq!(texturecraft_engine::inspect::session(&s)["solo"], json!({"layer": green.0, "ignoreMask": true}));
// The selected layer is the default
execute(&mut s, "view.solo", &json!({"layer": null})).unwrap();
assert_eq!(s.solo, None);
execute(&mut s, "layer.select", &json!({"layer": green.0})).unwrap();
let r = execute(&mut s, "view.solo", &json!({})).unwrap();
assert_eq!(r, json!({"layer": green.0, "ignoreMask": false}));
assert!(execute(&mut s, "view.solo", &json!({"layer": 999_999})).is_err());
assert_eq!(texturecraft_engine::inspect::session(&s)["solo"]["layer"], json!(green.0));
execute(&mut s, "view.solo", &json!({"layer": null})).unwrap();
assert_eq!(texturecraft_engine::inspect::session(&s)["solo"], Value::Null);
}
+172 -1
View File
@@ -1,6 +1,6 @@
//! Symmetry around a moved plane or axis, driven through engine commands the way agents paint
use serde_json::json;
use serde_json::{Value, json};
use texturecraft_engine::core::Channel;
use texturecraft_engine::geom::glam::{Vec2, Vec3, Vec4};
use texturecraft_engine::geom::{Mesh, primitives};
@@ -281,3 +281,174 @@ fn disabling_symmetry_paints_only_the_source_and_keeps_the_settings() {
assert_eq!(session.tool.brush.symmetry, settings);
}
}
/// Base color of the composite at the surface point under world `point`
fn color_at(session: &Session, point: Vec3) -> [f32; 3] {
let hit = session.pick(screen(session, point), session.viewport).unwrap();
session.caches[0].composite.value(Channel::BaseColor, (hit.uv.x * TEXTURE_SIZE) as u32, (hit.uv.y * TEXTURE_SIZE) as u32)
}
/// A red dab at `x` (and its mirror image with symmetry on), then a smudge stroke from `x` along `step` pixels per sample. Returns the strokes' surface points
fn smudge_a_red_dab(session: &mut Session, symmetry: bool, x: f32, step: f32) -> (Vec3, Vec3) {
execute(session, "tool.brush", &json!({"size": 12, "hardness": 90, "symmetryX": symmetry})).unwrap();
execute(session, "tool.stroke", &json!({"points": [[x, 200.0]]})).unwrap();
session.update();
let (dragged_to, mirrored_to) = (surface(session, x + 35.0 * step, 200.0), surface(session, 400.0 - x - 35.0 * step, 200.0));
execute(session, "tool.smudge", &Value::Null).unwrap();
execute(session, "tool.brush", &json!({"size": 10, "smudgeStrength": 100, "spacing": 5})).unwrap();
let points: Vec<[f32; 2]> = (0..=40).map(|i| [x + i as f32 * step, 200.0]).collect();
execute(session, "tool.stroke", &json!({"points": points})).unwrap();
session.update();
(dragged_to, mirrored_to)
}
#[test]
fn smudge_drags_the_mirrored_spot_equally() {
let mut session = session(primitives::cube(2.0));
let (right, left) = smudge_a_red_dab(&mut session, true, 240.0, 1.0);
assert!(right.x > 0.0 && left.x < 0.0 && (right.x + left.x).abs() < 1e-3, "{right:?} {left:?}");
let (on_source, on_copy) = (color_at(&session, right), color_at(&session, left));
assert!(on_source[0] - on_source[1] > 0.2, "the stroke drags red along +X: {on_source:?}");
for channel in 0..3 {
assert!((on_source[channel] - on_copy[channel]).abs() < 0.1, "the copy drags the same on -X: {on_source:?} vs {on_copy:?}");
}
}
#[test]
fn smudge_without_symmetry_leaves_the_mirrored_spot_alone() {
let mut session = session(primitives::cube(2.0));
let (right, left) = smudge_a_red_dab(&mut session, false, 240.0, 1.0);
let (on_source, on_far_side) = (color_at(&session, right), color_at(&session, left));
assert!(on_source[0] - on_source[1] > 0.2, "the stroke drags red along +X: {on_source:?}");
assert!(on_far_side[0] - on_far_side[1] < 0.05, "nothing on the mirrored spot: {on_far_side:?}");
}
/// Is the composite red at texture coordinate `uv`?
fn red_at_uv(session: &Session, uv: Vec2) -> bool {
let color = session.caches[0].composite.value(Channel::BaseColor, (uv.x * TEXTURE_SIZE) as u32, (uv.y * TEXTURE_SIZE) as u32);
color[0] > 0.85 && color[1] < 0.15
}
/// Texture coordinate of the surface a ray from `from` along `direction` hits first
fn uv_hit(session: &Session, from: Vec3, direction: Vec3) -> Vec2 {
let hit = session.bvh.closest(from, direction, f32::MAX).unwrap();
texturecraft_engine::geom::surface_at(&session.mesh, hit.tri, hit.u, hit.v).unwrap().uv
}
/// A stroke of one dab in the 2D view at `uv`
fn dab_uv(session: &mut Session, uv: Vec2) {
execute(session, "tool.strokeUv", &json!({"points": [[uv.x, uv.y]]})).unwrap();
session.update();
}
#[test]
fn a_2d_dab_paints_its_copy_where_the_3d_stroke_paints_it() {
let brush = json!({"size": 1, "symmetryX": true, "symmetryOffset": [0.25, 0.0, 0.0]});
// Paint one surface point in the 3D view
let mut in_3d = session(wall());
execute(&mut in_3d, "tool.brush", &brush).unwrap();
let hit = in_3d.pick(Vec2::new(300.0, 200.0), in_3d.viewport).unwrap();
execute(&mut in_3d, "tool.stroke", &json!({"points": [[300, 200]]})).unwrap();
in_3d.update();
// Paint its UV in the 2D view
let mut in_2d = session(wall());
execute(&mut in_2d, "tool.brush", &brush).unwrap();
dab_uv(&mut in_2d, hit.uv);
let mirrored = Vec3::new(0.5 - hit.pos.x, hit.pos.y, hit.pos.z);
for (name, session) in [("3D", &in_3d), ("2D", &in_2d)] {
assert!(red_at(session, hit.pos), "the dab in {name}");
assert!(red_at(session, mirrored), "its copy across x = 0.25 in {name}");
assert!(!red_at(session, Vec3::new(-hit.pos.x, hit.pos.y, hit.pos.z)), "nothing across the mesh center in {name}");
}
}
#[test]
fn a_2d_dab_on_the_cube_paints_the_opposite_face() {
let mut session = session(primitives::cube(2.0));
execute(&mut session, "tool.brush", &json!({"size": 1, "symmetryX": true})).unwrap();
let right = uv_hit(&session, Vec3::new(5.0, 0.3, 0.2), Vec3::NEG_X);
dab_uv(&mut session, right);
assert!(red_at_uv(&session, right), "the dab");
assert!(red_at_uv(&session, uv_hit(&session, Vec3::new(-5.0, 0.3, 0.2), Vec3::X)), "its copy on the left face, at the mirrored point");
assert!(!red_at_uv(&session, uv_hit(&session, Vec3::new(-5.0, -0.3, 0.2), Vec3::X)), "not elsewhere on the left face");
assert!(!red_at_uv(&session, uv_hit(&session, Vec3::new(0.3, 5.0, 0.2), Vec3::NEG_Y)), "not on the top face");
}
#[test]
fn a_2d_dab_with_four_radial_copies_paints_three_more() {
let mut session = session(wall());
execute(&mut session, "tool.brush", &json!({"size": 1, "symmetryRadial": 4, "symmetryAxis": "z"})).unwrap();
let hit = session.pick(Vec2::new(290.0, 160.0), session.viewport).unwrap();
dab_uv(&mut session, hit.uv);
let at = hit.pos;
assert!(red_at(&session, at), "the dab");
for (name, point) in
[("a quarter turn", Vec3::new(-at.y, at.x, 0.0)), ("a half turn", Vec3::new(-at.x, -at.y, 0.0)), ("three quarters", Vec3::new(at.y, -at.x, 0.0))]
{
assert!(red_at(&session, point), "the copy {name} around Z");
}
assert!(!red_at(&session, Vec3::new(at.x, -at.y, 0.0)), "no mirrored copy");
let painted = (0..TEXTURE_SIZE as u32).flat_map(|y| (0..TEXTURE_SIZE as u32).map(move |x| (x, y))).filter(|&(x, y)| {
let color = session.caches[0].composite.value(Channel::BaseColor, x, y);
color[0] - color[1] > PAINTED_TINT
});
let mut blobs: Vec<(u32, u32)> = Vec::new();
for (x, y) in painted {
if !blobs.iter().any(|&(bx, by)| bx.abs_diff(x) < 16 && by.abs_diff(y) < 16) {
blobs.push((x, y));
}
}
assert_eq!(blobs.len(), 4, "the dab and three copies, no more");
}
#[test]
fn a_2d_dab_paints_no_copy_with_symmetry_off() {
let mut session = session(wall());
let hit = session.pick(Vec2::new(300.0, 200.0), session.viewport).unwrap();
let mirrored = Vec3::new(-hit.pos.x, hit.pos.y, hit.pos.z);
execute(&mut session, "tool.brush", &json!({"size": 1})).unwrap();
dab_uv(&mut session, hit.uv);
assert!(red_at(&session, hit.pos), "the dab");
assert!(!red_at(&session, mirrored), "no copy without symmetry");
// The toolbar toggle off keeps the settings but paints no copies
execute(&mut session, "tool.brush", &json!({"symmetryX": true, "symmetryOn": false})).unwrap();
dab_uv(&mut session, hit.uv);
assert!(!red_at(&session, mirrored), "no copy with the toggle off");
}
#[test]
fn a_2d_smudge_with_symmetry_drags_both_sides_alike_at_the_mirror_plane() {
let mut session = session(wall());
let uv = |session: &Session, x: f32| uv_hit(session, Vec3::new(x, 0.0, 5.0), Vec3::NEG_Z);
let color = |session: &Session, uv: Vec2| session.caches[0].composite.value(Channel::BaseColor, (uv.x * TEXTURE_SIZE) as u32, (uv.y * TEXTURE_SIZE) as u32);
// A red dab next to the mirror plane (and its copy on the other side), then a smudge away from the plane
execute(&mut session, "tool.brush", &json!({"size": 6, "hardness": 90, "symmetryX": true})).unwrap();
let start = uv(&session, 0.05);
dab_uv(&mut session, start);
execute(&mut session, "tool.smudge", &Value::Null).unwrap();
execute(&mut session, "tool.brush", &json!({"size": 6, "smudgeStrength": 100, "spacing": 5})).unwrap();
let end = uv(&session, 0.4);
let points: Vec<[f32; 2]> = (0..=40).map(|i| start + (end - start) * (i as f32 / 40.0)).map(|p| [p.x, p.y]).collect();
execute(&mut session, "tool.strokeUv", &json!({"points": points})).unwrap();
session.update();
// The copies overlap at the plane; each drags its own trail, so both sides end up mirror images
let dragged = color(&session, uv(&session, 0.2));
assert!(dragged[0] - dragged[1] > 0.1, "the smudge drags red away from the plane: {dragged:?}");
for x in [0.01, 0.03, 0.05, 0.08, 0.12, 0.2, 0.3] {
let (right, left) = (color(&session, uv(&session, x)), color(&session, uv(&session, -x)));
for channel in 0..3 {
assert!((right[channel] - left[channel]).abs() < 0.03, "x = ±{x}: {right:?} vs {left:?}");
}
}
}
@@ -56,16 +56,13 @@ impl Selection {
/// Whether the shelf offers `tool` for this selection
pub(super) fn offers(self, tool: Tool) -> bool {
let reads_content = matches!(tool, Tool::Smudge | Tool::Clone);
match tool {
Tool::ColorPicker => true,
Tool::GeometryMask => !matches!(self, Selection::Nothing | Selection::QuickMaskOverNothing),
_ => match self {
Selection::PaintContent | Selection::PaintSublayer => true,
Selection::PaintSublayerInFill => tool != Tool::Path,
Selection::PaintMask | Selection::FillMask | Selection::FolderMask | Selection::InstanceOwnMask | Selection::PaintSublayerInMask => {
!reads_content
}
Selection::PaintMask | Selection::FillMask | Selection::FolderMask | Selection::InstanceOwnMask | Selection::PaintSublayerInMask => true,
Selection::PathSublayer => tool == Tool::Path,
Selection::QuickMaskOverPaint | Selection::QuickMaskOverFill | Selection::QuickMaskOverNothing => tool != Tool::Path,
_ => false,
+150
View File
@@ -0,0 +1,150 @@
//! Brush, symmetry and other tool settings outlive the project; what belongs to a project does not
use serde_json::json;
use texturecraft_engine::geom::glam::Vec3;
use texturecraft_engine::paint::BrushAlpha;
use texturecraft_engine::{CloneFrom, CloneSource, Session, ToolSettings, execute, sample_session};
fn another_project() -> Session {
sample_session(128, 64).unwrap()
}
fn import_image(session: &mut Session, file: &str) -> String {
let mut png_bytes = Vec::new();
let image = image::RgbaImage::from_fn(4, 4, |_, _| image::Rgba([200, 100, 50, 255]));
image.write_to(&mut std::io::Cursor::new(&mut png_bytes), image::ImageFormat::Png).unwrap();
session.import_resource_bytes(file, png_bytes).unwrap()
}
/// A session with every kind of tool setting changed from its default
fn tuned() -> Session {
let mut session = another_project();
execute(
&mut session,
"tool.brush",
&json!({
"size": 33, "hardness": 80, "flow": 40, "angle": 15, "spacing": 30, "alpha": "star",
"symmetryOn": true, "symmetryX": true, "symmetryY": false, "symmetryZ": true,
"symmetryRadial": 8, "symmetryAxis": "x", "symmetryOffset": [0.1, 0.0, 0.2],
"smudgeStrength": 80, "cloneSource": "layer", "cloneAligned": false,
}),
)
.unwrap();
session.tool.path.closed = true;
session.tool.path.fill = true;
session
}
#[test]
fn opening_another_project_keeps_the_brush_symmetry_and_tool_settings() {
let mut session = tuned();
let before = session.tool.clone();
session.switch_to(another_project());
assert_eq!(session.tool.brush, before.brush);
assert_eq!(session.tool.brush.alpha, BrushAlpha::Star);
assert!(session.tool.brush.symmetry.x && session.tool.brush.symmetry.z && !session.tool.brush.symmetry.y);
assert_eq!(session.tool.smudge_strength, 0.8);
assert_eq!(session.tool.clone_from, CloneFrom::Layer);
assert!(!session.tool.clone_aligned, "the Clone tool's Aligned switch is kept too");
assert!(session.tool.path.closed && session.tool.path.fill);
}
#[test]
fn a_project_loaded_from_a_file_gets_the_tool_settings_too() {
let mut session = tuned();
let before_size = session.tool.brush.size;
let bytes = another_project().to_project_bytes().unwrap();
session.switch_to(Session::from_project_bytes(&bytes).unwrap());
assert_ne!(session.tool.brush.size, another_project().tool.brush.size);
assert_eq!(session.tool.brush.size, before_size);
assert_eq!(session.tool.smudge_strength, 0.8);
}
#[test]
fn what_belongs_to_the_old_project_is_reset() {
let mut session = tuned();
let before_size = session.tool.brush.size;
let image = import_image(&mut session, "stamp.png");
execute(&mut session, "tool.brush", &json!({"alpha": {"image": image.clone()}})).unwrap();
execute(&mut session, "tool.stencil", &json!({"image": image, "scale": 2.0, "rotation": 30, "tile": true, "opacity": 0.9})).unwrap();
session.tool.clone_source = Some(CloneSource { uv: [0.3, 0.4], offset: Some([0.1, 0.1]) });
session.tool.path.push(Vec3::new(1.0, 2.0, 3.0), false);
session.switch_to(another_project());
assert_eq!(session.tool.clone_source, None);
assert_eq!(session.tool.stencil, None);
assert_eq!(session.tool.brush.alpha_image, None);
assert!(session.tool.path.points.is_empty());
// The rest of the brush came along
assert_ne!(session.tool.brush.size, another_project().tool.brush.size);
assert_eq!(session.tool.brush.size, before_size);
}
#[test]
fn the_stencil_placement_carries_over_to_the_next_stencil() {
let mut session = another_project();
let image = import_image(&mut session, "stamp.png");
execute(&mut session, "tool.stencil", &json!({"image": image, "scale": 2.0, "rotation": 30, "tile": true, "opacity": 0.9})).unwrap();
session.switch_to(another_project());
let image = import_image(&mut session, "other.png");
execute(&mut session, "tool.stencil", &json!({"image": image})).unwrap();
let stencil = session.tool.stencil.as_ref().unwrap();
assert_eq!((stencil.scale, stencil.rotation, stencil.tile, stencil.opacity), (2.0, 30.0, true, 0.9));
}
#[test]
fn clearing_the_stencil_keeps_its_placement_for_the_next_one() {
let mut session = another_project();
let image = import_image(&mut session, "stamp.png");
execute(&mut session, "tool.stencil", &json!({"image": image.clone(), "scale": 2.0})).unwrap();
execute(&mut session, "tool.stencil", &json!({"clear": true})).unwrap();
execute(&mut session, "tool.stencil", &json!({"image": image})).unwrap();
assert_eq!(session.tool.stencil.as_ref().unwrap().scale, 2.0);
}
#[test]
fn settings_survive_json_and_apply_to_a_fresh_tool() {
let session = tuned();
let saved = ToolSettings::of(&session.tool);
let loaded: ToolSettings = serde_json::from_str(&serde_json::to_string(&saved).unwrap()).unwrap();
let mut fresh = another_project();
loaded.apply(&mut fresh.tool);
assert_eq!(ToolSettings::of(&fresh.tool), saved);
assert_eq!(fresh.tool.brush.size, session.tool.brush.size);
}
#[test]
fn settings_saved_before_the_clone_aligned_switch_load_with_it_on() {
let mut saved = serde_json::to_value(ToolSettings::of(&tuned().tool)).unwrap();
saved.as_object_mut().unwrap().remove("clone_aligned");
let loaded: ToolSettings = serde_json::from_value(saved).unwrap();
assert!(loaded.clone_aligned);
}
#[test]
fn restored_stencil_and_smudge_settings_use_the_tool_limits() {
let mut session = another_project();
let mut settings = ToolSettings::default();
settings.smudge_strength = 2.0;
settings.stencil.center = [-20.0, 30.0];
settings.stencil.opacity = -1.0;
settings.stencil.scale = 0.0;
settings.stencil.rotation = -15.0;
settings.apply(&mut session.tool);
assert_eq!(session.tool.smudge_strength, 1.0);
let look = session.tool.stencil_look;
assert_eq!((look.center, look.scale, look.opacity, look.rotation), ([-4.0, 4.0], 0.01, 0.0, 345.0));
}
+214 -4
View File
@@ -53,15 +53,93 @@ fn clone_copies_values_from_the_source_offset() {
dab(&mut s, 240.0, 200.0);
let v = color_at(&s, 240.0, 200.0);
assert!(red(v), "cloned red: {v:?}");
// The offset stays for the next strokes: the source moved along with the destination.
// The offset stays for the next strokes: the source moved along with the destination
let off = s.tool.clone_source.unwrap().offset.unwrap();
assert!(off[0].abs() > 0.01, "{off:?}");
// One undo step per clone stroke.
// One undo step per clone stroke
execute(&mut s, "edit.undo", &Value::Null).unwrap();
s.update();
assert!(!red(color_at(&s, 240.0, 200.0)));
}
/// A red dab at (160, 200) as the clone source, the Clone tool selected with a small brush.
fn clone_ready() -> Session {
let mut s = session();
paint_red(&mut s, 20.0);
dab(&mut s, 160.0, 200.0);
execute(&mut s, "tool.clone", &Value::Null).unwrap();
execute(&mut s, "tool.cloneSource", &json!({"x": 160, "y": 200})).unwrap();
execute(&mut s, "tool.brush", &json!({"size": 6})).unwrap();
s
}
#[test]
fn aligned_clone_keeps_the_first_offset_for_later_strokes() {
let mut s = clone_ready();
assert_eq!(execute(&mut s, "tool.brush", &Value::Null).unwrap()["cloneAligned"], true, "aligned by default");
dab(&mut s, 240.0, 200.0);
assert!(red(color_at(&s, 240.0, 200.0)));
// The second stroke reads at the same offset, 40 points left of the first source: nothing red there
dab(&mut s, 200.0, 200.0);
assert!(!red(color_at(&s, 200.0, 200.0)), "aligned: the source moved along");
assert!(s.tool.clone_source.unwrap().offset.is_some());
}
#[test]
fn not_aligned_clone_starts_every_stroke_at_the_source() {
let mut s = clone_ready();
let r = execute(&mut s, "tool.brush", &json!({"cloneAligned": false})).unwrap();
assert_eq!(r["cloneAligned"], false);
dab(&mut s, 240.0, 200.0);
assert!(red(color_at(&s, 240.0, 200.0)), "first stroke copies the source");
assert!(s.tool.clone_source.unwrap().offset.is_none(), "no offset is kept");
dab(&mut s, 200.0, 200.0);
assert!(red(color_at(&s, 200.0, 200.0)), "the second stroke starts at the source again");
}
#[test]
fn switching_the_clone_mode_forgets_the_offset_of_earlier_strokes() {
let mut s = clone_ready();
dab(&mut s, 240.0, 200.0);
assert!(s.tool.clone_source.unwrap().offset.is_some());
execute(&mut s, "tool.brush", &json!({"cloneAligned": false})).unwrap();
execute(&mut s, "tool.brush", &json!({"cloneAligned": true})).unwrap();
assert!(s.tool.clone_source.unwrap().offset.is_none(), "the next aligned stroke fixes a fresh offset");
}
#[test]
fn the_clone_source_is_forgotten_when_another_texture_set_becomes_active() {
let mut s = texturecraft_engine::sample_session(256, 64).unwrap();
execute(&mut s, "tool.clone", &Value::Null).unwrap();
execute(&mut s, "tool.cloneSource", &json!({"uv": [0.3, 0.6]})).unwrap();
// Selecting the active set again keeps it
let active = s.ts();
execute(&mut s, "textureSet.select", &json!({"ts": active})).unwrap();
assert!(s.tool.clone_source.is_some());
execute(&mut s, "textureSet.select", &json!({"ts": 1})).unwrap();
assert!(s.tool.clone_source.is_none(), "a point of set 0 means nothing in set 1");
assert!(execute(&mut s, "tool.stroke", &json!({"points": [[200, 200]]})).is_err(), "asks for a source again");
// The same through selecting a layer that lives in another set
let other = s.doc.project.texture_sets[0].stack.last().copied().expect("set 0 has a layer");
execute(&mut s, "tool.cloneSource", &json!({"uv": [0.3, 0.6]})).unwrap();
execute(&mut s, "layer.select", &json!({"layer": other.0})).unwrap();
assert_eq!(s.ts(), 0);
assert!(s.tool.clone_source.is_none());
execute(&mut s, "tool.cloneSource", &json!({"uv": [0.3, 0.6]})).unwrap();
execute(&mut s, "layer.select", &json!({"layers": [other.0]})).unwrap();
assert!(s.tool.clone_source.is_some());
let layers = s.doc.project.texture_sets[1].stack.clone();
execute(&mut s, "layer.select", &json!({"layers": layers})).unwrap();
assert_eq!(s.ts(), 1);
assert!(s.tool.clone_source.is_none());
}
#[test]
fn smudge_drags_color_along_the_stroke() {
let mut s = session();
@@ -77,6 +155,21 @@ fn smudge_drags_color_along_the_stroke() {
assert!(after[0] - before[0] > 0.2 && after[1] < before[1], "red dragged right: {before:?} -> {after:?}");
}
#[test]
fn smudge_leaves_a_channel_alone_that_the_material_has_off() {
let mut s = session();
paint_red(&mut s, 12.0);
dab(&mut s, 170.0, 200.0);
let before = color_at(&s, 205.0, 200.0);
execute(&mut s, "tool.material", &json!({"channel": "baseColor", "enabled": false})).unwrap();
execute(&mut s, "tool.smudge", &Value::Null).unwrap();
execute(&mut s, "tool.brush", &json!({"size": 10, "smudgeStrength": 100, "spacing": 5})).unwrap();
let pts: Vec<[f32; 2]> = (0..=40).map(|i| [170.0 + i as f32, 200.0]).collect();
execute(&mut s, "tool.stroke", &json!({"points": pts})).unwrap();
let after = color_at(&s, 205.0, 200.0);
assert!((after[0] - before[0]).abs() < 0.02 && (after[1] - before[1]).abs() < 0.02, "base color not dragged: {before:?} -> {after:?}");
}
#[test]
fn image_alpha_shapes_the_stamp() {
let mut s = session();
@@ -273,7 +366,8 @@ fn stroke_after_undoing_mask_is_paint_stroke() {
s.update();
let undone = execute(&mut s, "edit.undo", &Value::Null).unwrap();
assert_eq!(undone["undone"], "Paint stroke", "the stroke after undoing the mask was recorded as {}", undone["undone"]);
let layer = s.doc.project.layer(s.selected_layer().unwrap()).unwrap().name.clone();
assert_eq!(undone["undone"], format!("Paint on {layer}"), "the stroke after undoing the mask was recorded as {}", undone["undone"]);
execute(&mut s, "edit.redo", &Value::Null).unwrap();
s.update();
@@ -300,5 +394,121 @@ fn undoing_after_painting_on_instance_source_mask_keeps_mask_target() {
execute(&mut s, "tool.stroke", &json!({"points": [[180, 180], [210, 200]]})).unwrap();
let undone = execute(&mut s, "edit.undo", &Value::Null).unwrap();
assert_eq!(undone["undone"], "Mask stroke");
let layer = s.doc.project.layer(s.selected_layer().unwrap()).unwrap().name.clone();
assert_eq!(undone["undone"], format!("Paint mask of {layer}"));
}
/// The name of the selected layer
fn selected_name(s: &Session) -> String {
s.doc.project.layer(s.selected_layer().unwrap()).unwrap().name.clone()
}
/// The label of the newest history step
fn last_label(s: &Session) -> String {
s.history_labels().pop().unwrap()
}
#[test]
fn strokes_are_named_by_tool_and_layer() {
let mut s = session();
execute(&mut s, "layer.rename", &json!({"name": "Rust"})).unwrap();
paint_red(&mut s, 20.0);
dab(&mut s, 160.0, 200.0);
assert_eq!(last_label(&s), "Paint on Rust");
execute(&mut s, "tool.clone", &Value::Null).unwrap();
execute(&mut s, "tool.cloneSource", &json!({"x": 160, "y": 200})).unwrap();
dab(&mut s, 240.0, 200.0);
assert_eq!(last_label(&s), "Clone on Rust");
execute(&mut s, "tool.smudge", &Value::Null).unwrap();
execute(&mut s, "tool.brush", &json!({"size": 10, "smudgeStrength": 100, "spacing": 5})).unwrap();
execute(&mut s, "tool.stroke", &json!({"points": [[150, 200], [200, 200], [250, 200]]})).unwrap();
assert_eq!(last_label(&s), "Smudge on Rust");
execute(&mut s, "tool.eraser", &Value::Null).unwrap();
dab(&mut s, 160.0, 200.0);
assert_eq!(last_label(&s), "Erase on Rust");
// Another layer gives another name
execute(&mut s, "layer.add.paint", &Value::Null).unwrap();
execute(&mut s, "layer.rename", &json!({"name": "Dust"})).unwrap();
execute(&mut s, "tool.paint", &Value::Null).unwrap();
dab(&mut s, 160.0, 200.0);
assert_eq!(last_label(&s), format!("Paint on {}", selected_name(&s)));
assert_eq!(selected_name(&s), "Dust");
}
#[test]
fn the_label_template_of_every_tool_is_listed_for_translation() {
use texturecraft_engine::{HISTORY_TEMPLATES, Tool, history_label, stroke_template};
for tool in Tool::ALL {
for on_mask in [false, true] {
let template = stroke_template(tool, on_mask);
assert!(HISTORY_TEMPLATES.contains(&template), "{template} is not in HISTORY_TEMPLATES");
assert!(history_label(template, "Rust").contains("Rust"));
}
}
assert_eq!(history_label("Paint on {layer}", "A {b}"), "Paint on A {b}");
}
/// Texels of base color red along a viewport row
fn red_width(s: &Session, y: f32) -> usize {
(100..300).filter(|x| s.pick(Vec2::new(*x as f32, y), s.viewport).is_some() && red(color_at(s, *x as f32, y))).count()
}
#[test]
fn brush_alpha_parameters_are_set_read_back_and_narrow_the_stamp() {
let mut full_session = session();
paint_red(&mut full_session, 30.0);
dab(&mut full_session, 200.0, 200.0);
let full = red_width(&full_session, 200.0);
assert!(full > 20, "{full}");
let mut s = session();
paint_red(&mut s, 30.0);
let brush = execute(&mut s, "tool.brush", &json!({"alphaSizeX": 50, "alphaRoundness": 0, "alphaContrast": 2.5, "alphaInvert": false})).unwrap();
assert_eq!((brush["alphaSizeX"].as_f64(), brush["alphaSizeY"].as_f64(), brush["alphaRoundness"].as_f64()), (Some(50.0), Some(100.0), Some(0.0)));
assert_eq!((brush["alphaContrast"].as_f64(), brush["alphaInvert"].as_bool()), (Some(2.5), Some(false)));
execute(&mut s, "tool.brush", &json!({"alphaRoundness": 100, "alphaContrast": 1})).unwrap();
dab(&mut s, 200.0, 200.0);
let narrow = red_width(&s, 200.0);
assert!(narrow > 5 && narrow * 10 < full * 7, "half the stamp width: {narrow} of {full}");
// Out-of-range values are clamped, not rejected
let brush = execute(&mut s, "tool.brush", &json!({"alphaSizeX": 0, "alphaContrast": 99})).unwrap();
assert_eq!((brush["alphaSizeX"].as_f64(), brush["alphaContrast"].as_f64()), (Some(5.0), Some(8.0)));
}
#[test]
fn brushes_saved_without_alpha_parameters_load_unchanged() {
use texturecraft_engine::paint::{AlphaParams, BrushSettings};
let mut saved = serde_json::to_value(BrushSettings::default()).unwrap();
assert!(saved.as_object_mut().unwrap().remove("alpha_params").is_some());
let loaded: BrushSettings = serde_json::from_value(saved.clone()).unwrap();
assert_eq!(loaded, BrushSettings::default());
saved["alpha_params"] = json!({"size_x": 0.5, "invert": true});
let partial: BrushSettings = serde_json::from_value(saved).unwrap();
assert_eq!(partial.alpha_params, AlphaParams { size_x: 0.5, invert: true, ..AlphaParams::default() });
}
#[test]
fn solo_keeps_the_document_source_for_clone_and_the_material_picker() {
let mut s = clone_ready();
let layer = s.selected_layer().unwrap();
let empty = execute(&mut s, "layer.add.paint", &json!({})).unwrap()["layer"].as_u64().unwrap();
execute(&mut s, "view.solo", &json!({"layer": empty})).unwrap();
execute(&mut s, "layer.select", &json!({"layer": layer.0})).unwrap();
s.update();
assert!(!red(color_at(&s, 160.0, 200.0)));
let picked = s.color_pick(Vec2::new(160.0, 200.0), s.viewport).unwrap();
assert!(red(picked[&Channel::BaseColor]));
dab(&mut s, 240.0, 200.0);
execute(&mut s, "view.solo", &json!({"layer": null})).unwrap();
s.update();
assert!(red(color_at(&s, 240.0, 200.0)));
}
+210
View File
@@ -0,0 +1,210 @@
//! A layer's mask saved as a user smart mask (`.tcmask`) and applied to other layers and projects.
use serde_json::{Value, json};
use texturecraft_engine::core::{Effect, EffectKind, LayerId, Source};
use texturecraft_engine::geom::primitives;
use texturecraft_engine::smart_masks::SMART_MASK_EXT;
use texturecraft_engine::{Session, execute};
use texturecraft_texel::TileImage;
fn session(resolution: u32) -> Session {
Session::new_project("t", primitives::sphere(1.0, 24, 12), "builtin:sphere", None, resolution).unwrap()
}
fn layer(s: &mut Session) -> LayerId {
LayerId(execute(s, "layer.add.fill", &Value::Null).unwrap()["layer"].as_u64().unwrap())
}
/// A mask with a generator, a filter, an image fill and painted pixels. Returns the layer and the image's name.
fn multi_effect_mask(s: &mut Session) -> (LayerId, String) {
let mut png = Vec::new();
image::RgbaImage::from_fn(8, 8, |x, y| image::Rgba([(x * 30) as u8, (y * 30) as u8, 90, 255]))
.write_to(&mut std::io::Cursor::new(&mut png), image::ImageFormat::Png)
.unwrap();
let name = s.import_resource_bytes("stencil.png", png).unwrap();
let id = layer(s);
execute(s, "mask.add.black", &json!({"layer": id.0})).unwrap();
execute(s, "effect.add.generator", &json!({"layer": id.0, "generator": "edgeWear"})).unwrap();
execute(s, "effect.add.filter", &json!({"layer": id.0, "target": "mask", "filter": "invert"})).unwrap();
let fill = execute(s, "effect.add.fill", &json!({"layer": id.0, "target": "mask"})).unwrap()["effect"].as_u64().unwrap();
let paint = execute(s, "effect.add.paint", &json!({"layer": id.0, "target": "mask"})).unwrap()["effect"].as_u64().unwrap();
let mask = s.doc.project.layer_mut(id).unwrap().mask.as_mut().unwrap();
for effect in &mut mask.effects {
if effect.id.0 == fill {
effect.kind = EffectKind::Fill { source: Source::image(&name), projection: Default::default() };
}
}
let size = s.doc.project.texture_set(0).unwrap().resolution;
let mut pixels = TileImage::new(size, size, 2);
pixels.set(10, 12, &[40000, 65535]);
s.doc.pixels.masks.insert(LayerId(paint), pixels);
(id, name)
}
/// The mask's effects without their ids (those are new in every project).
fn effects(s: &Session, layer: LayerId) -> Vec<Effect> {
s.doc.project.layer(layer).unwrap().mask.as_ref().unwrap().effects.iter().map(|effect| Effect { id: LayerId(0), ..effect.clone() }).collect()
}
fn painted(s: &Session, layer: LayerId) -> Vec<[u16; 4]> {
let mask = s.doc.project.layer(layer).unwrap().mask.as_ref().unwrap();
mask.effects.iter().filter(|effect| matches!(effect.kind, EffectKind::Paint)).map(|effect| s.doc.pixels.masks[&effect.id].get(10, 12)).collect()
}
#[test]
fn a_saved_mask_applies_to_another_layer_with_parameters_pixels_and_images() {
let mut s = session(256);
let (source, image) = multi_effect_mask(&mut s);
let bytes = s.smart_mask_bytes(source, "Worn stencil").unwrap();
let other = layer(&mut s);
execute(&mut s, "mask.add.white", &json!({"layer": other.0})).unwrap();
let before = s.doc.project.layers.len();
s.apply_smart_mask_bytes(other, &bytes).unwrap();
assert_eq!(effects(&s, other), effects(&s, source), "every effect keeps its type and parameters");
assert_eq!(painted(&s, other), painted(&s, source), "and the painted pixels");
assert_eq!(s.doc.project.layer(other).unwrap().mask.as_ref().unwrap().background, s.doc.project.layer(source).unwrap().mask.as_ref().unwrap().background);
assert_eq!(s.doc.project.layers.len(), before, "no layer is added");
let ids: Vec<_> = s.doc.project.layer(other).unwrap().mask.as_ref().unwrap().effects.iter().map(|effect| effect.id).collect();
assert!(ids.iter().all(|id| !s.doc.project.layer(source).unwrap().mask.as_ref().unwrap().effects.iter().any(|e| e.id == *id)), "the effects are new ones");
assert!(s.doc.resources.contains_key(&image));
s.doc.project.validate().unwrap();
execute(&mut s, "edit.undo", &Value::Null).unwrap();
assert_eq!(s.doc.project.layer(other).unwrap().mask.as_ref().unwrap().effects.len(), 0, "one undo step restores the old mask");
}
#[test]
fn a_saved_mask_applies_in_a_fresh_project_of_another_size() {
let mut s = session(256);
let (source, image) = multi_effect_mask(&mut s);
let bytes = s.smart_mask_bytes(source, "Worn stencil").unwrap();
let expected = effects(&s, source);
let mut fresh = session(128);
let target = layer(&mut fresh);
assert!(fresh.doc.resources.is_empty());
fresh.apply_smart_mask_bytes(target, &bytes).unwrap();
assert_eq!(effects(&fresh, target), expected);
assert_eq!(fresh.doc.resources.get(&image), s.doc.resources.get(&image), "the image arrives byte for byte");
assert!(fresh.images.contains_key(&image), "and is decoded for the mask to read");
let mask = fresh.doc.project.layer(target).unwrap().mask.as_ref().unwrap();
let paint = mask.effects.iter().find(|effect| matches!(effect.kind, EffectKind::Paint)).unwrap();
assert_eq!(fresh.doc.pixels.masks[&paint.id].width(), 128, "painted pixels are fitted to the project's size");
fresh.doc.project.validate().unwrap();
}
#[test]
fn the_commands_write_a_file_and_apply_it_by_path() {
let mut s = session(128);
let (source, _) = multi_effect_mask(&mut s);
let dir = std::env::temp_dir().join(format!("tc_user_smart_mask_{}", std::process::id()));
let path = dir.join("lib").join("worn");
let saved = execute(&mut s, "mask.smart.create", &json!({"layer": source.0, "path": path.display().to_string(), "name": "Worn"})).unwrap();
let file = dir.join("lib").join(format!("worn.{SMART_MASK_EXT}"));
assert_eq!(saved["path"], file.display().to_string(), "the extension is added and the folder made");
let other = layer(&mut s);
execute(&mut s, "mask.smart.apply", &json!({"layer": other.0, "path": file.display().to_string()})).unwrap();
assert_eq!(effects(&s, other), effects(&s, source));
std::fs::remove_dir_all(&dir).ok();
let plain = layer(&mut s);
assert!(execute(&mut s, "mask.smart.create", &json!({"layer": plain.0, "path": "unused"})).is_err(), "a layer without a mask has nothing to save");
assert!(execute(&mut s, "mask.smart.apply", &json!({"layer": plain.0, "path": file.display().to_string()})).is_err(), "a missing file changes nothing");
assert!(s.doc.project.layer(plain).unwrap().mask.is_none());
}
#[test]
fn a_file_without_a_mask_is_refused_and_a_disabled_mask_comes_back_on() {
let mut s = session(128);
let plain = layer(&mut s);
let material = s.smart_material_bytes(plain, "Plain").unwrap();
assert!(s.apply_smart_mask_bytes(plain, &material).is_err(), "a smart material file has no mask to take");
assert!(s.apply_smart_mask_bytes(plain, b"junk").is_err());
let (source, _) = multi_effect_mask(&mut s);
s.doc.project.layer_mut(source).unwrap().mask.as_mut().unwrap().enabled = false;
let bytes = s.smart_mask_bytes(source, "Off").unwrap();
s.apply_smart_mask_bytes(plain, &bytes).unwrap();
assert!(s.doc.project.layer(plain).unwrap().mask.as_ref().unwrap().enabled);
}
#[test]
fn an_image_name_the_project_uses_for_other_bytes_gets_a_new_name() {
let mut s = session(128);
let (source, image) = multi_effect_mask(&mut s);
let bytes = s.smart_mask_bytes(source, "Stencil").unwrap();
let mut other = session(128);
let mut png = Vec::new();
image::RgbaImage::from_fn(4, 4, |_, _| image::Rgba([1, 2, 3, 255])).write_to(&mut std::io::Cursor::new(&mut png), image::ImageFormat::Png).unwrap();
assert_eq!(other.import_resource_bytes("stencil.png", png).unwrap(), image);
let own = other.doc.resources[&image].clone();
let target = layer(&mut other);
other.apply_smart_mask_bytes(target, &bytes).unwrap();
assert_eq!(other.doc.resources[&image], own, "the project's own image is untouched");
let mask = other.doc.project.layer(target).unwrap().mask.as_ref().unwrap();
let read: Vec<&str> = mask.effects.iter().flat_map(|effect| effect.kind.images_read()).collect();
assert_eq!(read.len(), 1);
assert_ne!(read[0], image, "the mask reads its own image under another name");
assert_eq!(other.doc.resources[read[0]], s.doc.resources[&image]);
}
#[test]
fn effects_reading_an_anchor_of_the_mask_follow_it() {
let mut s = session(128);
let id = layer(&mut s);
let anchor = execute(&mut s, "effect.add.anchor", &json!({"layer": id.0, "target": "mask"})).unwrap()["effect"].as_u64().unwrap();
let fill = execute(&mut s, "effect.add.fill", &json!({"layer": id.0, "target": "mask"})).unwrap()["effect"].as_u64().unwrap();
let mask = s.doc.project.layer_mut(id).unwrap().mask.as_mut().unwrap();
for effect in &mut mask.effects {
if effect.id.0 == fill {
effect.kind = EffectKind::Fill {
source: Source::Anchor { anchor: LayerId(anchor), channel: texturecraft_engine::core::Channel::Height, ramp: Vec::new() },
projection: Default::default(),
};
}
}
let bytes = s.smart_mask_bytes(id, "Anchored").unwrap();
let target = layer(&mut s);
s.apply_smart_mask_bytes(target, &bytes).unwrap();
let mask = s.doc.project.layer(target).unwrap().mask.as_ref().unwrap();
let new_anchor = mask.effects.iter().find(|effect| matches!(effect.kind, EffectKind::Anchor)).unwrap().id;
let reads = mask.effects.iter().find_map(|effect| match &effect.kind {
EffectKind::Fill { source: Source::Anchor { anchor, .. }, .. } => Some(*anchor),
_ => None,
});
assert_eq!(reads, Some(new_anchor), "the fill reads the copied anchor, not the old one");
}
#[test]
fn an_external_anchor_cannot_be_saved_or_rebound_in_another_project() {
let mut s = session(128);
let (source, _) = multi_effect_mask(&mut s);
let external = layer(&mut s);
let anchor = execute(&mut s, "effect.add.anchor", &json!({"layer": external.0, "target": "mask"})).unwrap()["effect"].as_u64().unwrap();
let source_ref = Source::Anchor { anchor: LayerId(anchor), channel: texturecraft_engine::core::Channel::Height, ramp: Vec::new() };
let mut file = texturecraft_engine::formats::load_project_bytes(&s.smart_mask_bytes(source, "Preset").unwrap()).unwrap();
let holder = file.project.texture_sets[0].stack[0];
for (project, id) in [(&mut file.project, holder), (&mut s.doc.project, source)] {
let mask = project.layer_mut(id).unwrap().mask.as_mut().unwrap();
let fill = mask.effects.iter_mut().find(|effect| matches!(effect.kind, EffectKind::Fill { .. })).unwrap();
fill.kind = EffectKind::Fill { source: source_ref.clone(), projection: Default::default() };
}
assert!(s.smart_mask_bytes(source, "Preset").unwrap_err().to_string().contains("outside this mask"));
let bytes = texturecraft_engine::formats::save_project_bytes(&file).unwrap();
let before = s.doc.project.clone();
let history = s.history_labels();
assert!(s.apply_smart_mask_bytes(external, &bytes).unwrap_err().to_string().contains("outside this mask"));
assert_eq!(s.doc.project, before);
assert_eq!(s.history_labels(), history);
}
+50
View File
@@ -791,3 +791,53 @@ fn unparseable_color_param_returns_error() {
let err = execute(&mut s, "tool.click", &json!({"uv": [0.2, 0.8, 0.4]})).unwrap_err();
assert_eq!(err.to_string(), "`tool.click`: a 2D view point needs `uv` as [u, v]");
}
#[test]
fn resetting_a_stencil_puts_back_its_placement_only() {
let mut stencil = texturecraft_engine::StencilState::new("logo.png");
stencil.center = [0.4, -0.2];
stencil.scale = 2.0;
stencil.rotation = 30.0;
stencil.opacity = 0.9;
stencil.tile = true;
stencil.reset_placement();
assert_eq!((stencil.center, stencil.scale, stencil.rotation, stencil.opacity, stencil.tile), ([0.0, 0.0], 0.8, 0.0, 0.9, true));
}
#[test]
fn blending_set_gives_each_channel_its_own_mode_and_opacity_in_one_undo_step() {
let mut s = session();
let layer = execute(&mut s, "layer.add.paint", &json!({})).unwrap()["layer"].as_u64().unwrap();
let read = |s: &Session| s.doc.project.layers[&texturecraft_engine::core::LayerId(layer)].channels.clone();
let before = read(&s);
execute(
&mut s,
"layer.blending.set",
&json!({"layer": layer, "channels": {"baseColor": {"mode": "Multiply", "opacity": 0.25}, "roughness": {"opacity": 0.5}}}),
)
.unwrap();
let after = read(&s);
assert_eq!((after[&Channel::BaseColor].mode, after[&Channel::BaseColor].opacity), (texturecraft_engine::core::BlendMode::Multiply, 0.25));
assert_eq!((after[&Channel::Roughness].mode, after[&Channel::Roughness].opacity), (before[&Channel::Roughness].mode, 0.5));
assert_eq!(after[&Channel::Metallic], before[&Channel::Metallic], "channels not listed stay as they were");
execute(&mut s, "edit.undo", &Value::Null).unwrap();
assert_eq!(read(&s), before, "one undo step restores every listed channel");
execute(&mut s, "edit.redo", &Value::Null).unwrap();
// A channel the layer has disabled stays disabled
execute(&mut s, "layer.blend", &json!({"layer": layer, "channel": "metallic", "enabled": false})).unwrap();
execute(&mut s, "layer.blending.set", &json!({"layer": layer, "channels": {"metallic": {"opacity": 0.1}}})).unwrap();
assert!(!read(&s).contains_key(&Channel::Metallic));
let stable = read(&s);
for bad in [
json!({"layer": layer}),
json!({"layer": layer, "channels": {"nope": {}}}),
json!({"layer": layer, "channels": {"baseColor": {"mode": "Multiply"}, "nope": {}}}),
json!({"layer": layer, "channels": {"baseColor": {"mode": "???"}}}),
] {
assert!(execute(&mut s, "layer.blending.set", &bad).is_err(), "{bad}");
assert_eq!(read(&s), stable, "an error changes nothing");
}
execute(&mut s, "layer.blending.set", &json!({"layer": layer, "channels": {"baseColor": {"opacity": 2.0}, "roughness": {"opacity": -1.0}}})).unwrap();
assert_eq!((read(&s)[&Channel::BaseColor].opacity, read(&s)[&Channel::Roughness].opacity), (1.0, 0.0), "opacity is clamped");
}
+1 -1
View File
@@ -78,7 +78,7 @@ pub fn preset_from_json(json: &str) -> Result<ExportPreset>;
pub fn preset_to_json(preset: &ExportPreset) -> Result<String>;
```
- `ExportPreset { name, maps: Vec<MapSpec> }`, `MapSpec { file, format, bit_depth, channels: Vec<(Dest, SourceRef)> }`
- `ExportPreset { name, maps: Vec<MapSpec> }`, `MapSpec { file, format, bit_depth, channels: Vec<(Dest, SourceRef)>, inverted: Vec<Dest> }`
(serde JSON, so presets can be user files).
- `Dest`: `R G B A` or `L` (gray; `L` + `A` = gray + alpha).
- `SourceRef`: `Channel { channel, component }` (`Normal` = the **final** normal in the export
+59 -23
View File
@@ -253,6 +253,10 @@ pub struct MapSpec {
pub format: FileFormat,
pub bit_depth: u8,
pub channels: Vec<(Dest, SourceRef)>,
/// Destination channels written as `1 - value` (absent in old files: none). The source value
/// is inverted before the colour-space encoding, so a colour map is inverted in linear light.
#[serde(default, skip_serializing_if = "Vec::is_empty")]
pub inverted: Vec<Dest>,
}
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
@@ -268,26 +272,38 @@ impl ExportPreset {
if self.name.trim().is_empty() || self.name.chars().count() > MAX_PRESET_NAME || self.name.chars().any(char::is_control) {
return bad(format!("the name must be 1 to {MAX_PRESET_NAME} characters without control characters"));
}
if self.maps.len() > MAX_MAPS {
return bad(format!("more than {MAX_MAPS} maps"));
}
for m in &self.maps {
if let Some(e) = template_error(&m.file) {
return bad(e);
}
if !matches!(m.bit_depth, 8 | 16 | 32) {
return bad(format!("map \"{}\" has bit depth {} (8, 16 or 32)", m.file, m.bit_depth));
}
if m.channels.iter().any(|(_, s)| s.component() != s.raw_component()) {
return bad(format!("map \"{}\" picks a component other than 0, 1 or 2", m.file));
}
let dests: BTreeSet<Dest> = m.channels.iter().map(|(d, _)| *d).collect();
if dests.len() != m.channels.len() || m.channels.is_empty() {
return bad(format!("map \"{}\" needs distinct destination channels", m.file));
}
if dests.contains(&Dest::L) && dests.iter().any(|d| matches!(d, Dest::R | Dest::G | Dest::B)) {
return bad(format!("map \"{}\" mixes L with R/G/B", m.file));
}
let inv: BTreeSet<Dest> = m.inverted.iter().copied().collect();
if inv.len() != m.inverted.len() || !inv.is_subset(&dests) {
return bad(format!("map \"{}\" inverts a channel it does not write, or one twice", m.file));
}
if m.channels.iter().any(|(_, s)| matches!(s, SourceRef::Constant(v) if !v.is_finite())) {
return bad(format!("map \"{}\" has a non-finite constant", m.file));
}
@@ -389,7 +405,7 @@ pub struct PlannedFile {
}
// ---------------------------------------------------------------------------------------------
// Planning: which maps exist for a texture set and what their files are called.
// Planning: which maps exist for a texture set and what their files are called
fn normal_present(set: &TextureSet) -> bool {
set.has_channel(Channel::Normal) || set.has_channel(Channel::Height) || set.baked.contains(&BakedMap::Normal)
@@ -476,6 +492,7 @@ pub fn list_outputs(project: &Project, ts: usize, mesh_name: &str, opts: &Export
{
return Err(FormatError::Invalid(format!("export size {s} must be a power of two up to {MAX_IMAGE_SIZE}")));
}
let mut used = BTreeSet::new();
let mut out = Vec::new();
let tiles: Vec<Option<u32>> = if set.uv_tiles.is_empty() || opts.atlas { vec![None] } else { set.uv_tiles.iter().copied().map(Some).collect() };
@@ -483,6 +500,7 @@ pub fn list_outputs(project: &Project, ts: usize, mesh_name: &str, opts: &Export
if !map.channels.iter().any(|(_, s)| source_present(set, s)) {
continue;
}
let format = opts.format_override.unwrap_or(map.format);
let bit_depth = format.depth(opts.bit_depth_override.unwrap_or(map.bit_depth));
let space = opts.space_for(format);
@@ -491,9 +509,11 @@ pub fn list_outputs(project: &Project, ts: usize, mesh_name: &str, opts: &Export
(true, ColorSpace::Srgb) => "sRGB",
(true, other) => other.name(),
};
// Integer files clamp to 0-1, which wide-gamut linear colour can leave.
// Integer files clamp wide-gamut linear color to 0–1
let clamps = is_color(map) && !format.is_float() && matches!(space, ColorSpace::AcesCg | ColorSpace::Aces2065);
// One file per UV tile: names without `$udim` get it appended.
// Append `$udim` to names for separate UV tiles
let template = if tiles.iter().any(Option::is_some) && !map.file.contains("$udim") { format!("{}.$udim", map.file) } else { map.file.clone() };
for &tile in &tiles {
let stem = template
@@ -503,7 +523,8 @@ pub fn list_outputs(project: &Project, ts: usize, mesh_name: &str, opts: &Export
.replace("$textureSet", &set.name)
.replace("$channel", channel_label(map))
.replace("$colorSpace", color_space);
// The same name with the tile number as a placeholder, to write it as `<UDIM>` after.
// Replace the tile number with `<UDIM>` in the shared name
let token_stem = tile.map(|_| {
let t = template
.replace("$udim", "UDIMTOKEN")
@@ -525,7 +546,8 @@ pub fn list_outputs(project: &Project, ts: usize, mesh_name: &str, opts: &Export
format.extension().to_uppercase()
));
}
// Case-insensitive: Windows and macOS file systems are.
// Compare names case-insensitively for Windows and macOS
let mut k = 2;
while used.contains(&name.to_ascii_lowercase()) {
name = format!("{stem}_{k}.{ext}");
@@ -535,8 +557,9 @@ pub fn list_outputs(project: &Project, ts: usize, mesh_name: &str, opts: &Export
warnings.push(format!("\"{stem}.{ext}\" is produced by more than one map; this one was renamed to \"{name}\""));
}
used.insert(name.to_ascii_lowercase());
// Only when putting the tile number back gives this file's name: the length limit cuts the
// longer placeholder elsewhere (or off), and a name may hold the placeholder text itself.
// Use a UDIM name only when substituting its tile recovers the output name
// Truncation or literal placeholder text can make that substitution ambiguous
let udim_name = token_stem.filter(|t| tile.is_some_and(|n| t.contains("UDIMTOKEN") && t.replace("UDIMTOKEN", &n.to_string()) == stem)).map(|t| {
let renamed = if k > 2 { format!("_{}", k - 1) } else { String::new() };
format!("{t}{renamed}.{ext}").replace("UDIMTOKEN", "<UDIM>")
@@ -548,7 +571,7 @@ pub fn list_outputs(project: &Project, ts: usize, mesh_name: &str, opts: &Export
}
// ---------------------------------------------------------------------------------------------
// Sampling.
// Sampling
/// Which texel a value is taken from.
#[derive(Clone, Copy, PartialEq)]
@@ -702,10 +725,12 @@ pub fn render_maps(input: &ExportInput, opts: &ExportOptions) -> Result<Vec<Expo
if tile_res == 0 || tile_res > MAX_IMAGE_SIZE || height != tile_res * grid.map_or(1, |g| g.rows) {
return Err(FormatError::Invalid(format!("composite size {res}×{height} does not fit texture set \"{}\"", set.name)));
}
if input.coverage.len() != res as usize * height as usize {
return Err(FormatError::Invalid(format!("coverage has {} texels, expected {res}×{height}", input.coverage.len())));
}
// Padding stays inside each UV tile.
// Padding stays inside each UV tile
let dmap = match opts.padding {
Padding::None => None,
Padding::Dilation(d) | Padding::DilationDefault(d) => Some(DilationMap::in_blocks(input.coverage, res, height, Some(d), tile_res)),
@@ -729,11 +754,14 @@ pub fn render_maps(input: &ExportInput, opts: &ExportOptions) -> Result<Vec<Expo
let map = opts.preset.maps.get(p.map).ok_or_else(|| FormatError::Invalid("planned map out of range".into()))?;
let lay = layout(set, map);
let n = lay.len();
// The texels written: one tile, or the whole set.
let inverted: Vec<bool> = lay.iter().map(|(d, _)| map.inverted.contains(d)).collect();
// The texels written: one tile, or the whole set
let (x0, y0, w, h) = match (p.tile, grid) {
(Some(t), Some(g)) => {
let (bx, by) = g.block(t).ok_or_else(|| FormatError::Invalid(format!("UV tile {t} is not in the set's grid")))?;
// A tile smaller than its block fills the block's top-left corner.
// A tile smaller than its block fills the block's top-left corner
let side = ((tile_res as f32 * set.tile_scale(t)).round() as u32).clamp(1, tile_res);
(bx * tile_res, by * tile_res, side, side)
}
@@ -755,17 +783,19 @@ pub fn render_maps(input: &ExportInput, opts: &ExportOptions) -> Result<Vec<Expo
let mut cache = None;
for (k, (_, src)) in lay.iter().enumerate() {
if let Some(v) = row.get_mut(col * n + k) {
*v = sampler.sample(src, at, &mut cache);
let s = sampler.sample(src, at, &mut cache);
*v = if inverted.get(k).copied().unwrap_or(false) { 1.0 - s } else { s };
}
}
}
});
// `size` is per tile: an atlas scales with it.
// `size` is per tile: an atlas scales with it
let scale = |v: u32| (u64::from(v) * u64::from(opts.size.unwrap_or(tile_res)) / u64::from(tile_res)) as u32;
let size = (scale(w), scale(h));
let data = resize(data, (w, h), n, size);
// Colour maps leave linear Rec.709 for the chosen space. sRGB in integer files is
// encoded by `encode`; every other case is converted here (float sRGB included).
// Integer sRGB converts in `encode`; other color spaces convert here
let space = opts.space_for(p.format);
let rgb = lay.len() >= 3 && lay.iter().take(3).map(|(d, _)| *d).eq([Dest::R, Dest::G, Dest::B]);
let mut data = data;
@@ -781,7 +811,8 @@ pub fn render_maps(input: &ExportInput, opts: &ExportOptions) -> Result<Vec<Expo
warnings.push(format!("\"{}\" packs colour into one channel (L), so it is written in linear Rec.709, not {}", p.name, space.name()));
}
let srgb: Vec<bool> = lay.iter().map(|(d, _)| *d != Dest::A && is_color(map) && !p.format.is_float() && space == ColorSpace::Srgb).collect();
// A colour space the user chose is written into the colour maps (data maps have none).
// A colour space the user chose is written into the colour maps (data maps have none)
let embed = (opts.color_space.is_some() && is_color(map) && rgb).then_some(space);
let bytes = encode(p.format, p.bit_depth, size, n, &data, &srgb, embed, &mut warnings)?;
Ok(ExportedFile { name: p.name, bytes, width: size.0, height: size.1, warnings })
@@ -839,8 +870,8 @@ fn encode(
warnings: &mut Vec<String>,
) -> Result<Vec<u8>> {
let failed = |e: &dyn std::fmt::Display| FormatError::Invalid(format!("{} encoding failed: {e}", format.extension()));
// Where the colour space goes: an ICC profile in PNG, JPEG, TIFF and WebP, the chromaticities
// attribute in EXR. The other formats have no place for it.
// Embed ICC or EXR chromaticities only where the format supports them
if let Some(space) = embed
&& matches!(format, FileFormat::Tga | FileFormat::Bmp | FileFormat::Hdr)
{
@@ -858,7 +889,8 @@ fn encode(
}
_ => {}
}
// Integer formats: transfer function and quantization first, then fit the channel layout.
// Integer formats: transfer function and quantization first, then fit the channel layout
let encoded: Vec<f32> =
data.iter().enumerate().map(|(i, v)| if srgb.get(i % n).copied().unwrap_or(false) { linear_to_srgb(*v) } else { v.clamp(0.0, 1.0) }).collect();
let (encoded, n) = match (format, n) {
@@ -890,7 +922,8 @@ fn remap(data: &[f32], n: usize, pick: &[usize]) -> Vec<f32> {
fn write_image(format: FileFormat, bytes: &[u8], (w, h): (u32, u32), color: image::ExtendedColorType, icc: Option<Vec<u8>>) -> image::ImageResult<Vec<u8>> {
use image::ImageEncoder;
let mut out = Cursor::new(Vec::new());
// `set_icc_profile` says no (an error to ignore) for an encoder without a place for it.
// `set_icc_profile` says no (an error to ignore) for an encoder without a place for it
let fmt = match format {
FileFormat::Jpeg => {
let mut enc = image::codecs::jpeg::JpegEncoder::new_with_quality(&mut out, JPEG_QUALITY);
@@ -957,13 +990,15 @@ fn write_exr((w, h): (u32, u32), n: usize, data: &[f32], half: bool, space: Opti
let layer = Layer::new((w as usize, h as usize), LayerAttributes::default(), Encoding::SMALL_LOSSLESS, AnyChannels::sort(channels));
let mut out = Cursor::new(Vec::new());
let mut image = Image::from_layer(layer);
// The primaries and white point of the values, in the attribute OpenEXR readers look for.
// Store primaries and white point in the OpenEXR attribute
if let Some(space) = space {
let [r, g, b, white] = space.chromaticities().map(|xy| Vec2(xy[0] as f32, xy[1] as f32));
image.attributes.chromaticities = Some(exr::meta::attribute::Chromaticities { red: r, green: g, blue: b, white });
}
let writer = image.write();
// No worker threads on the web.
// The web build has no worker threads
#[cfg(target_arch = "wasm32")]
let writer = writer.non_parallel();
writer.to_buffered(&mut out)?;
@@ -978,11 +1013,12 @@ pub fn write_files(files: &[ExportedFile], dir: &std::path::Path) -> Result<Vec<
files
.iter()
.map(|f| {
// The planned name is `<sanitized stem>.<ext>`; the stem alone is capped at MAX_STEM.
// Cap the sanitized stem before adding the extension
let (stem, ext) = f.name.rsplit_once('.').unwrap_or((&f.name, ""));
if f.name.is_empty() || stem != sanitize_file_stem(stem) || !ext.chars().all(|c| c.is_ascii_alphanumeric()) || f.name.trim_matches('.').is_empty() {
return Err(FormatError::Invalid(format!("\"{}\" is not a plain file name", f.name)));
}
let path = dir.join(&f.name);
crate::write_atomic(&path, &f.bytes)?;
Ok(path)
+137 -10
View File
@@ -242,6 +242,7 @@ fn templates_are_sanitized_and_collisions_suffixed() {
format: FileFormat::Png,
bit_depth: 8,
channels: vec![(Dest::L, SourceRef::Channel { channel: Channel::Roughness, component: 0 })],
inverted: Vec::new(),
};
let preset = ExportPreset {
name: "t".into(),
@@ -316,6 +317,7 @@ fn every_format_encodes_and_decodes() {
format: FileFormat::Png,
bit_depth: 8,
channels: vec![(Dest::L, SourceRef::Channel { channel: Channel::Roughness, component: 0 }), (Dest::A, SourceRef::Constant(0.5))],
inverted: Vec::new(),
};
let mut preset = builtin_preset("glTF PBR Metal Roughness").unwrap();
preset.maps.push(gray_alpha);
@@ -331,9 +333,11 @@ fn every_format_encodes_and_decodes() {
if format == FileFormat::Exr && f.name.starts_with("la") {
continue; // Y/A EXR: covered by `exr_values_are_linear`.
}
assert_eq!(decode(f).dimensions(), (RES, RES), "{}", f.name);
}
// Roughness 0.25 everywhere survives every format (JPEG within its loss).
// Roughness 0.25 everywhere survives every format (JPEG within its loss)
let px = decode(find(&files, "OcclusionRoughnessMetallic.")).to_rgba32f().get_pixel(1, 1)[1];
assert!((px - 0.25).abs() < 0.01, "{format:?}/{depth}: {px}");
let base = find(&files, "_BaseColor.");
@@ -407,7 +411,7 @@ fn write_files_accepts_planned_name_with_max_length_stem() {
}
fn gray_map(file: &str, src: SourceRef) -> MapSpec {
MapSpec { file: file.into(), format: FileFormat::Png, bit_depth: 8, channels: vec![(Dest::L, src)] }
MapSpec { file: file.into(), format: FileFormat::Png, bit_depth: 8, channels: vec![(Dest::L, src)], inverted: Vec::new() }
}
#[test]
@@ -449,6 +453,7 @@ fn converted_maps_invert_and_derive_normals() {
format: FileFormat::Png,
bit_depth: 8,
channels: [Dest::R, Dest::G, Dest::B].into_iter().zip(0u8..).map(|(d, k)| (d, SourceRef::Virtual { map, component: k })).collect(),
inverted: Vec::new(),
};
let preset = ExportPreset {
name: "converted".into(),
@@ -467,7 +472,8 @@ fn converted_maps_invert_and_derive_normals() {
assert_eq!(hn.get_pixel(30, 30), full.get_pixel(30, 30), "without a normal channel the final normal is the height normal");
let (a, b) = (hn.get_pixel(30, 30), decode(find(&files, "dx")).to_rgb8().get_pixel(30, 30).to_owned());
assert!(a[1] > 136 && (a[1] as i32 + b[1] as i32 - 255).abs() <= 1, "DirectX flips green: {a:?} vs {b:?}");
// Converted maps only exist when their source channel does.
// Converted maps only exist when their source channel does
let fx = Fx::new(&default_channels());
let only = ExportPreset { name: "c".into(), maps: vec![gray_map("rough", virt(VirtualMap::Roughness)), rgb("hn", VirtualMap::HeightNormal)] };
let names: Vec<String> = list_outputs(&fx.project, 0, "m", &ExportOptions::new(only)).unwrap().into_iter().map(|p| p.name).collect();
@@ -476,7 +482,7 @@ fn converted_maps_invert_and_derive_normals() {
#[test]
fn uv_tiles_export_one_file_per_tile_without_padding_across() {
// Tiles 1001 (left block: red, only x < 16 covered) and 1002 (right block: blue).
// Tiles 1001 (left block: red, only x < 16 covered) and 1002 (right block: blue)
let mut project = Project::new("My Project", "builtin:udim_plane");
let mut ts = TextureSet::new("Body Set", 0, RES);
ts.uv_tiles = vec![1001, 1002];
@@ -505,6 +511,7 @@ fn uv_tiles_export_one_file_per_tile_without_padding_across() {
(Dest::G, SourceRef::Channel { channel: Channel::BaseColor, component: 1 }),
(Dest::B, SourceRef::Channel { channel: Channel::BaseColor, component: 2 }),
],
inverted: Vec::new(),
}],
};
let files = render_maps(&input, &ExportOptions::new(preset.clone())).unwrap();
@@ -512,10 +519,12 @@ fn uv_tiles_export_one_file_per_tile_without_padding_across() {
assert_eq!(names, ["Body_Set_color.1001.png", "Body_Set_color.1002.png"]);
let (left, right) = (decode(&files[0]).to_rgb8(), decode(&files[1]).to_rgb8());
assert_eq!((left.width(), left.height(), right.width()), (RES, RES, RES));
// Infinite padding fills tile 1001 from its own island only.
// Infinite padding fills tile 1001 from its own island only
assert!(left.pixels().all(|p| p.0 == [255, 0, 0]), "tile 1001 is red");
assert!(right.pixels().all(|p| p.0 == [0, 0, 255]), "tile 1002 is blue");
// `$udim` placed by the template; a size applies per tile; the atlas is one image.
// `$udim` placed by the template; a size applies per tile; the atlas is one image
let mut named = preset.clone();
named.maps[0].file = "$udim_$textureSet".into();
let opts = ExportOptions { size: Some(32), ..ExportOptions::new(named) };
@@ -534,12 +543,13 @@ fn the_udim_name_is_the_file_name_with_its_tile_number_as_placeholder() {
project.texture_sets.push(ts);
let udim_names = |file: String| {
let channels = vec![(Dest::R, SourceRef::Channel { channel: Channel::BaseColor, component: 0 })];
let preset = ExportPreset { name: "t".into(), maps: vec![MapSpec { file, format: FileFormat::Png, bit_depth: 8, channels }] };
let preset = ExportPreset { name: "t".into(), maps: vec![MapSpec { file, format: FileFormat::Png, bit_depth: 8, channels, inverted: Vec::new() }] };
list_outputs(&project, 0, "m", &ExportOptions::new(preset)).unwrap().into_iter().map(|f| f.udim_name).collect::<Vec<_>>()
};
let placeholder = Some("Body_<UDIM>.png".to_string());
assert_eq!(udim_names("$textureSet_$udim".into()), [placeholder.clone(), placeholder]);
// The length limit cuts the longer placeholder where it doesn't cut the tile number: none then.
// The length limit cuts the longer placeholder where it doesn't cut the tile number: none then
assert_eq!(udim_names(format!("{}_$udim_$textureSet", "a".repeat(MAX_STEM - 10))), [None, None]);
}
@@ -635,6 +645,7 @@ fn colour_space_names_the_files_and_warns_when_integer_files_clamp() {
(Dest::G, SourceRef::Channel { channel: Channel::BaseColor, component: 1 }),
(Dest::B, SourceRef::Channel { channel: Channel::BaseColor, component: 2 }),
],
inverted: Vec::new(),
}],
};
let plan = |space: Option<ColorSpace>, format: Option<FileFormat>| {
@@ -648,7 +659,8 @@ fn colour_space_names_the_files_and_warns_when_integer_files_clamp() {
assert!(aces.warnings.iter().any(|w| w.contains("clamped")), "{:?}", aces.warnings);
assert!(plan(Some(ColorSpace::AcesCg), Some(FileFormat::Exr)).warnings.is_empty(), "float files keep the values");
assert!(plan(None, None).warnings.is_empty() && plan(Some(ColorSpace::LinearRec709), None).warnings.is_empty());
// The planned names are the rendered names.
// The planned names are the rendered names
let opts = ExportOptions { color_space: Some(ColorSpace::Aces2065), ..ExportOptions::new(named) };
let names: Vec<String> = fx.render(&opts).into_iter().map(|f| f.name).collect();
assert_eq!(names, list_outputs(&fx.project, 0, "sphere", &opts).unwrap().into_iter().map(|p| p.name).collect::<Vec<_>>());
@@ -685,13 +697,15 @@ fn a_chosen_colour_space_is_embedded_as_an_icc_profile() {
if depth == 16 && matches!(format, FileFormat::Jpeg | FileFormat::Webp) {
continue;
}
for space in ColorSpace::ALL {
let mut warnings = Vec::new();
let bytes = encode(format, depth, (8, 8), 3, &data, &[false; 3], Some(space), &mut warnings).unwrap();
assert_eq!(embedded_icc(format, &bytes), crate::icc::profile(space), "{format:?} {depth}-bit {space:?}");
assert!(warnings.is_empty(), "{warnings:?}");
}
// No colour space chosen (a data map, or the default): nothing is embedded.
// No colour space chosen (a data map, or the default): nothing is embedded
let bytes = encode(format, depth, (8, 8), 3, &data, &[false; 3], None, &mut Vec::new()).unwrap();
assert_eq!(embedded_icc(format, &bytes), None, "{format:?} {depth}-bit");
}
@@ -727,3 +741,116 @@ fn formats_without_a_place_for_a_colour_space_say_so() {
assert!(quiet.is_empty(), "{format:?}: nothing to say without a chosen space: {quiet:?}");
}
}
/// R packs roughness (0.25) and B metallic (0.75); G and A are constants.
fn invert_map(depth: u8, inverted: Vec<Dest>) -> MapSpec {
let ch = |channel| SourceRef::Channel { channel, component: 0 };
MapSpec {
file: "packed".into(),
format: FileFormat::Png,
bit_depth: depth,
channels: vec![
(Dest::R, ch(Channel::Roughness)),
(Dest::G, SourceRef::Constant(0.5)),
(Dest::B, ch(Channel::Metallic)),
(Dest::A, SourceRef::Constant(1.0)),
],
inverted,
}
}
#[test]
fn inverted_channels_write_one_minus_the_source() {
let fx = Fx::new(&default_channels());
for depth in [8u8, 16] {
let preset = |inverted| ExportPreset { name: "inv".into(), maps: vec![invert_map(depth, inverted)] };
let px = |p: ExportPreset| {
let files = fx.render(&ExportOptions::new(p));
let img = decode(find(&files, "packed")).to_rgba16();
let p = img.get_pixel(9, 9).0;
// Compare 16-bit values for both depths: an 8-bit file widens to value * 257
p.map(i32::from)
};
let plain = px(preset(Vec::new()));
let inv = px(preset(vec![Dest::R, Dest::A]));
let tol = if depth == 8 { 257 } else { 2 };
// Roughness 0.25 inverts to 0.75, constant alpha 1 to 0; G and B stay
assert!((inv[0] - (65535 - plain[0])).abs() <= tol, "depth {depth}: R {} vs {}", inv[0], 65535 - plain[0]);
assert!((inv[0] - 49151).abs() <= tol, "depth {depth}: R {}", inv[0]);
assert!(inv[3] <= tol, "depth {depth}: A {}", inv[3]);
assert_eq!((inv[1], inv[2]), (plain[1], plain[2]), "depth {depth}: channels not listed stay as they are");
assert!((plain[0] - 16384).abs() <= tol && plain[3] == 65535, "depth {depth}: un-inverted {plain:?}");
}
// Gray maps and float files too
let gray = gray_map("g", SourceRef::Channel { channel: Channel::Metallic, component: 0 });
let gray = MapSpec { inverted: vec![Dest::L], ..gray };
let files = fx.render(&ExportOptions::new(ExportPreset { name: "inv".into(), maps: vec![gray] }));
assert_eq!(decode(find(&files, "g.png")).to_luma8().get_pixel(4, 4)[0], 64, "1 - metallic 0.75");
let mut float = invert_map(32, vec![Dest::B]);
float.format = FileFormat::Exr;
let files = fx.render(&ExportOptions::new(ExportPreset { name: "inv".into(), maps: vec![float] }));
let v = decode(find(&files, "packed.exr")).to_rgba32f().get_pixel(4, 4).0;
assert!((v[2] - 0.25).abs() < 1e-3 && (v[0] - 0.25).abs() < 1e-3, "metallic 0.75 inverted, roughness 0.25 not: {v:?}");
}
#[test]
fn inverted_flag_round_trips_and_old_json_loads() {
let mut map = invert_map(8, vec![Dest::B]);
let preset = ExportPreset { name: "Mine".into(), maps: vec![map.clone()] };
let json = preset_to_json(&preset).unwrap();
assert_eq!(preset_from_json(&json).unwrap(), preset);
// A file written before the flag existed has no `inverted` and keeps none on save
map.inverted.clear();
let old = ExportPreset { name: "Old".into(), maps: vec![map] };
let json = preset_to_json(&old).unwrap();
assert!(!json.contains("inverted"), "{json}");
assert_eq!(preset_from_json(&json).unwrap(), old);
assert!(preset_from_json(&json).unwrap().maps[0].inverted.is_empty());
}
#[test]
fn validation_rejects_inverting_a_channel_the_map_lacks() {
let ok = ExportPreset { name: "Mine".into(), maps: vec![invert_map(8, vec![Dest::R])] };
ok.validate().unwrap();
let mut bad = ok.clone();
bad.maps[0].inverted = vec![Dest::L];
assert!(bad.validate().is_err());
bad.maps[0].inverted = vec![Dest::R, Dest::R];
assert!(bad.validate().is_err());
}
#[test]
fn inverting_a_colour_channel_inverts_the_linear_value_before_encoding() {
let fx = Fx::new(&default_channels());
let base = |inverted: Vec<Dest>, size: Option<u32>| {
let map = MapSpec {
file: "col".into(),
format: FileFormat::Png,
bit_depth: 8,
channels: [Dest::R, Dest::G, Dest::B]
.into_iter()
.zip(0u8..)
.map(|(d, k)| (d, SourceRef::Channel { channel: Channel::BaseColor, component: k }))
.collect(),
inverted,
};
let mut opts = ExportOptions::new(ExportPreset { name: "c".into(), maps: vec![map] });
opts.size = size;
decode(find(&fx.render(&opts), "col")).to_rgb8()
};
let (plain, inv) = (base(Vec::new(), None), base(vec![Dest::R], None));
// Texel (9, 9): linear red 9/63, written as sRGB
let want = linear_to_srgb(1.0 - 9.0 / 63.0) * 255.0;
assert!((inv.get_pixel(9, 9)[0] as f32 - want).abs() <= 1.0, "{} vs {want}", inv.get_pixel(9, 9)[0]);
assert_eq!(inv.get_pixel(9, 9).0[1..], plain.get_pixel(9, 9).0[1..], "G and B stay");
// A size override goes through the resize path: the left-most texels are 1 - 0 -> white red
let half = base(vec![Dest::R], Some(RES / 2));
assert_eq!(half.width(), RES / 2);
assert!(half.get_pixel(0, 5)[0] >= 250, "{}", half.get_pixel(0, 5)[0]);
}
+1 -1
View File
@@ -72,7 +72,7 @@ pub fn usd_export_options() -> ExportOptions {
"ClearcoatRoughness" => gray(ch(Channel::CoatRoughness, 0)),
_ => gray(ch(Channel::Opacity, 0)),
};
MapSpec { file: stem.into(), format: FileFormat::Png, bit_depth: 8, channels }
MapSpec { file: stem.into(), format: FileFormat::Png, bit_depth: 8, channels, inverted: Vec::new() }
})
.collect();
super::png8_options(ExportPreset { name: "USD preview surface".into(), maps }, NormalFormat::OpenGl)
+2 -2
View File
@@ -19,7 +19,7 @@ pub(crate) fn virt(map: VirtualMap, component: u8) -> SourceRef {
/// `$mesh_$textureSet_<suffix>` PNG.
fn map(suffix: &str, bit_depth: u8, channels: Vec<(Dest, SourceRef)>) -> MapSpec {
MapSpec { file: format!("$mesh_$textureSet_{suffix}"), format: FileFormat::Png, bit_depth, channels }
MapSpec { file: format!("$mesh_$textureSet_{suffix}"), format: FileFormat::Png, bit_depth, channels, inverted: Vec::new() }
}
pub(crate) fn rgb(f: impl Fn(u8) -> SourceRef) -> Vec<(Dest, SourceRef)> {
@@ -68,7 +68,7 @@ pub(crate) const GLTF_SHEEN: &str = "Sheen";
/// glTF metallic-roughness maps (8-bit PNG), plus the clear coat and sheen extension maps where
/// the texture set has those channels; `file` turns a stem above into a file template.
pub(crate) fn gltf_pbr_maps(file: impl Fn(&str) -> String) -> Vec<MapSpec> {
let spec = |stem: &str, channels| MapSpec { file: file(stem), format: FileFormat::Png, bit_depth: 8, channels };
let spec = |stem: &str, channels| MapSpec { file: file(stem), format: FileFormat::Png, bit_depth: 8, channels, inverted: Vec::new() };
let mut sheen = rgb(|k| virt(VirtualMap::SheenTint, k));
sheen.push((Dest::A, ch(Channel::SheenRoughness, 0)));
vec![
+20
View File
@@ -71,6 +71,19 @@ impl Mesh {
self.positions.iter().fold((Vec3::splat(f32::MAX), Vec3::splat(f32::MIN)), |(lo, hi), p| (lo.min(*p), hi.max(*p)))
}
/// Axis-aligned bounds of the triangles drawn with `material` (None when none are).
pub fn bounds_of_material(&self, material: usize) -> Option<(Vec3, Vec3)> {
let mut bounds: Option<(Vec3, Vec3)> = None;
for triangle in self.triangles_of(material) {
let Some(corners) = self.tri(triangle) else { continue };
for corner in corners {
let Some(position) = self.positions.get(corner) else { continue };
bounds = Some(bounds.map_or((*position, *position), |(lo, hi)| (lo.min(*position), hi.max(*position))));
}
}
bounds
}
/// Bounding-sphere radius around the bounds center (at least a small epsilon).
pub fn radius(&self) -> f32 {
let (lo, hi) = self.bounds();
@@ -480,6 +493,13 @@ mod tests {
assert_eq!(m.triangles_of(0).collect::<Vec<_>>(), vec![0, 1]);
}
#[test]
fn bounds_of_a_material_cover_only_its_triangles() {
let m = quad();
assert_eq!(m.bounds_of_material(0), Some((Vec3::ZERO, Vec3::new(1.0, 1.0, 0.0))));
assert_eq!(m.bounds_of_material(1), None);
}
#[test]
fn wire_edges_leave_out_polygon_diagonals() {
let mut m = quad();
+63
View File
@@ -0,0 +1,63 @@
//! Parameters shared by every brush alpha: extent inside the stamp, roundness, contrast, invert.
//! The defaults leave a stamp exactly as it was before the parameters existed.
use serde::{Deserialize, Serialize};
/// Smallest extent a stamp's alpha can be shrunk to along one axis
pub const MIN_ALPHA_SIZE: f32 = 0.05;
/// Highest contrast; 1 leaves the alpha's values as they are
pub const MAX_ALPHA_CONTRAST: f32 = 8.0;
/// How the alpha is placed and graded inside the stamp square (see [`crate::Shape::sample`]).
#[derive(Clone, Copy, Debug, PartialEq, Serialize, Deserialize)]
#[serde(default)]
pub struct AlphaParams {
/// Width of the alpha as a fraction of the stamp (1 = the whole stamp)
pub size_x: f32,
/// Height of the alpha as a fraction of the stamp
pub size_y: f32,
/// Round procedural shape only: 1 = circle, 0 = square
pub roundness: f32,
/// Steepness of the values around 0.5 (1 = unchanged, more = harder edges)
pub contrast: f32,
/// Swap paint and no paint inside the stamp square
pub invert: bool,
}
impl Default for AlphaParams {
fn default() -> Self {
AlphaParams { size_x: 1.0, size_y: 1.0, roundness: 1.0, contrast: 1.0, invert: false }
}
}
impl AlphaParams {
/// Every value into its valid range (input from the UI, a file or an agent)
pub fn sanitized(self) -> AlphaParams {
let clamp_finite = |value: f32, min: f32, max: f32, default: f32| if value.is_finite() { value.clamp(min, max) } else { default };
AlphaParams {
size_x: clamp_finite(self.size_x, MIN_ALPHA_SIZE, 1.0, 1.0),
size_y: clamp_finite(self.size_y, MIN_ALPHA_SIZE, 1.0, 1.0),
roundness: clamp_finite(self.roundness, 0.0, 1.0, 1.0),
contrast: clamp_finite(self.contrast, 1.0, MAX_ALPHA_CONTRAST, 1.0),
invert: self.invert,
}
}
/// The local coordinates the alpha is sampled at: the stamp's, stretched so the alpha fills
/// only its extent
pub fn place(&self, lx: f32, ly: f32) -> (f32, f32) {
(lx / self.size_x, ly / self.size_y)
}
/// Contrast, then invert, on a sampled value `v` at stamp coordinates (`lx`, `ly`). Invert
/// stays inside the stamp square, so the area around a shape isn't flooded with paint.
pub fn grade(&self, v: f32, lx: f32, ly: f32) -> f32 {
let v = if self.contrast == 1.0 { v } else { ((v - 0.5) * self.contrast + 0.5).clamp(0.0, 1.0) };
match self.invert {
true if lx.abs() <= 1.0 && ly.abs() <= 1.0 => 1.0 - v,
true => 0.0,
false => v,
}
}
}
+143 -9
View File
@@ -5,6 +5,7 @@ use texturecraft_compose::ImageRes;
use texturecraft_geom::glam::{Mat3, Vec3};
use texturecraft_texel::noise;
use crate::alpha_params::AlphaParams;
use crate::alphas::AlphaImage;
/// How the stamp plane is oriented.
@@ -93,23 +94,35 @@ pub struct Shape<'a> {
pub alpha: BrushAlpha,
pub image: Option<&'a ImageRes>,
pub library: Option<&'a AlphaImage>,
/// Extent, roundness, contrast and invert shared by every kind of alpha
pub params: AlphaParams,
/// Mip level of `library` to sample (set per stamp by [`Shape::at_radius`]).
pub level: usize,
}
impl Shape<'_> {
/// Shape value at local stamp coordinates (see [`BrushAlpha::sample`]).
/// Shape value at local stamp coordinates (see [`BrushAlpha::sample`]), placed and graded by
/// the [`AlphaParams`]: the same for image, library and procedural alphas.
pub fn sample(&self, lx: f32, ly: f32, hardness: f32, seed: u32) -> f32 {
match (self.image, self.library) {
(Some(img), _) => image_alpha(img, lx, ly),
(None, Some(lib)) => lib.sample(self.level, lx, ly),
(None, None) => self.alpha.sample(lx, ly, hardness, seed),
}
let (x, y) = self.params.place(lx, ly);
let value = match (self.image, self.library) {
(Some(img), _) => image_alpha(img, x, y),
(None, Some(lib)) => lib.sample(self.level, x, y),
(None, None) if self.alpha == BrushAlpha::Round && self.params.roundness < 1.0 => {
// Between the square's edge distance (0) and the circle's (1)
let (square, circle) = (x.abs().max(y.abs()), (x * x + y * y).sqrt());
1.0 - smoothstep(hardness.min(0.999), 1.0, square + (circle - square) * self.params.roundness)
}
(None, None) => self.alpha.sample(x, y, hardness, seed),
};
self.params.grade(value, lx, ly)
}
/// This shape for a stamp `radius` texels wide (picks the library alpha's mip level).
pub fn at_radius(self, radius: f32) -> Self {
Shape { level: self.library.map_or(0, |l| l.level_for(radius)), ..self }
// A shrunk alpha covers fewer texels, so it wants a finer mip level
let covered = radius * self.params.size_x.min(self.params.size_y);
Shape { level: self.library.map_or(0, |l| l.level_for(covered)), ..self }
}
}
@@ -311,6 +324,9 @@ pub struct BrushSettings {
/// Built-in library alpha id used as the stamp shape (see [`crate::alphas`]).
#[serde(default)]
pub alpha_library: Option<String>,
/// Extent, roundness, contrast and invert of whichever alpha is used.
#[serde(default)]
pub alpha_params: AlphaParams,
/// Only paint surfaces facing the camera.
pub backface_culling: bool,
/// Half-depth of the stamp volume relative to the radius (thinner = less bleed into folds).
@@ -343,6 +359,7 @@ impl Default for BrushSettings {
alpha: BrushAlpha::Round,
alpha_image: None,
alpha_library: None,
alpha_params: AlphaParams::default(),
backface_culling: true,
depth: 1.0,
symmetry: Symmetry::default(),
@@ -379,6 +396,7 @@ impl BrushSettings {
jitter_flow: clamp_finite(self.jitter_flow, 0.0, 1.0, 0.0),
jitter_position: clamp_finite(self.jitter_position, 0.0, 4.0, 0.0),
depth: clamp_finite(self.depth, 0.05, 4.0, 1.0),
alpha_params: self.alpha_params.sanitized(),
symmetry: Symmetry {
radial: self.symmetry.radial.min(MAX_RADIAL_COPIES),
axis: self.symmetry.axis.min(LAST_AXIS),
@@ -426,9 +444,9 @@ mod tests {
#[test]
fn image_alpha_follows_the_image_and_is_zero_outside() {
// Left half white, right half black (2×1 image, sampled at texel centers).
// Left half white, right half black (2×1 image, sampled at texel centers)
let img = ImageRes { width: 2, height: 1, rgba: vec![[1.0; 4], [0.0, 0.0, 0.0, 1.0]], srgb: true };
let shape = Shape { alpha: BrushAlpha::Round, image: Some(&img), library: None, level: 0 };
let shape = Shape { alpha: BrushAlpha::Round, image: Some(&img), library: None, params: AlphaParams::default(), level: 0 };
assert!(shape.sample(-0.5, 0.0, 0.5, 0) > 0.99);
assert!(shape.sample(0.5, 0.0, 0.5, 0) < 0.01);
assert_eq!(shape.sample(1.5, 0.0, 0.5, 0), 0.0);
@@ -443,4 +461,120 @@ mod tests {
assert!(b.hardness < 1.0);
assert!(b.spacing > 0.0);
}
/// A grid over the stamp square and beyond it
fn grid() -> impl Iterator<Item = (f32, f32)> {
(-30..=30).flat_map(|i| (-30..=30).map(move |j| (i as f32 / 20.0, j as f32 / 20.0)))
}
/// Width and height (in grid steps) of the area where `shape` is above zero
fn extent(shape: &Shape, hardness: f32) -> (usize, usize) {
let (mut xs, mut ys) = (std::collections::BTreeSet::new(), std::collections::BTreeSet::new());
for (x, y) in grid().filter(|&(x, y)| shape.sample(x, y, hardness, 1) > 0.0) {
xs.insert((x * 20.0) as i32);
ys.insert((y * 20.0) as i32);
}
(xs.len(), ys.len())
}
fn procedural(alpha: BrushAlpha, params: AlphaParams) -> Shape<'static> {
Shape { alpha, image: None, library: None, params, level: 0 }
}
#[test]
fn default_parameters_reproduce_every_alpha_exactly() {
let img = ImageRes {
width: 3,
height: 2,
rgba: vec![[1.0; 4], [0.3, 0.3, 0.3, 1.0], [0.0, 0.0, 0.0, 1.0], [0.6, 0.6, 0.6, 1.0], [0.9; 4], [0.1, 0.1, 0.1, 1.0]],
srgb: true,
};
let library = crate::alphas::library().first().map(|alpha| alpha.image());
let kinds = BrushAlpha::ALL.map(|alpha| Shape { alpha, image: None, library: None, params: AlphaParams::default(), level: 0 });
for shape in kinds.into_iter().chain([
Shape { alpha: BrushAlpha::Round, image: Some(&img), library: None, params: AlphaParams::default(), level: 0 },
Shape { alpha: BrushAlpha::Round, image: None, library, params: AlphaParams::default(), level: 0 },
]) {
for (x, y) in grid() {
let before = match (shape.image, shape.library) {
(Some(img), _) => image_alpha(img, x, y),
(None, Some(lib)) => lib.sample(shape.level, x, y),
(None, None) => shape.alpha.sample(x, y, 0.4, 7),
};
assert_eq!(shape.sample(x, y, 0.4, 7).to_bits(), before.to_bits(), "{:?} at ({x}, {y})", shape.alpha);
}
}
}
#[test]
fn size_x_half_halves_the_width_and_keeps_the_height() {
for alpha in [BrushAlpha::Round, BrushAlpha::Square] {
let (width, height) = extent(&procedural(alpha, AlphaParams::default()), 0.5);
let (narrow_width, narrow_height) = extent(&procedural(alpha, AlphaParams { size_x: 0.5, ..AlphaParams::default() }), 0.5);
assert_eq!(narrow_height, height, "{alpha:?}");
assert!((narrow_width as f32 - width as f32 / 2.0).abs() <= 2.0, "{alpha:?}: {narrow_width} of {width}");
let (flat_width, flat_height) = extent(&procedural(alpha, AlphaParams { size_y: 0.25, ..AlphaParams::default() }), 0.5);
assert_eq!(flat_width, width, "{alpha:?}");
assert!((flat_height as f32 - height as f32 / 4.0).abs() <= 2.0, "{alpha:?}: {flat_height} of {height}");
}
}
#[test]
fn sizes_apply_to_image_and_library_alphas_too() {
let img = ImageRes { width: 1, height: 1, rgba: vec![[1.0; 4]], srgb: true };
let params = AlphaParams { size_x: 0.5, ..AlphaParams::default() };
let image = Shape { alpha: BrushAlpha::Round, image: Some(&img), library: None, params, level: 0 };
assert_eq!((image.sample(0.4, 0.0, 0.5, 0) > 0.99, image.sample(0.6, 0.0, 0.5, 0)), (true, 0.0));
let library = crate::alphas::find("square").map(|alpha| alpha.image());
let shape = |params| Shape { alpha: BrushAlpha::Round, image: None, library, params, level: 0 };
assert!(shape(AlphaParams::default()).sample(0.7, 0.0, 0.5, 0) > 0.5, "a library square is wide open");
assert_eq!(shape(params).sample(0.7, 0.0, 0.5, 0), 0.0);
}
#[test]
fn invert_flips_values_inside_the_stamp_square_only() {
let invert = AlphaParams { invert: true, ..AlphaParams::default() };
for alpha in BrushAlpha::ALL {
for (x, y) in grid() {
let (plain, inverted) = (procedural(alpha, AlphaParams::default()).sample(x, y, 0.5, 3), procedural(alpha, invert).sample(x, y, 0.5, 3));
let expected = if x.abs() <= 1.0 && y.abs() <= 1.0 { 1.0 - plain } else { 0.0 };
assert!((inverted - expected).abs() < 1e-6, "{alpha:?} at ({x}, {y})");
}
}
}
#[test]
fn roundness_zero_turns_the_round_shape_into_a_square_footprint() {
let square = AlphaParams { roundness: 0.0, ..AlphaParams::default() };
assert_eq!(procedural(BrushAlpha::Round, AlphaParams::default()).sample(0.9, 0.9, 0.5, 0), 0.0, "a circle leaves the corner empty");
assert!(procedural(BrushAlpha::Round, square).sample(0.9, 0.9, 0.5, 0) > 0.0);
assert_eq!(extent(&procedural(BrushAlpha::Round, square), 0.99), extent(&procedural(BrushAlpha::Square, AlphaParams::default()), 0.99));
let half = AlphaParams { roundness: 0.5, ..AlphaParams::default() };
let (round, rounded) = (procedural(BrushAlpha::Round, AlphaParams::default()), procedural(BrushAlpha::Round, half));
assert!(rounded.sample(0.75, 0.75, 0.5, 0) > round.sample(0.75, 0.75, 0.5, 0), "between circle and square");
// Other shapes have no roundness
let star = |params| procedural(BrushAlpha::Star, params).sample(0.3, 0.2, 0.5, 0);
assert_eq!(star(square), star(AlphaParams::default()));
}
#[test]
fn contrast_steepens_the_values_around_one_half() {
let sharp = AlphaParams { contrast: 4.0, ..AlphaParams::default() };
let (soft, hard) = (procedural(BrushAlpha::Round, AlphaParams::default()), procedural(BrushAlpha::Round, sharp));
let [low, high] = [0.8, 0.3].map(|x| (soft.sample(x, 0.0, 0.0, 0), hard.sample(x, 0.0, 0.0, 0)));
assert!(low.0 < 0.5 && low.1 < low.0, "dark values get darker: {low:?}");
assert!(high.0 > 0.5 && high.1 > high.0, "light values get lighter: {high:?}");
assert_eq!(hard.sample(1.2, 0.0, 0.0, 0), 0.0, "outside the shape stays empty");
}
#[test]
fn sanitize_clamps_alpha_parameters() {
let wild = AlphaParams { size_x: 0.0, size_y: f32::NAN, roundness: 3.0, contrast: -2.0, invert: true };
let clean = BrushSettings { alpha_params: wild, ..BrushSettings::default() }.sanitized().alpha_params;
assert_eq!(clean, AlphaParams { size_x: crate::alpha_params::MIN_ALPHA_SIZE, size_y: 1.0, roundness: 1.0, contrast: 1.0, invert: true });
}
}
+21 -4
View File
@@ -244,7 +244,7 @@ impl Staging {
/// the same arguments will write.
pub fn stage_mask(&mut self, pixels: &PixelStore, effect: LayerId, value: f32, src: &CommitSource) {
let value = [value.clamp(0.0, 1.0)];
let b = Blend { kind: ChannelKind::Scalar, value: &value, stencil_color: false, carried: None };
let b = Blend { kind: ChannelKind::Scalar, value: &value, stencil_color: false, carried: src.carried_mask };
self.images.entry(None).or_default().stage(pixels.masks.get(&effect), 2, &b, src);
}
@@ -290,6 +290,8 @@ pub struct CommitSource<'a> {
pub per_texel: Option<TexelFn<'a>>,
/// Clone and smudge: straight values per channel carried by the stroke (replace `values`).
pub carried: Option<&'a BTreeMap<Channel, TileImage>>,
/// Scalar values sampled from a mask by clone or smudge.
pub carried_mask: Option<&'a TileImage>,
}
/// Commit a stroke into paint layer `layer` (channels in `values`; erase clears every painted
@@ -300,7 +302,8 @@ pub fn commit_layer(pixels: &mut PixelStore, layer: LayerId, size: (u32, u32), v
for &c in &channels {
pixels.layer_mut(layer, c, size);
}
// The channels blend in parallel too: an 8K stroke touches hundreds of tiles per channel.
// The channels blend in parallel too: an 8K stroke touches hundreds of tiles per channel
let images: Vec<(Channel, &mut TileImage, Option<StagedImage>)> =
pixels.layers.iter_mut().filter(|((id, c), _)| *id == layer && channels.contains(c)).map(|((_, c), img)| (*c, img, staging.take(Some(*c)))).collect();
images.into_par_iter().for_each(|(c, img, staged)| over(img, &layer_blend(c, values, &src), &src, staged));
@@ -310,7 +313,7 @@ pub fn commit_layer(pixels: &mut PixelStore, layer: LayerId, size: (u32, u32), v
pub fn commit_mask(pixels: &mut PixelStore, effect: LayerId, size: (u32, u32), value: f32, src: CommitSource, staging: &mut Staging) {
let img = pixels.mask_mut(effect, size);
let value = [value.clamp(0.0, 1.0)];
over(img, &Blend { kind: ChannelKind::Scalar, value: &value, stencil_color: false, carried: None }, &src, staging.take(None));
over(img, &Blend { kind: ChannelKind::Scalar, value: &value, stencil_color: false, carried: src.carried_mask }, &src, staging.take(None));
}
/// Commit a stroke into a coverage-only image (1 component), e.g. the quick mask.
@@ -323,7 +326,7 @@ mod tests {
use super::*;
fn src<'a>(alpha: &'a TileImage, tiles: &'a BTreeSet<(u32, u32)>, opacity: f32, erase: bool) -> CommitSource<'a> {
CommitSource { alpha, tiles, opacity, erase, per_texel: None, carried: None }
CommitSource { alpha, tiles, opacity, erase, per_texel: None, carried: None, carried_mask: None }
}
fn alpha(v: f32) -> (TileImage, BTreeSet<(u32, u32)>) {
@@ -394,6 +397,20 @@ mod tests {
CommitSource { carried, ..src(a, tiles, 0.8, erase) }
}
#[test]
fn layer_roughness_does_not_override_mask_coverage() {
let (alpha, tiles) = alpha(1.0);
let mut roughness = TileImage::new(64, 64, 1);
roughness.set(5, 5, &[to_u16(0.25)]);
let carried = [(Channel::Roughness, roughness)].into();
let source = CommitSource { carried: Some(&carried), ..src(&alpha, &tiles, 1.0, false) };
let mut pixels = PixelStore::default();
commit_mask(&mut pixels, LayerId(1), (64, 64), 1.0, source, &mut Staging::default());
assert_eq!(pixels.masks[&LayerId(1)].get(5, 5)[0], u16::MAX);
}
#[test]
fn staged_commits_match_and_stale_copies_are_ignored() {
let vals: BTreeMap<Channel, [f32; 3]> = [(Channel::BaseColor, [0.2, 0.4, 0.6]), (Channel::Height, [-0.5; 3])].into_iter().collect();
+3 -1
View File
@@ -11,6 +11,7 @@
#![forbid(unsafe_code)]
#![deny(clippy::unwrap_used, clippy::expect_used, clippy::panic, clippy::unimplemented, clippy::todo, clippy::unreachable)]
pub mod alpha_params;
pub mod alphas;
pub mod brush;
pub mod commit;
@@ -24,9 +25,10 @@ pub mod stroke;
pub mod text;
pub mod visibility;
pub use alpha_params::AlphaParams;
pub use brush::{Alignment, BrushAlpha, BrushSettings, FULL_TURN_DEGREES, MAX_RADIAL_COPIES, Particles, Shape, Symmetry, image_alpha};
pub use commit::{CommitSource, Staging, TexelFn, commit_coverage, commit_layer, commit_mask};
pub use path::{Lasso, spline, spline_segments};
pub use path::{Lasso, spline, spline_segments, spline_segments_with_corners, spline_with_corners};
pub use pickup::{Pickup, PickupMode};
pub use raster::{RasterCtx, StrokeCanvas, UvStamp, fill_coverage, fill_triangles, rasterize, rasterize_uv};
pub use stamp_source::StampSource;
+75 -8
View File
@@ -8,8 +8,14 @@ const MAX_SEGMENT_SAMPLES: f32 = 1024.0;
/// A Catmull-Rom spline through `points`, sampled about every `step` units, starting on the first point (closed curves end there too)
pub fn spline(points: &[Vec2], closed: bool, step: f32) -> Vec<Vec2> {
spline_with_corners(points, &[], closed, step)
}
/// [`spline`] with corner points: the curve turns sharply at a point whose entry in `corners` is true (a missing entry is smooth).
/// Each run between corners is its own Catmull-Rom spline ending on the corners, so two adjacent corners give a straight segment.
pub fn spline_with_corners(points: &[Vec2], corners: &[bool], closed: bool, step: f32) -> Vec<Vec2> {
let mut out: Vec<Vec2> = points.first().copied().into_iter().collect();
for segment in segment_samples(points, closed, step) {
for segment in segment_samples(points, corners, closed, step) {
out.extend(segment);
}
out
@@ -17,16 +23,20 @@ pub fn spline(points: &[Vec2], closed: bool, step: f32) -> Vec<Vec2> {
/// [`spline`]'s samples per segment: segment `s` holds those after point `s`, up to and including the next point
pub fn spline_segments(points: &[Vec2], closed: bool, step: f32) -> Vec<Vec<Vec2>> {
segment_samples(points, closed, step).map(Iterator::collect).collect()
spline_segments_with_corners(points, &[], closed, step)
}
/// [`spline_segments`] with corner points as in [`spline_with_corners`]
pub fn spline_segments_with_corners(points: &[Vec2], corners: &[bool], closed: bool, step: f32) -> Vec<Vec<Vec2>> {
segment_samples(points, corners, closed, step).map(Iterator::collect).collect()
}
/// Stream samples so a flat curve does not allocate and retain every segment alongside its output
fn segment_samples(points: &[Vec2], closed: bool, step: f32) -> impl Iterator<Item = impl Iterator<Item = Vec2>> + '_ {
fn segment_samples<'a>(points: &'a [Vec2], corners: &'a [bool], closed: bool, step: f32) -> impl Iterator<Item = impl Iterator<Item = Vec2> + 'a> + 'a {
let n = points.len();
let at = move |i: isize| {
let i = if closed { i.rem_euclid(n as isize) } else { i.clamp(0, n as isize - 1) };
points.get(i as usize).copied().unwrap_or_default()
};
let wrap = move |i: isize| if closed { i.rem_euclid(n as isize) } else { i.clamp(0, n as isize - 1) };
let at = move |i: isize| points.get(wrap(i) as usize).copied().unwrap_or_default();
let corner = move |i: isize| corners.get(wrap(i) as usize).copied().unwrap_or(false);
let step = if step.is_finite() && step > 1e-6 { step } else { 1.0 };
let segments = if n < 2 {
0
@@ -36,7 +46,11 @@ fn segment_samples(points: &[Vec2], closed: bool, step: f32) -> impl Iterator<It
n - 1
} as isize;
(0..segments).map(move |s| {
let (p0, p1, p2, p3) = (at(s - 1), at(s), at(s + 1), at(s + 2));
let (p1, p2) = (at(s), at(s + 1));
// A corner ends its run: the neighbour beyond it is replaced by the corner itself
let p0 = if corner(s) { p1 } else { at(s - 1) };
let p3 = if corner(s + 1) { p2 } else { at(s + 2) };
let k = ((p2 - p1).length() / step).ceil().clamp(1.0, MAX_SEGMENT_SAMPLES) as usize;
(1..=k).map(move |j| {
let t = j as f32 / k as f32;
@@ -100,6 +114,59 @@ mod tests {
assert_eq!(spline(&pts[..1], false, f32::NAN), vec![pts[0]]);
}
fn square() -> [Vec2; 4] {
[Vec2::new(0.0, 0.0), Vec2::new(10.0, 0.0), Vec2::new(10.0, 10.0), Vec2::new(0.0, 10.0)]
}
/// Distance from `p` to the closed polygon `poly`
fn edge_distance(poly: &[Vec2], p: Vec2) -> f32 {
poly.iter()
.zip(poly.iter().cycle().skip(1))
.map(|(a, b)| {
let e = *b - *a;
(*a + e * ((p - *a).dot(e) / e.length_squared()).clamp(0.0, 1.0)).distance(p)
})
.fold(f32::MAX, f32::min)
}
#[test]
fn all_corner_closed_path_is_the_straight_edged_quadrilateral() {
let pts = square();
let curve = spline_with_corners(&pts, &[true; 4], true, 0.5);
assert!(curve.len() > 40);
for p in &curve {
assert!(edge_distance(&pts, *p) < 1e-3, "{p} left the edges");
}
for corner in pts {
assert!(curve.iter().any(|q| q.distance(corner) < 1e-4), "{corner}");
}
let smooth = spline(&pts, true, 0.5);
assert!(smooth.iter().any(|q| edge_distance(&pts, *q) > 0.5), "the smooth curve bulges off the edges");
}
#[test]
fn mixed_corners_split_the_spline_into_runs() {
let pts = [Vec2::new(0.0, 0.0), Vec2::new(10.0, 8.0), Vec2::new(20.0, 0.0), Vec2::new(30.0, 8.0), Vec2::new(40.0, 0.0)];
let corners = [false, false, true, false, false];
let mixed = spline_segments_with_corners(&pts, &corners, false, 0.5);
let smooth = spline_segments(&pts, false, 0.5);
// The segments next to the corner differ; the corner point itself is still reached
assert_ne!(mixed[1], smooth[1]);
assert_ne!(mixed[2], smooth[2]);
assert_eq!(mixed[1].last().copied(), Some(pts[2]));
// Neither side of the corner overshoots past it: the turn is a cusp, not a loop
let before = mixed[1][mixed[1].len() - 2];
let after = mixed[2][0];
assert!(before.x < 20.0 && after.x > 20.0);
// Pure smooth input is unchanged, and a short or missing flag list means smooth
assert_eq!(spline_segments_with_corners(&pts, &[], false, 0.5), smooth);
assert_eq!(spline_segments_with_corners(&pts, &[false; 5], false, 0.5), smooth);
assert_eq!(spline_with_corners(&pts, &[false, false], false, 0.5), spline(&pts, false, 0.5));
}
#[test]
fn lasso_covers_the_inside_with_a_soft_edge() {
let sq = Lasso::new(vec![Vec2::new(0.0, 0.0), Vec2::new(10.0, 0.0), Vec2::new(10.0, 10.0), Vec2::new(0.0, 10.0)]);
+302 -53
View File
@@ -2,17 +2,25 @@
//! painting the tool's material. The carried values are kept straight (not premultiplied) per
//! channel next to the stroke alpha, so the live preview and the commit read them directly.
use std::collections::BTreeMap;
use std::collections::{BTreeMap, BTreeSet};
use std::sync::Arc;
use texturecraft_compose::Composite;
use texturecraft_compose::eval::FlatTile;
use texturecraft_compose::{Composite, MASK_CHANNEL, PaintTarget};
use texturecraft_core::Channel;
use texturecraft_geom::{NO_TRI, UvGBuffer};
use texturecraft_texel::{TILE_AREA, TileImage, from_u16, to_u16};
use texturecraft_texel::{TILE, TILE_AREA, TileImage, from_u16, to_u16};
use crate::StampSource;
use crate::commit::{dec, enc};
mod lane;
mod pickup_snapshot;
pub use pickup_snapshot::PickupSnapshot;
use lane::Lane;
/// How a pickup stroke finds the values it deposits.
#[derive(Clone, Copy, Debug, PartialEq)]
pub enum PickupMode {
@@ -32,12 +40,18 @@ pub struct Pickup {
/// How much of `source` there is to read per texel (a single layer's coverage); None reads
/// everywhere.
coverage: Option<TileImage>,
mask: bool,
snapshot: Option<Arc<PickupSnapshot>>,
loaded: BTreeSet<(u32, u32)>,
/// Texels outside the texture set's UV islands are never read.
gbuf: Arc<UvGBuffer>,
/// Straight values per painted channel; the stroke alpha lives in the stroke canvas.
pub values: BTreeMap<Channel, TileImage>,
/// Previous smudge stamp center (texels).
prev: Option<[f32; 2]>,
/// Smudge with symmetry: each copy drags its own trail (see [`Pickup::isolate_copies`]).
isolated: bool,
lanes: Vec<Lane>,
/// Per-stamp scratch: texels that receive values, and the values read for them.
reads: Vec<(u32, u32, f32)>,
read_values: Vec<[f32; 3]>,
@@ -56,7 +70,21 @@ impl Pickup {
/// A pickup reading `source` (whose resolution is the stroke's) for `channels`.
pub fn new(mode: PickupMode, source: Composite, gbuf: Arc<UvGBuffer>, channels: impl IntoIterator<Item = Channel>) -> Pickup {
let values = channels.into_iter().map(|c| (c, TileImage::new(source.resolution, source.height, c.components()))).collect();
Pickup { mode, source, coverage: None, gbuf, values, prev: None, reads: Vec::new(), read_values: Vec::new() }
Pickup {
mode,
source,
coverage: None,
mask: false,
snapshot: None,
loaded: BTreeSet::new(),
gbuf,
values,
prev: None,
isolated: false,
lanes: Vec::new(),
reads: Vec::new(),
read_values: Vec::new(),
}
}
/// A pickup reading one layer alone, from its flattened tiles (premultiplied values plus
@@ -64,10 +92,18 @@ impl Pickup {
/// layer is empty the stroke deposits nothing.
pub fn from_layer(mode: PickupMode, flat: &[FlatTile], size: (u32, u32), gbuf: Arc<UvGBuffer>, channels: impl IntoIterator<Item = Channel>) -> Pickup {
let channels: Vec<Channel> = channels.into_iter().collect();
let mut source = Composite::with_size(&channels, size.0, size.1);
let mut coverage = TileImage::new(size.0, size.1, 1);
let source = Composite::with_size(&channels, size.0, size.1);
let mut pickup = Self::new(mode, source, gbuf, channels);
pickup.coverage = Some(TileImage::new(size.0, size.1, 1));
pickup.add_layer_tiles(flat);
pickup
}
fn add_layer_tiles(&mut self, flat: &[FlatTile]) {
let Some(coverage) = self.coverage.as_mut() else { return };
for (c, (tx, ty), data) in flat {
let Some(img) = source.channels.get_mut(c) else { continue };
let Some(img) = self.source.channels.get_mut(c) else { continue };
let (n, kind) = (c.components(), c.kind());
let mut straight = vec![0u16; TILE_AREA * n];
let Some(cov) = coverage.tile_mut(*tx, *ty, &[0]) else { continue };
@@ -88,75 +124,192 @@ impl Pickup {
}
img.set_tile(*tx, *ty, Some(Arc::new(straight)));
}
let mut p = Pickup::new(mode, source, gbuf, channels);
p.coverage = Some(coverage);
p
}
fn covered(&self, x: u32, y: u32) -> bool {
let i = y as usize * self.gbuf.width as usize + x as usize;
x < self.gbuf.width && self.gbuf.tri.get(i).is_some_and(|t| *t != NO_TRI)
/// A pickup reading mask `values` (one component per texel, at the stroke's size): the stroke
/// carries mask values under [`MASK_CHANNEL`].
pub fn from_mask(mode: PickupMode, values: TileImage, gbuf: Arc<UvGBuffer>) -> Pickup {
let mut source = Composite::with_size(&[MASK_CHANNEL], values.width(), values.height());
source.channels.insert(MASK_CHANNEL, values);
let mut pickup = Pickup::new(mode, source, gbuf, [MASK_CHANNEL]);
pickup.mask = true;
pickup
}
/// Blend one stamp's texels `(x, y, alpha)` (stamp center `center` in texels) into the
/// stroke `alpha` and the carried values. False when nothing was deposited: the first smudge
/// stamp only picks up.
pub fn stamp(&mut self, alpha: &mut TileImage, texels: &[(u32, u32, f32)], center: [f32; 2]) -> bool {
/// Evaluate only the source tiles read by this stroke, sharing each tile across its stamps.
pub fn from_snapshot(mode: PickupMode, snapshot: PickupSnapshot, gbuf: Arc<UvGBuffer>, channels: impl IntoIterator<Item = Channel>) -> Self {
let mask = matches!(snapshot.target, PaintTarget::Mask(_));
let channels = if mask { vec![MASK_CHANNEL] } else { channels.into_iter().collect() };
let source = Composite::with_size(&channels, gbuf.width, gbuf.height);
let coverage = (!mask).then(|| TileImage::new(gbuf.width, gbuf.height, 1));
let mut pickup = Self::new(mode, source, gbuf, channels);
pickup.coverage = coverage;
pickup.mask = mask;
pickup.snapshot = Some(Arc::new(snapshot));
pickup
}
/// Only a mask pickup can supply coverage to a mask preview or commit.
pub fn mask_values(&self) -> Option<&TileImage> {
self.mask.then(|| self.values.get(&MASK_CHANNEL)).flatten()
}
fn load_tiles(&mut self, texels: &[(u32, u32, f32)], shift: [i64; 2]) {
let Some(snapshot) = &self.snapshot else { return };
let mut missing = Vec::new();
let mut previous = None;
for &(x, y, alpha) in texels {
let Ok(x) = u32::try_from(i64::from(x).saturating_add(shift[0])) else { continue };
let Ok(y) = u32::try_from(i64::from(y).saturating_add(shift[1])) else { continue };
let tile = (x / TILE, y / TILE);
if previous == Some(tile) || alpha <= 0.0 || !covered(&self.gbuf, x, y) {
continue;
}
previous = Some(tile);
if self.loaded.insert(tile) {
missing.push(tile);
}
}
if missing.is_empty() {
return;
}
let Some(inputs) = snapshot.inputs(&self.gbuf) else { return };
match snapshot.target {
PaintTarget::Layer(id) => {
if let Some(flat) = texturecraft_compose::flatten_layer(&inputs, id, &missing) {
self.add_layer_tiles(&flat);
}
}
PaintTarget::Mask(owner) => {
if let Some(output) = self.source.channels.get_mut(&MASK_CHANNEL) {
texturecraft_compose::eval::mask_values_into(&inputs, owner, &missing, output);
}
}
}
}
/// Smudge with symmetry: every copy of the stamp (told apart by its [`StampSource`]) drags
/// its own trail. A copy reads the texture as it was when the stroke began plus what it
/// deposited itself, never what another copy deposited, so copies where they overlap (at the
/// mirror plane) do not smear each other. Their deposits still blend into the stroke, later
/// copies over earlier ones.
pub fn isolate_copies(&mut self) {
self.isolated = true;
}
/// Blend one stamp's texels `(x, y, alpha)` (stamp center `center` in texels, `source` the
/// symmetry copy it belongs to, None for the stroke itself) into the stroke `alpha` and the
/// carried values. False when nothing was deposited: the first smudge stamp only picks up.
pub fn stamp(&mut self, alpha: &mut TileImage, texels: &[(u32, u32, f32)], center: [f32; 2], source: Option<StampSource>) -> bool {
if texels.is_empty() {
return false;
}
let mut lane = if self.isolated && matches!(self.mode, PickupMode::Smudge { .. }) { Some(self.take_lane(source, alpha)) } else { None };
let (shift, strength, smudge) = match self.mode {
PickupMode::Clone { offset } => (offset, 1.0, false),
PickupMode::Smudge { strength } => {
let Some(prev) = self.prev.replace(center) else { return false };
let prev = match &mut lane {
Some(l) => l.prev.replace(center),
None => self.prev.replace(center),
};
let Some(prev) = prev else { return self.put_back(lane, false) };
let d = [center[0] - prev[0], center[1] - prev[1]];
// A jump (UV seam, lifted cursor) has nothing to drag along.
// A jump across a UV seam or lifted cursor has nothing to drag along
if d[0].hypot(d[1]) > extent(texels) {
return false;
return self.put_back(lane, false);
}
// shortcut: nearest-texel pickup; bilinear would smooth sub-texel stamp spacing.
// Nearest-texel pickup avoids smoothing sub-texel stamp spacing
([-(d[0].round() as i64), -(d[1].round() as i64)], strength.clamp(0.0, 1.0), true)
}
};
self.load_tiles(texels, shift);
let (w, h) = (i64::from(self.source.resolution), i64::from(self.source.height));
self.reads.clear();
self.read_values.clear();
for &(x, y, a) in texels {
let (sx, sy) = (i64::from(x) + shift[0], i64::from(y) + shift[1]);
if !(a > 0.0 && (0..w).contains(&sx) && (0..h).contains(&sy) && self.covered(sx as u32, sy as u32)) {
// Saturate hostile offsets so the bounds check rejects them without overflow
let (sx, sy) = (i64::from(x).saturating_add(shift[0]), i64::from(y).saturating_add(shift[1]));
if !(a > 0.0 && (0..w).contains(&sx) && (0..h).contains(&sy) && covered(&self.gbuf, sx as u32, sy as u32)) {
continue;
}
let (sx, sy) = (sx as u32, sy as u32);
let a = a * strength * self.coverage.as_ref().map_or(1.0, |c| from_u16(c.get(sx, sy)[0]));
if a <= 0.0 {
continue;
}
// Smudge reads what the stroke shows so far: carried values over the source.
let m = if smudge { from_u16(alpha.get(sx, sy)[0]) } else { 0.0 };
for (c, img) in &self.values {
// Each smudge copy reads its own deposits over the original source
let (seen_alpha, seen_values) = match &lane {
Some(l) => (&l.alpha, &l.values),
None => (&*alpha, &self.values),
};
let m = if smudge { from_u16(seen_alpha.get(sx, sy)[0]) } else { 0.0 };
for c in self.values.keys() {
let base = self.source.value(*c, sx, sy);
let v = if m > 0.0 {
let carried = get(img, *c, sx, sy);
std::array::from_fn(|k| carried[k] * m + base[k] * (1.0 - m))
} else {
base
let v = match seen_values.get(c) {
Some(img) if m > 0.0 => {
let carried = get(img, *c, sx, sy);
std::array::from_fn(|k| carried[k] * m + base[k] * (1.0 - m))
}
_ => base,
};
self.read_values.push(v);
}
self.reads.push((x, y, a));
}
let n = self.values.len();
for (i, &(x, y, a)) in self.reads.iter().enumerate() {
let m = from_u16(alpha.get(x, y)[0]);
let m2 = a + m * (1.0 - a);
for (k, (c, img)) in self.values.iter_mut().enumerate() {
let Some(src) = self.read_values.get(i * n + k) else { continue };
let old = get(img, *c, x, y);
put(img, *c, x, y, std::array::from_fn(|j| (src[j] * a + old[j] * m * (1.0 - a)) / m2.max(1e-6)));
}
alpha.set(x, y, &[to_u16(m2)]);
if let Some(l) = &mut lane {
deposit(&mut l.alpha, &mut l.values, &self.reads, &self.read_values);
}
!self.reads.is_empty()
deposit(alpha, &mut self.values, &self.reads, &self.read_values);
let painted = !self.reads.is_empty();
self.put_back(lane, painted)
}
/// The lane of the copy `source`, started when the copy first stamps.
fn take_lane(&mut self, source: Option<StampSource>, alpha: &TileImage) -> Lane {
match self.lanes.iter().position(|l| l.source == source) {
Some(i) => self.lanes.swap_remove(i),
None => {
let values = self.values.iter().map(|(c, img)| (*c, TileImage::new(img.width(), img.height(), c.components()))).collect();
Lane { source, prev: None, alpha: TileImage::new(alpha.width(), alpha.height(), 1), values }
}
}
}
fn put_back(&mut self, lane: Option<Lane>, painted: bool) -> bool {
self.lanes.extend(lane);
painted
}
}
fn covered(gbuf: &UvGBuffer, x: u32, y: u32) -> bool {
if x >= gbuf.width || y >= gbuf.height {
return false;
}
let i = u64::from(y) * u64::from(gbuf.width) + u64::from(x);
usize::try_from(i).ok().and_then(|i| gbuf.tri.get(i)).is_some_and(|t| *t != NO_TRI)
}
/// Blend the texels `reads` `(x, y, alpha)` with their `read_values` (one entry per channel of
/// `values`, in order) into `alpha` and `values` ("over").
fn deposit(alpha: &mut TileImage, values: &mut BTreeMap<Channel, TileImage>, reads: &[(u32, u32, f32)], read_values: &[[f32; 3]]) {
let n = values.len();
for (i, &(x, y, a)) in reads.iter().enumerate() {
let m = from_u16(alpha.get(x, y)[0]);
let m2 = a + m * (1.0 - a);
for (k, (c, img)) in values.iter_mut().enumerate() {
let Some(src) = read_values.get(i * n + k) else { continue };
let old = get(img, *c, x, y);
put(img, *c, x, y, std::array::from_fn(|j| (src[j] * a + old[j] * m * (1.0 - a)) / m2.max(1e-6)));
}
alpha.set(x, y, &[to_u16(m2)]);
}
}
@@ -203,23 +356,82 @@ mod tests {
v
}
#[test]
fn layer_and_mask_pickups_only_evaluate_the_shifted_tiles_the_stroke_reads() {
use texturecraft_core::{Fill, Layer, LayerKind, Mask, MaskBackground, Project, Source, TextureSet};
let size = 4 * TILE;
let mesh = Arc::new(primitives::plane(2.0, 4));
let gbuf = Arc::new(UvGBuffer::new(&mesh, 0, size, size));
let mut project = Project::new("test", "builtin:plane");
project.texture_sets.push(TextureSet::new("Set", 0, size));
let id = project.alloc_id();
let fill = Fill { sources: [(Channel::Roughness, Source::Uniform([0.25; 3]))].into(), projection: Default::default(), link: None };
let mut layer = Layer::new(id, "fill", LayerKind::Fill(fill), &[Channel::Roughness]);
layer.mask = Some(Mask::new(MaskBackground::White));
project.insert_layer(0, layer, None, false).unwrap();
for (target, expected) in [(PaintTarget::Layer(id), 0.25), (PaintTarget::Mask(id), 1.0)] {
let snapshot = PickupSnapshot {
project: project.clone(),
ts: 0,
target,
mesh: mesh.clone(),
bounds: mesh.bounds(),
pixels: Default::default(),
baked: Default::default(),
images: Default::default(),
};
let mut pickup = Pickup::from_snapshot(PickupMode::Clone { offset: [i64::from(TILE), 0] }, snapshot, gbuf.clone(), [Channel::Roughness]);
let mut alpha = TileImage::new(size, size, 1);
assert!(pickup.loaded.is_empty());
for x in [8, 12, TILE + 8] {
assert!(pickup.stamp(&mut alpha, &[(x, 8, 1.0)], [x as f32, 8.0], None));
let image = &pickup.values[&Channel::Roughness];
assert!((from_u16(image.get(x, 8)[0]) - expected).abs() < 1e-4);
assert_eq!(pickup.mask_values().is_some(), matches!(target, PaintTarget::Mask(_)));
}
assert_eq!(pickup.loaded, [(1, 0), (2, 0)].into());
assert_eq!(pickup.source.channels[&Channel::Roughness].allocated_count(), 2);
}
}
#[test]
fn clone_copies_values_from_the_offset() {
let (c, g) = setup(|x| if x < 32 { 0.9 } else { 0.1 });
let mut p = Pickup::new(PickupMode::Clone { offset: [-30, 0] }, c, g, [Channel::Roughness]);
let mut alpha = TileImage::new(TILE, TILE, 1);
assert!(p.stamp(&mut alpha, &disc(45, 32, 4), [45.0, 32.0]));
assert!(p.stamp(&mut alpha, &disc(45, 32, 4), [45.0, 32.0], None));
let v = get(&p.values[&Channel::Roughness], Channel::Roughness, 45, 32);
assert!((v[0] - 0.9).abs() < 1e-3, "{v:?}");
assert!(from_u16(alpha.get(45, 32)[0]) > 0.99);
// Sources outside the image are skipped.
assert!(!p.stamp(&mut alpha, &disc(5, 5, 2), [5.0, 5.0]));
// Sources outside the image are skipped
assert!(!p.stamp(&mut alpha, &disc(5, 5, 2), [5.0, 5.0], None));
}
#[test]
fn clone_skips_offsets_outside_the_coordinate_range() {
for offset in [[i64::MAX, 0], [0, i64::MAX], [i64::MIN, 0], [0, i64::MIN]] {
let (composite, gbuf) = setup(|_| 0.5);
let mut pickup = Pickup::new(PickupMode::Clone { offset }, composite, gbuf, [Channel::Roughness]);
let mut alpha = TileImage::new(TILE, TILE, 1);
let painted = pickup.stamp(&mut alpha, &[(1, 1, 1.0)], [1.0, 1.0], None);
assert!(!painted);
assert_eq!(alpha.allocated_count(), 0);
assert_eq!(pickup.values[&Channel::Roughness].allocated_count(), 0);
}
}
#[test]
fn layer_clones_copy_only_where_the_layer_has_paint() {
let (_, g) = setup(|_| 0.0);
// The layer: roughness 0.8 at half coverage on the left half (premultiplied).
// The layer has roughness 0.8 at half coverage on its left half
let mut data = vec![0u16; TILE_AREA * 2];
for y in 0..TILE {
for x in 0..TILE / 2 {
@@ -231,13 +443,14 @@ mod tests {
let flat = vec![(Channel::Roughness, (0, 0), data)];
let mut p = Pickup::from_layer(PickupMode::Clone { offset: [-30, 0] }, &flat, (TILE, TILE), g.clone(), [Channel::Roughness]);
let mut alpha = TileImage::new(TILE, TILE, 1);
assert!(p.stamp(&mut alpha, &disc(45, 32, 3), [45.0, 32.0]));
assert!(p.stamp(&mut alpha, &disc(45, 32, 3), [45.0, 32.0], None));
let v = get(&p.values[&Channel::Roughness], Channel::Roughness, 45, 32)[0];
assert!((v - 0.8).abs() < 1e-3, "straight value: {v}");
assert!((from_u16(alpha.get(45, 32)[0]) - 0.5).abs() < 1e-3, "the layer's coverage scales the stroke");
// Reading the layer's empty right half deposits nothing.
// Reading the layer's empty right half deposits nothing
let mut q = Pickup::from_layer(PickupMode::Clone { offset: [30, 0] }, &flat, (TILE, TILE), g, [Channel::Roughness]);
assert!(!q.stamp(&mut TileImage::new(TILE, TILE, 1), &disc(20, 32, 3), [20.0, 32.0]), "the source is the empty half");
assert!(!q.stamp(&mut TileImage::new(TILE, TILE, 1), &disc(20, 32, 3), [20.0, 32.0], None), "the source is the empty half");
}
#[test]
@@ -245,13 +458,49 @@ mod tests {
let (c, g) = setup(|x| if x < 20 { 1.0 } else { 0.0 });
let mut p = Pickup::new(PickupMode::Smudge { strength: 1.0 }, c, g, [Channel::Roughness]);
let mut alpha = TileImage::new(TILE, TILE, 1);
assert!(!p.stamp(&mut alpha, &disc(18, 32, 5), [18.0, 32.0]), "the first stamp only picks up");
assert!(!p.stamp(&mut alpha, &disc(18, 32, 5), [18.0, 32.0], None), "the first stamp only picks up");
for cx in 20..30 {
p.stamp(&mut alpha, &disc(cx, 32, 5), [cx as f32, 32.0]);
p.stamp(&mut alpha, &disc(cx, 32, 5), [cx as f32, 32.0], None);
}
let v = get(&p.values[&Channel::Roughness], Channel::Roughness, 30, 32)[0];
assert!(v > 0.5 && from_u16(alpha.get(30, 32)[0]) > 0.99, "white dragged to the right: {v}");
// A jump larger than the stamp deposits nothing.
assert!(!p.stamp(&mut alpha, &disc(50, 10, 3), [50.0, 10.0]));
// A jump larger than the stamp deposits nothing
assert!(!p.stamp(&mut alpha, &disc(50, 10, 3), [50.0, 10.0], None));
}
/// Two copies smudging through the same texels: copy B drags exactly what it would alone.
#[test]
fn mirrored_smudge_copies_do_not_feed_each_other() {
use texturecraft_geom::glam::{Mat3, Vec3};
let source = |x: f32| Some(StampSource { origin: Vec3::ZERO, to_source: Mat3::from_diagonal(Vec3::new(x, 1.0, 1.0)) });
let (a, b) = (source(1.0), source(-1.0));
let smudge = || {
let (c, g) = setup(|x| if x < 20 { 1.0 } else { 0.0 });
Pickup::new(PickupMode::Smudge { strength: 1.0 }, c, g, [Channel::Roughness])
};
// A drags white right along row 32 while B drags left through the same texels
let (mut alone, mut isolated) = (smudge(), smudge());
isolated.isolate_copies();
let (mut alpha_alone, mut alpha_isolated) = (TileImage::new(TILE, TILE, 1), TileImage::new(TILE, TILE, 1));
for i in 0..24 {
let (xa, xb) = (18.0 + i as f32, 46.0 - i as f32);
for (pickup, alpha, copies) in [(&mut isolated, &mut alpha_isolated, true), (&mut alone, &mut alpha_alone, false)] {
if copies {
pickup.stamp(alpha, &disc(xa as u32, 32, 5), [xa, 32.0], a);
}
pickup.stamp(alpha, &disc(xb as u32, 32, 5), [xb, 32.0], b);
}
}
let lane_b = isolated.lanes.iter().find(|l| l.source == b).expect("copy B has its lane");
let (mut stroke_differs, mut lane_differs) = (false, false);
for x in 14..52 {
let alone_value = get(&alone.values[&Channel::Roughness], Channel::Roughness, x, 32)[0];
lane_differs |= (get(&lane_b.values[&Channel::Roughness], Channel::Roughness, x, 32)[0] - alone_value).abs() > 1e-4;
stroke_differs |= (get(&isolated.values[&Channel::Roughness], Channel::Roughness, x, 32)[0] - alone_value).abs() > 1e-4;
}
assert!(!lane_differs, "copy B drags what it would drag alone");
assert!(stroke_differs, "the stroke shows both copies where they overlap");
}
}
+15
View File
@@ -0,0 +1,15 @@
use std::collections::BTreeMap;
use texturecraft_core::Channel;
use texturecraft_texel::TileImage;
use crate::StampSource;
/// What one symmetry copy of a smudge stroke carries: its own previous stamp and deposits
#[derive(Clone, Debug)]
pub(super) struct Lane {
pub(super) source: Option<StampSource>,
pub(super) prev: Option<[f32; 2]>,
pub(super) alpha: TileImage,
pub(super) values: BTreeMap<Channel, TileImage>,
}
@@ -0,0 +1,36 @@
use std::sync::Arc;
use texturecraft_compose::{BakedMaps, ImageStore, Inputs, PaintTarget, PixelStore};
use texturecraft_core::Project;
use texturecraft_geom::{Mesh, UvGBuffer};
/// Compositor inputs frozen at stroke start. A mask target identifies the layer that owns it.
#[derive(Clone, Debug)]
pub struct PickupSnapshot {
pub project: Project,
pub ts: usize,
pub target: PaintTarget,
pub mesh: Arc<Mesh>,
pub bounds: (texturecraft_geom::glam::Vec3, texturecraft_geom::glam::Vec3),
pub pixels: PixelStore,
pub baked: BakedMaps,
pub images: ImageStore,
}
impl PickupSnapshot {
pub(super) fn inputs<'a>(&'a self, gbuf: &'a UvGBuffer) -> Option<Inputs<'a>> {
let set = self.project.texture_sets.get(self.ts)?;
Some(Inputs {
project: &self.project,
ts: self.ts,
mesh: &self.mesh,
gbuf,
pixels: &self.pixels,
baked: &self.baked,
block_scales: set.block_scales(),
preview: None,
images: &self.images,
bounds: self.bounds,
})
}
}
+11 -1
View File
@@ -22,7 +22,7 @@ impl BrushPreset {
}
/// `brush` with the stroke of `from` (shape, flow, opacity, spacing, hardness, angle, path
/// following, jitters and particles): what a preset sets.
/// following, jitters, particles and the alpha's parameters): what a preset sets.
pub fn with_stroke_of(brush: &BrushSettings, from: &BrushSettings) -> BrushSettings {
BrushSettings {
flow: from.flow,
@@ -38,6 +38,7 @@ pub fn with_stroke_of(brush: &BrushSettings, from: &BrushSettings) -> BrushSetti
alpha: from.alpha,
alpha_image: from.alpha_image.clone(),
alpha_library: from.alpha_library.clone(),
alpha_params: from.alpha_params,
particles: from.particles,
..brush.clone()
}
@@ -178,6 +179,15 @@ pub const PRESETS: [BrushPreset; 18] = [
#[cfg(test)]
mod tests {
use super::*;
use crate::alpha_params::AlphaParams;
#[test]
fn a_saved_brush_brings_its_alpha_parameters_and_a_built_in_preset_resets_them() {
let params = AlphaParams { size_x: 0.5, invert: true, ..AlphaParams::default() };
let saved = BrushSettings { alpha_params: params, ..BrushSettings::default() };
assert_eq!(with_stroke_of(&BrushSettings::default(), &saved).alpha_params, params);
assert_eq!(PRESETS[0].applied(&saved).alpha_params, AlphaParams::default());
}
#[test]
fn presets_are_unique_valid_and_keep_the_setup() {
+19 -13
View File
@@ -11,6 +11,7 @@ use texturecraft_texel::{TILE, TileImage, from_u16, to_u16};
use crate::brush::Shape;
use crate::pickup::Pickup;
use crate::stamp_source::StampSource;
use crate::stroke::Stamp;
use crate::visibility::EyeDepth;
@@ -52,7 +53,7 @@ impl StrokeCanvas {
/// Blend the gathered stamp texels (stamp center `center` in texels) into the stroke: the
/// quick mask scales them, then the pickup deposits its values or the alpha accumulates
/// ("over": `m = a + m·(1 − a)`).
fn add_stamp(&mut self, center: [f32; 2]) {
fn add_stamp(&mut self, center: [f32; 2], source: Option<StampSource>) {
let mut texels = std::mem::take(&mut self.texels);
if let Some((mask, invert)) = &self.limit {
for t in &mut texels {
@@ -61,7 +62,7 @@ impl StrokeCanvas {
}
}
let painted = match &mut self.pickup {
Some(p) => p.stamp(&mut self.alpha, &texels, center),
Some(p) => p.stamp(&mut self.alpha, &texels, center, source),
None => {
for &(x, y, a) in &texels {
let m = from_u16(self.alpha.get(x, y)[0]);
@@ -216,7 +217,7 @@ pub fn rasterize(canvas: &mut StrokeCanvas, context: &RasterCtx, stamps: &[Stamp
canvas.texels.extend(texels);
}
canvas.add_stamp(center.0);
canvas.add_stamp(center.0, stamp.source);
}
}
@@ -338,7 +339,7 @@ pub fn fill_coverage(canvas: &mut StrokeCanvas, gbuf: &UvGBuffer, coverage: impl
(a > 0.0).then_some(((i as u32) % w, (i as u32) / w, a))
})
.collect();
canvas.add_stamp([0.0; 2]);
canvas.add_stamp([0.0; 2], None);
}
#[cfg(test)]
@@ -383,7 +384,7 @@ mod tests {
eye: camera.eye(),
backface_culling: false,
angle_fade: (89.0, 90.0),
shape: Shape { alpha: crate::BrushAlpha::Round, image: None, library: None, level: 0 },
shape: Shape { alpha: crate::BrushAlpha::Round, image: None, library: None, params: Default::default(), level: 0 },
};
let stamp = Stamp {
center: Vec3::new(0.0, 0.03, 0.0),
@@ -428,7 +429,7 @@ mod tests {
eye: camera.eye(),
backface_culling: true,
angle_fade: (89.0, 90.0),
shape: Shape { alpha: crate::BrushAlpha::Round, image: None, library: None, level: 0 },
shape: Shape { alpha: crate::BrushAlpha::Round, image: None, library: None, params: Default::default(), level: 0 },
};
let point = Vec3::ZERO;
let to_eye = (camera.eye() - point).normalize();
@@ -459,7 +460,7 @@ mod tests {
eye: camera.eye(),
backface_culling: true,
angle_fade: (89.0, 90.0),
shape: Shape { alpha: crate::BrushAlpha::Round, image: None, library: None, level: 0 },
shape: Shape { alpha: crate::BrushAlpha::Round, image: None, library: None, params: Default::default(), level: 0 },
};
let point = Vec3::new(1.0, 0.0, 0.0);
let to_eye = (camera.eye() - point).normalize();
@@ -485,7 +486,7 @@ mod tests {
eye: camera.eye(),
backface_culling: false,
angle_fade: (89.0, 90.0),
shape: Shape { alpha: crate::BrushAlpha::Round, image: None, library: None, level: 0 },
shape: Shape { alpha: crate::BrushAlpha::Round, image: None, library: None, params: Default::default(), level: 0 },
};
let to_eye = -camera.forward();
let behind = context.eye + to_eye;
@@ -547,7 +548,7 @@ mod tests {
eye: camera.eye(),
backface_culling: culling,
angle_fade: (89.0, 90.0),
shape: Shape { alpha: crate::BrushAlpha::Round, image: None, library: None, level: 0 },
shape: Shape { alpha: crate::BrushAlpha::Round, image: None, library: None, params: Default::default(), level: 0 },
};
let stamp =
Stamp { center, normal: Vec3::Y, tangent: Vec3::X, bitangent: Vec3::Z, radius, flow: 1.0, hardness: 0.9, depth: 1.0, seed: 0, source: None };
@@ -676,7 +677,7 @@ mod tests {
eye: camera.eye(),
backface_culling: false,
angle_fade: (89.0, 90.0),
shape: Shape { alpha: crate::BrushAlpha::Round, image: None, library: None, level: 0 },
shape: Shape { alpha: crate::BrushAlpha::Round, image: None, library: None, params: Default::default(), level: 0 },
};
// A silhouette normal is perpendicular to the direction from the surface to the eye
@@ -746,7 +747,7 @@ mod tests {
eye: Vec3::new(0.0, 5.0, 0.0),
backface_culling: true,
angle_fade: (70.0, 85.0),
shape: Shape { alpha: crate::BrushAlpha::Round, image: None, library: None, level: 0 },
shape: Shape { alpha: crate::BrushAlpha::Round, image: None, library: None, params: Default::default(), level: 0 },
};
let stamp = Stamp {
center: Vec3::ZERO,
@@ -789,6 +790,9 @@ pub struct UvStamp {
pub flow: f32,
pub hardness: f32,
pub seed: u32,
/// The symmetry copy this dab belongs to (None: the stroke itself), so a smudge's copies each
/// drag their own trail as in the 3D view
pub source: Option<StampSource>,
}
/// Accumulate UV-space stamps into `canvas` (only texels covered by the texture set).
@@ -799,6 +803,7 @@ pub fn rasterize_uv(canvas: &mut StrokeCanvas, gbuf: &UvGBuffer, shape: Shape, s
if s.radius.is_nan() || s.radius <= 0.0 || !s.center.is_finite() {
continue;
}
let (cx, cy, r) = (s.center.x * w as f32, s.center.y * h as f32, s.radius * w as f32);
let x0 = (cx - r * 1.42).floor().max(0.0) as u32;
let x1 = ((cx + r * 1.42).ceil().max(0.0) as u32).min(w);
@@ -811,7 +816,8 @@ pub fn rasterize_uv(canvas: &mut StrokeCanvas, gbuf: &UvGBuffer, shape: Shape, s
if gbuf.tri.get((y * w + x) as usize).copied().unwrap_or(NO_TRI) == NO_TRI {
continue;
}
// Local frame with y up on screen (texel rows grow downward), as in the 3D view.
// Local frame with y up on screen (texel rows grow downward), as in the 3D view
let (dx, dy) = ((x as f32 + 0.5 - cx) / r, (cy - y as f32 - 0.5) / r);
let (lx, ly) = (dx * cs + dy * sn, -dx * sn + dy * cs);
let a = shape.sample(lx, ly, s.hardness, s.seed) * s.flow;
@@ -820,6 +826,6 @@ pub fn rasterize_uv(canvas: &mut StrokeCanvas, gbuf: &UvGBuffer, shape: Shape, s
}
}
}
canvas.add_stamp([cx, cy]);
canvas.add_stamp([cx, cy], s.source);
}
}
+5
View File
@@ -265,6 +265,11 @@ impl Stroke {
copies
}
/// The center of the mesh the stroke paints, which the symmetry planes are measured from
pub fn center(&self) -> Vec3 {
self.center
}
pub fn last_hit(&self) -> Option<SurfaceHit> {
self.last
}
+10
View File
@@ -0,0 +1,10 @@
use crate::list_action::ListAction;
/// A question waiting for an answer in the Output templates tab
#[derive(Clone, Debug, PartialEq)]
pub enum Ask {
/// Delete this template (its file goes with it)
Delete(String),
/// Leave the selected template, whose last edit does not validate and is not saved, for this
Leave(ListAction),
}
+18 -1
View File
@@ -7,7 +7,9 @@
//! - `session.inspect`: project, texture sets, layer stack, tool, camera, display, history.
//! - `ui.inspect`: the UI state (panels, windows, mode, layout, viewport rect, who draws the title bar).
//! - `ui.menu.list`: the menu catalog with ids, shortcuts and whether each is live.
//! - `ui.menu.invoke {id}`: behave like a menu click (may open a window).
//! - `ui.menu.invoke {id}`: behave like a menu click (may open a window; `ui.resetUi` asks first).
//! `{id: "ui.layout.apply", name}` switches to the saved panel layout `name` (an error when there is none).
//! - `ui.reset`: reset the panels and every view setting at once, without the question the menu asks.
//! - `ui.set {...}`: merge fields into the UI state (e.g. `{"layout":"Only3D"}`).
//! - `viewport.screenshot {view?: "3d"|"2d"}`: PNG of a viewport, base64.
//! - `ui.screenshot`: PNG of the whole window (replies after the next frame).
@@ -101,6 +103,7 @@ pub fn handle(app: &mut TextureCraftApp, ctx: &egui::Context, method: &str, para
"command.run" => {
let Some(id) = params.get("id").and_then(Value::as_str) else { return err("`id` is required") };
let command_params = params.get("params").cloned().unwrap_or(Value::Null);
let before = app.session.camera;
match texturecraft_engine::execute(&mut app.session, id, &command_params) {
Ok(value) => {
if matches!(id, "brush.preset.store" | "brush.preset.rename" | "brush.preset.delete") {
@@ -119,6 +122,9 @@ pub fn handle(app: &mut TextureCraftApp, ctx: &egui::Context, method: &str, para
app.ui.windows.export = false;
}
// A command that moved the camera takes over from a glide in progress; a projection switch joins it
app.settle_camera_glide(id, before);
ok(value)
}
Err(error) => err(error),
@@ -187,6 +193,11 @@ pub fn handle(app: &mut TextureCraftApp, ctx: &egui::Context, method: &str, para
)),
"ui.menu.invoke" => {
let Some(id) = params.get("id").and_then(Value::as_str) else { return err("`id` is required") };
if id == "ui.layout.apply" {
let Some(name) = params.get("name").and_then(Value::as_str) else { return err("`name` is required") };
return if app.ui.apply_named_layout(name) { ok(Value::Null) } else { err(format!("no saved layout named `{name}`")) };
}
if !crate::menus::implemented(id) {
return err(format!("menu item `{id}` is not implemented"));
}
@@ -194,6 +205,12 @@ pub fn handle(app: &mut TextureCraftApp, ctx: &egui::Context, method: &str, para
crate::menus::invoke(app, ctx, id);
ok(Value::Null)
}
// What Window > Reset UI does once the question is answered with Reset
"ui.reset" => {
app.ui.adopt_layout(crate::UiState::default());
ok(Value::Null)
}
"ui.set" => {
let mut current_state = serde_json::to_value(&app.ui).unwrap_or(Value::Null);
if let (Some(object), Some(patch)) = (current_state.as_object_mut(), params.as_object()) {
File diff suppressed because it is too large. Load diff
+149 -21
View File
@@ -120,6 +120,14 @@ fn is_rgb(d: Dest) -> bool {
fn set_layout(map: &mut MapSpec, layout: Layout) {
let get = |d: Dest| map.channels.iter().find(|(x, _)| *x == d).map(|(_, s)| s.clone());
let color = get(Dest::R).or_else(|| get(Dest::L)).unwrap_or(SourceRef::Constant(0.0));
// A source that moves to a new channel keeps its inversion
let color_inverted = map.inverted.contains(if get(Dest::R).is_some() { &Dest::R } else { &Dest::L });
let was_inverted = |d: Dest| match get(d) {
Some(_) => map.inverted.contains(&d),
None => !matches!(d, Dest::A) && color_inverted,
};
let inverted: Vec<Dest> = layout.dests().iter().copied().filter(|&d| was_inverted(d)).collect();
let channels = layout
.dests()
.iter()
@@ -132,10 +140,11 @@ fn set_layout(map: &mut MapSpec, layout: Layout) {
})
.collect();
map.channels = channels;
map.inverted = inverted;
}
fn new_map(layout: Layout) -> MapSpec {
let mut map = MapSpec { file: "$mesh_$textureSet_Output".into(), format: FileFormat::Png, bit_depth: 8, channels: Vec::new() };
let mut map = MapSpec { file: "$mesh_$textureSet_Output".into(), format: FileFormat::Png, bit_depth: 8, channels: Vec::new(), inverted: Vec::new() };
set_layout(&mut map, layout);
map
}
@@ -170,16 +179,8 @@ fn sync_draft(app: &mut TextureCraftApp) {
}
}
enum ListAction {
Select(String),
New,
Duplicate,
StartRename(String),
Rename(String),
Remove,
Import,
Export,
}
pub use crate::ask::Ask;
pub use crate::list_action::ListAction;
enum MapAction {
Add(Layout),
@@ -200,7 +201,7 @@ pub fn tab(app: &mut TextureCraftApp, ui: &mut Ui, builtins: &[ExportPreset]) {
});
ui.separator();
ui.vertical(|ui| {
// Leave room for the input maps column and two separators.
// Leave room for the input maps column and two separators
ui.set_width((ui.available_width() - INPUTS_WIDTH - 5.0 * ui.spacing().item_spacing.x - 4.0).max(200.0));
ui.set_height(height);
outputs(app, ui);
@@ -216,6 +217,16 @@ pub fn tab(app: &mut TextureCraftApp, ui: &mut Ui, builtins: &[ExportPreset]) {
}
}
/// Select template `name` from outside the list (the Settings tab's dropdown); an unfinished
/// edit of the current one is asked about first.
pub fn select(app: &mut TextureCraftApp, name: String) {
if name != app.ui.export.preset && unfinished(app).is_some() {
app.ui.export.ask = Some(Ask::Leave(ListAction::Select(name)));
} else {
app.ui.export.preset = name;
}
}
fn preset_list(app: &mut TextureCraftApp, ui: &mut Ui, builtins: &[ExportPreset]) -> Option<ListAction> {
let mut act = None;
let sel = app.ui.export.preset.clone();
@@ -278,7 +289,28 @@ fn preset_list(app: &mut TextureCraftApp, ui: &mut Ui, builtins: &[ExportPreset]
act
}
/// The error of the selected template's draft when it does not validate: that edit is not saved.
fn unfinished(app: &TextureCraftApp) -> Option<String> {
app.ui.export.draft.as_ref().and_then(|d| d.validate().err()).map(|e| e.to_string())
}
/// Run `act`; deleting a template and leaving one with an unfinished edit ask first.
fn apply(app: &mut TextureCraftApp, ctx: &egui::Context, act: ListAction) {
let leaves = match &act {
ListAction::Select(name) | ListAction::StartRename(name) => *name != app.ui.export.preset,
ListAction::New | ListAction::Duplicate | ListAction::Imported(_) => true,
_ => false,
};
if act == ListAction::Remove {
app.ui.export.ask = Some(Ask::Delete(app.ui.export.preset.clone()));
} else if leaves && unfinished(app).is_some() {
app.ui.export.ask = Some(Ask::Leave(act));
} else {
perform(app, ctx, act);
}
}
fn perform(app: &mut TextureCraftApp, ctx: &egui::Context, act: ListAction) {
app.ui.export.renaming = None;
match act {
ListAction::Select(name) => app.ui.export.preset = name,
@@ -297,18 +329,76 @@ fn apply(app: &mut TextureCraftApp, ctx: &egui::Context, act: ListAction) {
ctx.memory_mut(|m| m.request_focus(egui::Id::unique(RENAME_ID)));
}
ListAction::Rename(name) => rename(app, name.trim()),
ListAction::Remove => {
let name = app.ui.export.preset.clone();
if app.run("export.preset.remove", json!({ "name": name })).is_some() {
app.ui.export.preset = crate::state::ExportUi::default().preset;
app.toast(trf("Deleted template \"{name}\"", &[("name", &name)]), false);
}
}
ListAction::Remove => remove(app, app.ui.export.preset.clone()),
ListAction::Import => import_file(app, ctx),
ListAction::Imported(p) => add_imported(app, &p),
ListAction::Export => export_file(app),
}
}
fn remove(app: &mut TextureCraftApp, name: String) {
if app.run("export.preset.remove", json!({ "name": name })).is_some() {
if app.ui.export.preset == name {
app.ui.export.preset = crate::state::ExportUi::default().preset;
}
app.toast(trf("Deleted template \"{name}\"", &[("name", &name)]), false);
}
}
/// The open question, if any: Escape or Cancel keeps things as they are.
pub(crate) fn ask(app: &mut TextureCraftApp, ctx: &egui::Context) {
let Some(question) = app.ui.export.ask.clone() else { return };
// The edit was fixed while the question was open: nothing is dropped any more
if matches!(question, Ask::Leave(_)) && unfinished(app).is_none() {
app.ui.export.ask = None;
return;
}
let mut cancel = false;
let mut yes = false;
let (title, text, yes_label, no_label) = match &question {
Ask::Delete(name) => (
tr("Delete template"),
trf("Delete the template \"{name}\"? Its file is removed and this cannot be undone.", &[("name", name)]),
tr("Delete"),
tr("Cancel"),
),
Ask::Leave(_) => (
tr("Unfinished template edit"),
trf(
"The last edit of the template \"{name}\" is not saved: {error}. Switching away drops it.",
&[("name", &app.ui.export.preset), ("error", &unfinished(app).unwrap_or_default())],
),
tr("Discard changes"),
tr("Keep editing"),
),
};
egui::Window::new(title)
.id(egui::Id::unique("export_template_ask"))
.collapsible(false)
.resizable(false)
.anchor(egui::Align2::CENTER_CENTER, vec2(0.0, 0.0))
.show(ctx, |ui| {
ui.set_max_width(360.0);
ui.label(text);
ui.add_space(8.0);
ui.horizontal(|ui| {
yes = ui.button(yes_label).clicked();
cancel |= ui.button(no_label).clicked();
});
});
if yes {
app.ui.export.ask = None;
match question {
Ask::Delete(name) => remove(app, name),
Ask::Leave(act) => perform(app, ctx, act),
}
} else if cancel {
app.ui.export.ask = None;
}
}
/// Save `preset` as a new user preset (renamed when its name is taken) and select it.
fn save_new(app: &mut TextureCraftApp, preset: &ExportPreset) -> Option<String> {
let v = serde_json::to_value(preset).ok()?;
@@ -334,6 +424,14 @@ fn rename(app: &mut TextureCraftApp, name: &str) {
/// Add an imported preset (renamed when its name is taken) and select it.
pub fn import(app: &mut TextureCraftApp, preset: &ExportPreset) {
if unfinished(app).is_some() {
app.ui.export.ask = Some(Ask::Leave(ListAction::Imported(preset.clone())));
} else {
add_imported(app, preset);
}
}
fn add_imported(app: &mut TextureCraftApp, preset: &ExportPreset) {
if let Some(name) = save_new(app, preset) {
app.toast(trf("Imported template \"{name}\"", &[("name", &name)]), false);
}
@@ -587,7 +685,8 @@ fn channel_slots(ui: &mut Ui, mi: usize, map: &mut MapSpec) -> bool {
let tk = Tokens::get(ui.ctx());
let mut changed = false;
let mut dropped = None;
for (k, (dest, src)) in map.channels.iter_mut().enumerate() {
let MapSpec { channels, inverted, .. } = map;
for (k, (dest, src)) in channels.iter_mut().enumerate() {
ui.horizontal(|ui| {
let dest_name = match *dest {
Dest::L => tr("Gray"),
@@ -628,6 +727,14 @@ fn channel_slots(ui: &mut Ui, mi: usize, map: &mut MapSpec) -> bool {
}
_ => {}
}
let on = inverted.contains(dest);
if ui.selectable_label(on, tr("Invert")).on_hover_text(tr("Write 1 minus the value in this channel")).clicked() {
inverted.retain(|x| x != dest);
if !on {
inverted.push(*dest);
}
changed = true;
}
});
}
if let Some((dest, input)) = dropped {
@@ -649,7 +756,8 @@ fn input_maps(ui: &mut Ui) {
ui.horizontal_wrapped(|ui| {
for (k, (label, s)) in inputs.iter().enumerate() {
let label = tr(label);
// Not `dnd_drag_source`: its scope doesn't wrap inside `horizontal_wrapped`.
// `dnd_drag_source` cannot wrap inside `horizontal_wrapped`
let r = chip(ui, label, false).interact(egui::Sense::drag()).on_hover_cursor(egui::CursorIcon::Grab);
r.dnd_set_drag_payload(s.clone());
if r.dragged()
@@ -697,4 +805,24 @@ mod tests {
assert!(same_source(&ch(Channel::Normal, 2), &ch(Channel::Normal, 0)));
assert!(!same_source(&SourceRef::Constant(0.0), &SourceRef::Constant(1.0)));
}
#[test]
fn inversion_follows_its_source_through_layouts_and_drops() {
let mut map = new_map(Layout::Rgb);
map.inverted = vec![Dest::R];
set_layout(&mut map, Layout::Gray);
assert_eq!(map.inverted, vec![Dest::L], "the colour source keeps its inversion on L");
set_layout(&mut map, Layout::Rgb);
assert_eq!(map.inverted, vec![Dest::R, Dest::G, Dest::B], "and spreads it over R, G, B");
set_layout(&mut map, Layout::Rgba);
assert_eq!(map.inverted, vec![Dest::R, Dest::G, Dest::B], "alpha stays un-inverted");
map.inverted = vec![Dest::G];
set_layout(&mut map, Layout::GrayAlpha);
assert!(map.inverted.is_empty(), "channels that leave take their inversion with them");
let mut map = new_map(Layout::Rgb);
map.inverted = vec![Dest::B];
drop_input(&mut map, Dest::B, &ch(Channel::Metallic, 0));
assert_eq!(map.inverted, vec![Dest::B], "a dropped map keeps the channel's toggle, like picking from the list");
ExportPreset { name: "t".into(), maps: vec![map] }.validate().unwrap();
}
}
+1 -1
View File
@@ -337,7 +337,7 @@ fn input_slot(app: &mut TextureCraftApp, ui: &mut Ui, (layer, id): (LayerId, u64
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::Anchor { anchor, channel, .. }) => anchor_label(app, *anchor, *channel),
Some(Source::Procedural { .. }) => tr("Procedural").to_string(),
};
let group = ui.group(|ui| {
+58 -3
View File
@@ -282,6 +282,7 @@ impl GpuLink {
if self.aux.get(&texture_set) == Some(&key) {
continue;
}
let Some(cache) = session.caches.get(texture_set) else { continue };
let resolution = texturecraft_render::aux_size(cache.size);
@@ -300,9 +301,20 @@ impl GpuLink {
if self.aux.get(&texture_set) != Some(&key) && !session.stroke_active() {
let resolution =
session.caches.get(texture_set).map_or(MASK_VIEW_FALLBACK_RESOLUTION, |cache| texturecraft_render::aux_size(cache.size));
if let Some(rgba) = session.mask_view_rgba(id, resolution) {
out.aux.push((texture_set, resolution, rgba));
}
let rgba = session.mask_view_rgba(id, resolution).unwrap_or_else(|| MASK_VIEW_BLANK.repeat((resolution * resolution) as usize));
out.aux.push((texture_set, resolution, rgba));
self.aux.insert(texture_set, key);
}
}
// The other texture sets show nothing of this mask: a flat dark gray
let shown = session.doc.project.locate(id).map(|(texture_set, _, _)| texture_set);
for texture_set in (0..session.caches.len()).filter(|set| Some(*set) != shown) {
let Some(cache) = session.caches.get(texture_set) else { continue };
let resolution = texturecraft_render::aux_size(cache.size);
let key = ("maskblank".to_owned(), u64::from(resolution));
if self.aux.get(&texture_set) != Some(&key) {
out.aux.push((texture_set, resolution, MASK_VIEW_BLANK.repeat((resolution * resolution) as usize)));
self.aux.insert(texture_set, key);
}
}
@@ -315,6 +327,7 @@ impl GpuLink {
if self.aux.get(&texture_set) == Some(&key) {
continue;
}
let resolution = texturecraft_render::aux_size(cache.size);
if let Some(rgba) = session.quick_mask_rgba(texture_set, resolution) {
out.aux.push((texture_set, resolution, rgba));
@@ -350,6 +363,9 @@ fn record_recreated_uploads(recreated: &mut BTreeMap<usize, BTreeSet<DisplayKind
/// Mask view resolution for a texture set without a composite cache
const MASK_VIEW_FALLBACK_RESOLUTION: u32 = 1024;
/// RGBA of the texel the other texture sets show in the mask view
const MASK_VIEW_BLANK: [u8; 4] = [38, 38, 38, 255];
/// Paint callback for one view.
pub struct ViewCallback {
pub frame: Frame,
@@ -502,6 +518,45 @@ mod tests {
s
}
#[test]
fn the_mask_view_uploads_the_mask_for_its_set_and_a_blank_for_the_others() {
let mut gpu = link();
let mut s = texturecraft_engine::sample_session(128, 64).unwrap();
assert!(s.doc.project.texture_sets.len() >= 2, "needs another set to blank");
let layer = texturecraft_engine::core::LayerId(execute(&mut s, "layer.add.fill", &json!({})).unwrap()["layer"].as_u64().unwrap());
execute(&mut s, "mask.add.white", &json!({})).unwrap();
let owner = s.doc.project.locate(layer).unwrap().0;
let sets = s.doc.project.texture_sets.len();
let out = gpu.sync(&mut s, Some(AuxView::Mask(layer)), None, 0, 0.0);
assert_eq!(out.aux.len(), sets, "every set gets an aux texture");
for (set, _, rgba) in &out.aux {
let blank = rgba.chunks(4).all(|px| px == MASK_VIEW_BLANK);
assert_eq!(blank, *set != owner, "set {set}: only the other sets are blank");
}
drop(out);
let out = gpu.sync(&mut s, Some(AuxView::Mask(layer)), None, 0, 0.0);
assert!(out.aux.is_empty(), "nothing is sent again while the view stays");
drop(out);
execute(&mut s, "mask.toggle", &json!({"layer": layer.0, "enabled": false})).unwrap();
let out = gpu.sync(&mut s, Some(AuxView::Mask(layer)), None, 0, 0.0);
assert_eq!(out.aux.len(), 1, "disabling the displayed mask replaces its old upload");
let (set, resolution, rgba) = &out.aux[0];
assert_eq!(*set, owner);
assert_eq!(*rgba, MASK_VIEW_BLANK.repeat((resolution * resolution) as usize));
assert_eq!(gpu.aux.len(), sets, "only view keys remain in the link");
drop(out);
let out = gpu.sync(&mut s, Some(AuxView::Mask(layer)), None, 0, 0.0);
assert!(out.aux.is_empty(), "the disabled view needs no repeat upload");
drop(out);
execute(&mut s, "mask.toggle", &json!({"layer": layer.0, "enabled": true})).unwrap();
let out = gpu.sync(&mut s, Some(AuxView::Mask(layer)), None, 0, 0.0);
assert_eq!(out.aux.len(), 1, "re-enabling the mask uploads its values again");
assert!(out.aux[0].2.chunks(4).any(|pixel| pixel != MASK_VIEW_BLANK));
}
fn kinds(out: &SceneSync) -> BTreeSet<DisplayKind> {
out.tiles.iter().filter(|t| t.0 == 0).map(|t| t.1).collect()
}
+61
View File
@@ -101,6 +101,36 @@ pub fn trf(template: &str, args: &[(&str, &dyn Display)]) -> String {
craft_i18n::fmt(tr(template), &args)
}
/// An undo step's label in the current language. A label with a layer name, path number or
/// smart mask name in it ("Paint on Rust") is matched to its engine template, which is translated
/// and filled in again; any other label is translated as it is.
pub fn tr_history(label: &str) -> String {
tr_history_with(label, |text| tr(text).to_string())
}
/// [`tr_history`] with its own lookup `translate`
fn tr_history_with(label: &str, translate: impl Fn(&str) -> String) -> String {
match history_template(label) {
Some((template, name, value)) => craft_i18n::fmt(&translate(template), &[(name, value)]),
None => translate(label),
}
}
/// The engine template a history label was made from, its placeholder name and the value in it.
/// The template with the longest fixed start wins.
fn history_template(label: &str) -> Option<(&'static str, &'static str, &str)> {
texturecraft_engine::HISTORY_TEMPLATES
.iter()
.filter_map(|template| {
let (open, close) = (template.find('{')?, template.find('}')?);
let (prefix, suffix) = (&template[..open], &template[close + 1..]);
let value = label.strip_prefix(prefix)?.strip_suffix(suffix)?;
Some((prefix.len(), *template, &template[open + 1..close], value))
})
.max_by_key(|(prefix_length, ..)| *prefix_length)
.map(|(_, template, name, value)| (template, name, value))
}
/// The supported language for a locale such as "de-AT", "pt_BR.UTF-8" or "zh-Hant-TW" ("en" when
/// none matches). Chinese locales get Simplified Chinese; Portuguese ones get Brazilian Portuguese.
pub fn language_for_locale(locale: &str) -> &'static str {
@@ -174,6 +204,7 @@ mod tests {
keys.extend(BlendMode::all().map(|mode| mode.label()));
keys.extend(texturecraft_engine::formats::export::VirtualMap::ALL.iter().map(|map| map.label()));
keys.extend(texturecraft_engine::Tool::ALL.iter().map(|tool| tool.label()));
keys.extend(texturecraft_engine::HISTORY_TEMPLATES);
keys.extend(ProceduralKind::ALL.iter().map(|kind| kind.label()));
keys.extend(GeneratorKind::ALL.iter().map(|kind| kind.label()));
keys.extend(texturecraft_engine::paint::BrushAlpha::ALL.iter().map(|alpha| alpha.label()));
@@ -285,6 +316,36 @@ mod tests",
}
}
#[test]
fn history_labels_are_matched_to_their_templates() {
assert_eq!(history_template("Paint on Rust"), Some(("Paint on {layer}", "layer", "Rust")));
assert_eq!(history_template("Paint on Paint mask of x"), Some(("Paint on {layer}", "layer", "Paint mask of x")));
assert_eq!(history_template("Paint mask of Paint on x"), Some(("Paint mask of {layer}", "layer", "Paint on x")));
assert_eq!(history_template("Erase mask of Rust"), Some(("Erase mask of {layer}", "layer", "Rust")));
assert_eq!(history_template("Edit path 2"), Some(("Edit path {n}", "n", "2")));
assert_eq!(history_template("Apply smart mask Dirt"), Some(("Apply smart mask {name}", "name", "Dirt")));
assert_eq!(history_template("Rename layer"), None);
}
/// The template is translated and the layer name filled in; other labels are translated whole
#[test]
fn history_labels_with_a_layer_name_are_translated_through_their_template() {
let translate = |text: &str| {
match text {
"Paint on {layer}" => "Auf {layer} malen",
"Paint mask of {layer}" => "Maske von {layer} malen",
"Remove layer" => "Ebene entfernen",
other => other,
}
.to_string()
};
assert_eq!(tr_history_with("Paint on Rust", translate), "Auf Rust malen");
assert_eq!(tr_history_with("Paint mask of Paint on x", translate), "Maske von Paint on x malen");
assert_eq!(tr_history_with("Remove layer", translate), "Ebene entfernen");
assert_eq!(tr_history_with("Clone on Rust", translate), "Clone on Rust");
assert_eq!(tr_history_with("Paint on {layer}", translate), "Auf {layer} malen");
}
const UNTRANSLATED: &[&str] = &["RGB", "RGBA"];
#[test]
+29
View File
@@ -0,0 +1,29 @@
//! A brush stroke that starts on a texture set other than the active one paints nothing (only the active set takes paint): say why, once per stroke
use texturecraft_engine::geom::glam::Vec2;
use texturecraft_engine::{Session, Tool};
use crate::TextureCraftApp;
use crate::i18n::trf;
/// Tools that paint into the active texture set with the brush
fn paints_active_set(tool: Tool) -> bool {
matches!(tool, Tool::Paint | Tool::Eraser | Tool::Projection | Tool::Smudge | Tool::Clone)
}
/// The name of the texture set under viewport pixel `screen` when a brush stroke started there would paint nothing because that set is not the active one
pub fn inactive_set_under(session: &Session, screen: Vec2) -> Option<String> {
if !paints_active_set(session.tool.tool) {
return None;
}
let set = session.texture_set_at(screen, session.viewport).filter(|set| *set != session.ts())?;
session.doc.project.texture_sets.get(set).map(|texture_set| texture_set.name.clone())
}
/// Show the toast for a stroke that starts at viewport pixel `screen` (call once, when the stroke begins). Returns whether it did.
pub fn hint_on_stroke_start(app: &mut TextureCraftApp, screen: Vec2) -> bool {
let Some(name) = inactive_set_under(&app.session, screen) else { return false };
app.toast(trf("Texture set '{name}' is not active for painting. Select it in the Texture Sets list.", &[("name", &name)]), false);
true
}
+149 -21
View File
@@ -1,4 +1,4 @@
//! Keyboard shortcuts: every menu item and every command with a default shortcut, the user's
//! Keyboard shortcuts: every menu item and every command a key can run, the user's
//! overrides (`UiState::keymap`, id → "Ctrl+Shift+E" or "" for unbound), conflict detection and
//! the shortcut editor window (Edit ▸ Settings ▸ Keyboard, Help ▸ Shortcuts list).
@@ -26,7 +26,21 @@ pub struct Binding {
pub default: Option<&'static str>,
}
/// Every bindable item: the menu catalog, then commands with a default shortcut.
/// The menu a command without a menu entry is listed under, from its id.
fn group_of(id: &str) -> &'static str {
match id.split('.').next().unwrap_or("") {
"layer" | "mask" | "effect" | "material" | "textureSet" => "Layers",
"tool" | "brush" | "alpha" | "text" => "Tools",
"camera" | "viewport" => "Viewport",
"file" | "project" | "export" | "resource" => "File",
"edit" => "Edit",
"bake" => "Mode",
_ => "Commands",
}
}
/// Every bindable item: the menu catalog, then every command that has a default shortcut or that
/// a key can run (see [`texturecraft_engine::CommandSpec::bindable`]).
pub fn bindings() -> &'static [Binding] {
static ALL: std::sync::OnceLock<Vec<Binding>> = std::sync::OnceLock::new();
ALL.get_or_init(|| {
@@ -36,9 +50,9 @@ pub fn bindings() -> &'static [Binding] {
v.push(Binding { id: i.id, group: i.menu, label: i.label, default: i.shortcut });
}
}
for c in texturecraft_engine::command_specs().iter().filter(|c| c.shortcut.is_some()) {
for c in texturecraft_engine::command_specs().iter().filter(|c| c.shortcut.is_some() || c.bindable()) {
if !v.iter().any(|b| b.id == c.id) {
v.push(Binding { id: c.id, group: c.menu.first().copied().unwrap_or("Commands"), label: c.label, default: c.shortcut });
v.push(Binding { id: c.id, group: c.menu.first().copied().unwrap_or_else(|| group_of(c.id)), label: c.label, default: c.shortcut });
}
}
v
@@ -270,6 +284,7 @@ pub fn window(app: &mut TextureCraftApp, ctx: &egui::Context) {
if !app.ui.windows.shortcuts {
return;
}
let capture_id = Id::unique(CAPTURE);
let filter_id = Id::unique("keymap_filter");
let mut capture: Option<usize> = ctx.data(|d| d.get_temp(capture_id));
@@ -312,6 +327,7 @@ pub fn window(app: &mut TextureCraftApp, ctx: &egui::Context) {
{
continue;
}
ui.horizontal(|ui| {
ui.label(tr(b.label));
ui.label(RichText::new(tr(b.group)).size(10.5).color(tk.text_dim));
@@ -350,21 +366,7 @@ pub fn window(app: &mut TextureCraftApp, ctx: &egui::Context) {
});
ui.add_space(4.0);
section(ui, "keymap_nav", tr("Viewport and brush (fixed)"), false, |ui| {
egui::Grid::new("keymap_fixed").striped(true).show(ui, |ui| {
for (k, v) in [
(tr("Alt + LMB drag"), tr("Orbit")),
(tr("MMB drag / Alt + MMB"), tr("Pan")),
(tr("Wheel / Alt + RMB drag"), tr("Zoom")),
(tr("LMB"), tr("Paint with the current tool")),
("[ / ]", tr("Brush size down / up")),
(tr("Shift + wheel"), tr("Brush size")),
("Esc", tr("Cancel the stroke")),
] {
ui.label(RichText::new(k).strong());
ui.label(v);
ui.end_row();
}
});
fixed_gestures_grid(ui);
});
});
app.ui.windows.shortcuts = open;
@@ -384,6 +386,53 @@ pub fn window(app: &mut TextureCraftApp, ctx: &egui::Context) {
});
}
/// The fixed gestures as a two-column grid (the "Viewport and brush" section of the shortcut window)
pub fn fixed_gestures_grid(ui: &mut egui::Ui) {
egui::Grid::new("keymap_fixed").striped(true).show(ui, |ui| {
for (k, v) in fixed_gestures() {
ui.label(RichText::new(k).strong());
ui.label(v);
ui.end_row();
}
});
}
/// The mouse gestures and hold keys of the viewports, as (gesture, what it does) rows for the
/// shortcut window. The hold keys come from the constants the viewport reads, so a rebound hold key
/// is named from the same constant.
pub fn fixed_gestures() -> Vec<(String, String)> {
let stencil = crate::viewport::STENCIL_KEY.name();
let clone = crate::viewport::CLONE_SOURCE_KEY.name();
let keyed = |template: &str| trf(template, &[("key", &stencil)]);
vec![
(tr("Alt + LMB drag").into(), tr("Orbit").into()),
(tr("RMB drag").into(), tr("Orbit (3D view)").into()),
(tr("MMB drag / Alt + MMB").into(), tr("Pan").into()),
(tr("Wheel / Alt + RMB drag").into(), tr("Zoom").into()),
(tr("Shift + RMB drag").into(), tr("Turn the environment light (3D view)").into()),
(tr("LMB").into(), tr("Paint with the current tool").into()),
(tr("Shift + LMB").into(), tr("Paint a straight line from where the last stroke ended").into()),
(tr("Ctrl + Shift + LMB").into(), tr("Draw snapped straight lines").into()),
("[ / ]".into(), tr("Brush size down / up").into()),
(tr("Shift + wheel").into(), tr("Brush size").into()),
(tr("Ctrl + wheel").into(), tr("Brush size (wheel up smaller, down larger)").into()),
(tr("Ctrl + RMB drag").into(), tr("Brush size (left/right) and hardness (up/down)").into()),
(tr("Ctrl + LMB drag").into(), tr("Brush flow (left/right) and angle (up/down)").into()),
(tr("Ctrl + Shift + RMB drag").into(), tr("Brush size and hardness in fine steps").into()),
(keyed("{key} + LMB drag"), tr("Projection: rotate the stencil").into()),
(keyed("{key} + RMB drag"), tr("Projection: scale the stencil").into()),
(keyed("{key} + MMB drag"), tr("Projection: move the stencil").into()),
(trf("{key} + LMB", &[("key", &clone)]), tr("Clone: pick the point to copy from").into()),
(tr("Click (Path tool)").into(), tr("Path: add a point; on the curve it inserts one").into()),
(tr("LMB drag on a point (Path tool)").into(), tr("Path: move the point").into()),
(tr("Click the first point (Path tool)").into(), tr("Path: close it (needs 3 points)").into()),
("Enter".into(), tr("Path: apply it with the brush").into()),
("Backspace".into(), tr("Path: remove the selected or last point").into()),
("Esc".into(), tr("Cancel the stroke").into()),
(tr("Esc (Path tool)").into(), tr("Path: cancel it").into()),
]
}
#[cfg(test)]
mod tests {
use super::*;
@@ -400,6 +449,29 @@ mod tests {
assert!(!captured(Modifiers::NONE, Key::M) && !captured(Modifiers::NONE, Key::F), "plain keys need no capture");
}
#[test]
fn gesture_rows_name_the_hold_keys_and_cover_every_gesture() {
let rows = fixed_gestures();
let has = |gesture: &str, what: &str| rows.iter().any(|(g, w)| g == gesture && w.contains(what));
let (s, v) = (crate::viewport::STENCIL_KEY.name(), crate::viewport::CLONE_SOURCE_KEY.name());
assert!(has(&format!("{s} + LMB drag"), "rotate") && has(&format!("{s} + RMB drag"), "scale") && has(&format!("{s} + MMB drag"), "move"));
assert!(has(&format!("{v} + LMB"), "Clone"));
for (gesture, what) in [
("Shift + LMB", "straight line"),
("Shift + RMB drag", "environment light"),
("Enter", "apply"),
("Backspace", "remove"),
("Esc (Path tool)", "cancel"),
("Click the first point (Path tool)", "close"),
("LMB drag on a point (Path tool)", "move"),
("Click (Path tool)", "add a point"),
] {
assert!(has(gesture, what), "no row {gesture} / {what}");
}
let mut seen = std::collections::HashSet::new();
assert!(rows.iter().all(|(g, w)| seen.insert((g.clone(), w.clone()))), "duplicate row");
}
#[test]
fn shortcuts_round_trip_through_parse_and_format() {
for b in bindings() {
@@ -529,10 +601,12 @@ mod tests {
#[test]
fn a_stored_shortcut_replaces_the_default_and_an_empty_one_unbinds() {
let mut keymap = Keymap::new();
keymap.insert("file.save".into(), "F5".into());
// F7 is bound to nothing else, so the stored shortcut alone decides (F5 is Perspective)
keymap.insert("file.save".into(), "F7".into());
keymap.insert("edit.undo".into(), String::new());
let resolved = bindings_for(&keymap);
assert_eq!(resolved.command_of(&press(Key::F5, Modifiers::NONE)).as_deref(), Some("file.save"));
assert_eq!(resolved.command_of(&press(Key::F7, Modifiers::NONE)).as_deref(), Some("file.save"));
assert_eq!(resolved.command_of(&press(Key::S, Modifiers::COMMAND)), None);
assert_eq!(resolved.command_of(&press(Key::Z, Modifiers::COMMAND)), None);
}
@@ -546,6 +620,60 @@ mod tests {
assert_eq!(resolved.command_of(&press(Key::S, Modifiers::CTRL)), None, "the Control key is another key");
}
#[test]
fn commands_without_a_default_key_are_listed_unbound_and_filtered_by_their_parameters() {
for id in ["layer.add.fill", "layer.add.paint", "layer.add.group", "mask.invert", "layer.visible"] {
let b = binding(id);
assert!(b.default.is_none() && shortcut(&Keymap::new(), b).is_none(), "{id} is listed without a key");
}
assert_eq!(binding("mask.invert").group, "Layers");
for id in ["textureSet.select", "layer.rename", "tool.select", "layer.list", "project.inspect"] {
assert!(bindings().iter().all(|b| b.id != id), "{id} cannot run from a key");
}
let ids: Vec<_> = bindings().iter().map(|b| b.id).collect();
let unique: std::collections::BTreeSet<_> = ids.iter().collect();
assert_eq!(ids.len(), unique.len(), "every id is listed once");
}
#[test]
fn every_listed_item_is_implemented() {
for b in bindings() {
assert!(crate::menus::implemented(b.id), "{} is listed but nothing runs it", b.id);
}
}
#[test]
fn a_command_without_a_default_key_can_be_bound_unbound_and_conflicts() {
let (invert, save) = (binding("mask.invert"), binding("file.save"));
let mut keymap = Keymap::new();
rebind(&mut keymap, invert, "Ctrl+Alt+I");
assert_eq!(shortcut_of(&keymap, "mask.invert"), Some("Ctrl+Alt+I"));
let resolved = bindings_for(&keymap);
assert_eq!(resolved.command_of(&press(Key::I, Modifiers::COMMAND | Modifiers::ALT)).as_deref(), Some("mask.invert"));
assert!(resolved.conflict(invert).is_none());
// Taking the key of a default shortcut is a conflict, on both items
rebind(&mut keymap, invert, "Ctrl+S");
let resolved = bindings_for(&keymap);
assert_eq!(resolved.conflict(invert).map(|b| b.id), Some("file.save"));
assert_eq!(resolved.conflict(save).map(|b| b.id), Some("mask.invert"));
// Unbinding drops the override of an item that has no default
rebind(&mut keymap, invert, "");
assert_eq!(shortcut_of(&keymap, "mask.invert"), None);
assert!(bindings_for(&keymap).conflict(save).is_none());
}
#[test]
fn a_saved_keymap_from_before_every_command_was_bindable_still_loads() {
let old: Keymap = serde_json::from_str(r#"{"file.save":"F5","edit.undo":"","ui.layout.3d":"Ctrl+Shift+H"}"#).unwrap();
let resolved = bindings_for(&old);
assert_eq!(resolved.command_of(&press(Key::F5, Modifiers::NONE)).as_deref(), Some("file.save"));
assert_eq!(resolved.command_of(&press(Key::Z, Modifiers::COMMAND)), None);
assert_eq!(shortcut_of(&old, "ui.layout.3d"), Some("Ctrl+Shift+H"));
assert_eq!(shortcut_of(&old, "mask.invert"), None);
}
#[test]
fn the_first_item_listed_wins_a_shared_shortcut() {
let mut keymap = Keymap::new();
+10
View File
@@ -0,0 +1,10 @@
/// The layout dialog being shown (not saved)
#[derive(Clone, Debug, PartialEq)]
pub enum LayoutDialog {
/// Asking for the name to save the current layout under
Save(String),
/// A layout of this name exists: asking whether to replace it
Overwrite(String),
/// The list with rename and delete
Manage { renaming: Option<(String, String)>, deleting: Option<String> },
}
+81 -15
View File
@@ -7,6 +7,7 @@
#![forbid(unsafe_code)]
#![deny(clippy::unwrap_used, clippy::expect_used, clippy::panic, clippy::unimplemented, clippy::todo, clippy::unreachable)]
mod ask;
mod bake_job;
pub mod bake_mode;
mod bake_scene;
@@ -25,14 +26,24 @@ pub mod gpu;
mod grid_tile;
pub mod i18n;
pub mod id_color_pick;
mod inactive_set_hint;
pub mod keymap;
pub mod layer_panel;
mod layout_dialog;
mod levels_editor;
mod levels_handle;
mod levels_properties;
mod line_snap;
mod list_action;
mod mask_preview_image;
mod material_preview_image;
pub mod menus;
mod name_error;
mod named_layout;
pub mod named_layouts;
mod nav_button;
pub mod nav_buttons;
mod nav_view;
pub mod new_project_advanced;
mod orb_shape;
pub mod parity;
@@ -61,8 +72,11 @@ pub mod shelf_preview;
mod shelf_tabs;
mod shelf_toolbar;
pub mod shelf_view;
#[cfg(not(target_arch = "wasm32"))]
mod smart_mask_menu;
mod soft_box;
pub mod state;
mod surface_paint_point;
pub mod symmetry;
pub mod theme;
pub mod thumbs;
@@ -130,6 +144,8 @@ pub struct TextureCraftApp {
pub session: Session,
/// A smooth move to a saved camera in progress.
camera_glide: Option<CameraGlide>,
/// Yaw and pitch an Alt+Shift drag has reached before snapping to 90° steps (see `viewport`).
orbit_snap: Option<(f32, f32)>,
pub ui: UiState,
/// Where `ui` is saved between runs
ui_store: ui_state_store::UiStateStore,
@@ -157,8 +173,8 @@ pub struct TextureCraftApp {
pub ui_ms: f32,
/// Frame timing and the scripted paint test (`debug.*` control methods).
pub profiler: profile::Profiler,
/// Where the last 3D stroke ended (viewport pixels), for Shift+click straight lines.
pub last_paint_point: Option<texturecraft_engine::geom::glam::Vec2>,
/// Where the last 3D stroke ended on the model, scoped to its mesh and texture set, for Shift+click straight lines.
pub last_paint_point: Option<uv_paint_point::SurfacePaintPoint>,
/// The last finished 2D stroke's endpoint, scoped to its mesh and texture set for Shift+click lines
pub last_paint_uv: Option<uv_paint_point::UvPaintPoint>,
/// The decal layer the next click in the 3D view places.
@@ -167,6 +183,8 @@ pub struct TextureCraftApp {
pub properties_popup: Option<properties_popup::PropertiesPopup>,
/// The color selection the next click in the 3D or 2D view picks an ID color for
pub picking_id_color: Option<id_color_pick::IdColorPick>,
/// Whether the next click on the model places the symmetry planes (Pick point in the symmetry settings)
pub picking_symmetry_plane: bool,
/// The wgpu state (screenshots read the renderer's targets).
pub render_state: Option<eframe::egui_wgpu::RenderState>,
/// CJK fallback fonts for the UI language.
@@ -199,9 +217,24 @@ pub struct TextureCraftApp {
pub(crate) bindings: keymap::Bindings,
}
/// The UI state to start with: the saved one, whose tool settings go to `session`, else the defaults in the OS language
pub(crate) fn start_ui(saved: Option<UiState>, session: &mut Session) -> UiState {
match saved {
Some(ui) => {
ui.tool_settings.apply(&mut session.tool);
ui
}
None => {
let mut ui = UiState::default();
ui.prefs.language = i18n::os_language().into();
ui
}
}
}
impl TextureCraftApp {
/// The app around `session`, with the saved UI state (or defaults in the OS language) and the GPU viewport.
pub fn new(cc: &eframe::CreationContext<'_>, session: Session) -> TextureCraftApp {
pub fn new(cc: &eframe::CreationContext<'_>, mut session: Session) -> TextureCraftApp {
theme::install(&cc.egui_ctx);
// Bakes cast their rays on a GPU device of their own (created on the first bake)
@@ -211,11 +244,7 @@ impl TextureCraftApp {
// The first run speaks the OS (or browser) language
let mut ui_store = ui_state_store::UiStateStore::new(ui_state_store::FILE.get().cloned());
let mut ui = ui_store.load(cc.storage).unwrap_or_else(|| {
let mut ui = UiState::default();
ui.prefs.language = i18n::os_language().into();
ui
});
let mut ui = start_ui(ui_store.load(cc.storage), &mut session);
// No window opens by itself with no project (a saved layout may have left Export open)
if !session.project_open {
@@ -227,6 +256,7 @@ impl TextureCraftApp {
let mut app = TextureCraftApp {
camera_glide: None,
orbit_snap: None,
session,
ui,
ui_store,
@@ -251,6 +281,7 @@ impl TextureCraftApp {
placing_decal: None,
properties_popup: None,
picking_id_color: None,
picking_symmetry_plane: false,
render_state: cc.wgpu_render_state.clone(),
fonts: fonts::UiFonts::default(),
banner: None,
@@ -301,8 +332,10 @@ impl TextureCraftApp {
pub fn run(&mut self, id: &str, params: Value) -> Option<Value> {
self.ui.prefs.apply_resource_limits();
// Going to a saved camera glides there; the control channel and CLI jump straight away
let glide_from = (id.starts_with("camera.select") || id.starts_with("camera.bookmark")).then_some(self.session.camera);
// Going to a saved camera or a fixed view glides there; the control channel and CLI jump straight away
let glides = id.starts_with("camera.select") || id.starts_with("camera.bookmark") || id.starts_with("camera.view");
let before = self.session.camera;
let glide_from = glides.then_some(before);
match texturecraft_engine::execute(&mut self.session, id, &params) {
Ok(value) => {
if matches!(id, "brush.preset.store" | "brush.preset.rename" | "brush.preset.delete") {
@@ -322,9 +355,15 @@ impl TextureCraftApp {
self.ui.windows.export = false;
}
if let Some(from) = glide_from.filter(|camera| *camera != self.session.camera) {
self.camera_glide = Some(CameraGlide { from, to: self.session.camera, start: self.last_time });
self.session.camera = from;
match glide_from {
Some(from) if from != self.session.camera => {
self.camera_glide = Some(CameraGlide { from, to: self.session.camera, start: self.last_time });
self.session.camera = from;
}
// Already at the destination: drop a glide an earlier command in the same frame started
Some(_) => self.camera_glide = None,
None => self.settle_camera_glide(id, before),
}
Some(value)
@@ -336,6 +375,21 @@ impl TextureCraftApp {
}
}
/// After command `id` ran without starting a glide (the camera was `before`): a projection switch
/// carries over into a running glide, which would otherwise put back the projection it recorded;
/// any other command that moved the camera, or named where it should be, ends the glide, which
/// would put the camera back or carry it on to the glide's old destination.
pub(crate) fn settle_camera_glide(&mut self, id: &str, before: texturecraft_engine::geom::OrbitCamera) {
if matches!(id, "camera.perspective" | "camera.orthographic") {
if let Some(glide) = &mut self.camera_glide {
glide.from.ortho = self.session.camera.ortho;
glide.to.ortho = self.session.camera.ortho;
}
} else if self.session.camera != before || sets_camera(id) {
self.camera_glide = None;
}
}
fn report_ui_storage_warning(&mut self) {
if let Some(warning) = self.ui_store.take_warning() {
self.session.log.push(warning.clone());
@@ -630,14 +684,17 @@ impl TextureCraftApp {
#[cfg(not(target_arch = "wasm32"))]
fn autosave(&mut self, now: f64) {
let period = self.ui.prefs.autosave_minutes as f64 * 60.0;
// The clock starts at the first unsaved change.
// The clock starts at the first unsaved change
if period <= 0.0 || !self.session.modified {
self.next_autosave = now + period;
return;
}
if now < self.next_autosave {
return;
}
self.next_autosave = now + period;
let dir = user_dir("autosave");
let path = dir.join(format!(
@@ -661,6 +718,13 @@ impl TextureCraftApp {
}
}
/// Whether command `id` puts the camera at a place it names (a view, a saved camera, explicit values or
/// framing), so a glide toward an earlier destination must not go on even when the camera is already there
fn sets_camera(id: &str) -> bool {
matches!(id, "camera.set" | "camera.orbit" | "camera.select")
|| ["camera.view.", "camera.bookmark", "viewport.frame"].iter().any(|prefix| id.starts_with(prefix))
}
/// A smooth move of the viewport camera (see [`TextureCraftApp::run`]).
struct CameraGlide {
from: texturecraft_engine::geom::OrbitCamera,
@@ -684,7 +748,8 @@ impl TextureCraftApp {
c.pitch = mix(a.pitch, b.pitch);
c.distance = mix(a.distance, b.distance);
c.fov = mix(a.fov, b.fov);
// Orthographic switches at the end (the projections cannot be blended).
// Switch orthographic mode at the end because projections cannot blend
c.ortho = if t >= 1.0 { b.ortho } else { a.ortho };
self.session.camera = c;
self.session.revision = self.session.revision.wrapping_add(1);
@@ -702,6 +767,7 @@ impl eframe::App for TextureCraftApp {
}
fn save(&mut self, storage: &mut dyn eframe::Storage) {
self.ui.tool_settings = texturecraft_engine::ToolSettings::of(&self.session.tool);
self.ui_store.save(&self.ui, storage);
self.report_ui_storage_warning();
export_templates::save_library(self, storage);
+95
View File
@@ -0,0 +1,95 @@
//! Ctrl+Shift+click straight lines: the end point turns about the start to the nearest angle step
use egui::{Pos2, Vec2};
/// The angle step of a snapped line, in degrees
pub const LINE_SNAP_STEP_DEGREES: f32 = 15.0;
/// `end` turned about `start` to the nearest multiple of `step_degrees` (measured in the plane's
/// own axes); the distance from `start` stays what it was. A zero step or a zero-length line is
/// returned unchanged.
pub fn snap_line_end(start: Pos2, end: Pos2, step_degrees: f32) -> Pos2 {
let offset = end - start;
let length = offset.length();
if step_degrees <= 0.0 || length == 0.0 {
return end;
}
let step = step_degrees.to_radians();
let angle = (offset.y.atan2(offset.x) / step).round() * step;
start + Vec2::new(angle.cos(), angle.sin()) * length
}
#[cfg(test)]
mod tests {
use super::*;
use egui::pos2;
const START: Pos2 = pos2(100.0, 50.0);
/// The angle of `end` from `START` in degrees
fn angle(end: Pos2) -> f32 {
(end - START).angle().to_degrees()
}
fn assert_close(actual: Pos2, expected: Pos2) {
assert!((actual - expected).length() < 1e-3, "{actual:?} vs {expected:?}");
}
#[test]
fn a_line_near_0_degrees_becomes_horizontal() {
let end = snap_line_end(START, pos2(200.0, 55.0), 15.0);
assert_close(end, pos2(100.0 + (100.0f32 * 100.0 + 25.0).sqrt(), 50.0));
}
#[test]
fn a_line_near_15_degrees_turns_to_15_degrees() {
let end = snap_line_end(START, START + Vec2::angled(18.0f32.to_radians()) * 80.0, 15.0);
assert!((angle(end) - 15.0).abs() < 1e-3, "{}", angle(end));
}
#[test]
fn a_line_near_45_degrees_turns_to_45_degrees() {
let end = snap_line_end(START, START + Vec2::angled(40.0f32.to_radians()) * 60.0, 15.0);
assert!((angle(end) - 45.0).abs() < 1e-3, "{}", angle(end));
assert_close(end, START + Vec2::angled(45.0f32.to_radians()) * 60.0);
}
#[test]
fn a_line_near_90_degrees_becomes_vertical() {
let end = snap_line_end(START, pos2(104.0, 150.0), 15.0);
assert!((end.x - START.x).abs() < 1e-3, "{end:?}");
assert!(end.y > START.y);
}
#[test]
fn negative_angles_snap_to_negative_multiples() {
let end = snap_line_end(START, START + Vec2::angled((-37.0f32).to_radians()) * 70.0, 15.0);
assert!((angle(end) + 30.0).abs() < 1e-3, "{}", angle(end));
let backwards = snap_line_end(START, START + Vec2::angled((-172.0f32).to_radians()) * 70.0, 15.0);
assert!((angle(backwards).abs() - 165.0).abs() < 1e-3, "{}", angle(backwards));
}
#[test]
fn the_distance_from_the_start_is_kept() {
for degrees in [-170.0f32, -100.0, -33.0, -7.0, 3.0, 22.0, 58.0, 91.0, 133.0, 179.0] {
let end = START + Vec2::angled(degrees.to_radians()) * 123.0;
let snapped = snap_line_end(START, end, 15.0);
assert!(((snapped - START).length() - 123.0).abs() < 1e-3, "{degrees}");
let multiple = angle(snapped) / 15.0;
assert!((multiple - multiple.round()).abs() < 1e-3, "{degrees}: {}", angle(snapped));
}
}
#[test]
fn a_line_already_on_a_step_stays() {
let end = START + Vec2::angled(60.0f32.to_radians()) * 40.0;
assert_close(snap_line_end(START, end, 15.0), end);
}
#[test]
fn a_zero_length_line_or_zero_step_is_unchanged() {
assert_eq!(snap_line_end(START, START, 15.0), START);
assert_eq!(snap_line_end(START, pos2(130.0, 77.0), 0.0), pos2(130.0, 77.0));
}
}
+16
View File
@@ -0,0 +1,16 @@
use texturecraft_engine::formats::ExportPreset;
/// A template list action
#[derive(Clone, Debug, PartialEq)]
pub enum ListAction {
Select(String),
New,
Duplicate,
StartRename(String),
Rename(String),
Remove,
Import,
/// A template read from a file, added and selected
Imported(ExportPreset),
Export,
}
+48 -2
View File
@@ -80,8 +80,11 @@ pub const CATALOG: &[Item] = &[
sep("Window"),
sub("Window", "Save UI Layout", "Save current layout...", "ui.layout.save", None),
it("Window", "Load UI Layout", "ui.layout.load", None),
sub("Window", "Layouts", "Save current layout as...", "ui.layout.saveAs", None),
sub("Window", "Layouts", "Manage layouts...", "ui.layout.manage", None),
sep("Window"),
it("Window", "Hide UI", "ui.hideUi", Some("Tab")),
it("Window", "Reset panel layout", "ui.resetPanelLayout", None),
it("Window", "Reset UI", "ui.resetUi", None),
it("Viewport", "Display material", "viewport.displayMaterial", Some("M")),
it("Viewport", "Display next channel", "viewport.nextChannel", Some("C")),
@@ -90,12 +93,24 @@ pub const CATALOG: &[Item] = &[
it("Viewport", "Display previous mesh map", "viewport.previousMeshMap", Some("Shift+B")),
it("Viewport", "UV checker", "ui.uvChecker", None),
sep("Viewport"),
it("Viewport", "Frame texture set", "viewport.frameSelection", Some("Shift+F")),
it("Viewport", "Show entire mesh", "viewport.frame", Some("F")),
it("Viewport", "Front view", "camera.view.front", None),
it("Viewport", "Back view", "camera.view.back", None),
it("Viewport", "Left view", "camera.view.left", None),
it("Viewport", "Right view", "camera.view.right", None),
it("Viewport", "Top view", "camera.view.top", None),
it("Viewport", "Bottom view", "camera.view.bottom", None),
sep("Viewport"),
it("Viewport", "Perspective", "camera.perspective", Some("F5")),
it("Viewport", "Orthographic", "camera.orthographic", Some("F6")),
sep("Viewport"),
it("Viewport", "3D/2D views", "ui.layout.split", Some("F1")),
it("Viewport", "3D view only", "ui.layout.3d", Some("F2")),
it("Viewport", "2D view only", "ui.layout.2d", Some("F3")),
sep("Viewport"),
it("Viewport", "Navigation buttons", "ui.navButtons", None),
sep("Viewport"),
it("Viewport", "Enable quick mask", "viewport.quickMask", Some("Y")),
it("Viewport", "Edit quick mask", "viewport.quickMask.edit", Some("U")),
it("Viewport", "Invert quick mask", "viewport.quickMask.invert", Some("Ctrl+Shift+I")),
@@ -132,6 +147,10 @@ pub fn enabled(app: &TextureCraftApp, id: &str) -> bool {
return false;
}
if id == "ui.layout.manage" {
return !app.ui.named_layouts.is_empty();
}
if is_ui(id) {
return app.session.project_open || !ui_needs_project(id);
}
@@ -186,9 +205,13 @@ pub fn invoke(app: &mut TextureCraftApp, ctx: &egui::Context, id: &str) {
"ui.mode.paint" => app.ui.mode = Mode::Painting,
"ui.mode.render" => app.ui.mode = Mode::Rendering,
"ui.hideUi" => app.ui.hide_ui = !app.ui.hide_ui,
"ui.resetUi" => app.ui.adopt_layout(crate::UiState::default()),
"ui.navButtons" => app.ui.nav_buttons = !app.ui.nav_buttons,
"ui.resetPanelLayout" => app.ui.reset_panel_layout(),
"ui.resetUi" => app.ui.windows.confirm_reset_ui = true,
"ui.layout.save" => crate::windows::layout_file(app, true),
"ui.layout.load" => crate::windows::layout_file(app, false),
"ui.layout.saveAs" => app.ui.layout_dialog = Some(crate::named_layouts::LayoutDialog::Save(String::new())),
"ui.layout.manage" => app.ui.layout_dialog = Some(crate::named_layouts::LayoutDialog::Manage { renaming: None, deleting: None }),
"ui.uvChecker" => {
app.run("viewport.view", json!({"mode": "uvChecker"}));
}
@@ -228,18 +251,24 @@ pub fn menu_bar(app: &mut TextureCraftApp, ui: &mut egui::Ui) {
if current_sub == Some(s) {
continue;
}
current_sub = Some(s);
ui.menu_button(tr(s), |ui| {
for x in items.iter().filter(|x| x.sub == Some(s)) {
menu_item(app, &ctx, ui, x);
}
if s == "Layouts" {
crate::named_layouts::entries(app, ui);
}
});
continue;
}
if item.label == "-" {
ui.separator();
continue;
}
menu_item(app, &ctx, ui, item);
}
});
@@ -265,6 +294,9 @@ fn menu_item(app: &mut TextureCraftApp, ctx: &egui::Context, ui: &mut egui::Ui,
"ui.mode.paint" => Some(app.ui.mode == Mode::Painting),
"ui.mode.bake" => Some(app.ui.mode == Mode::Baking),
"ui.mode.render" => Some(app.ui.mode == Mode::Rendering),
"ui.navButtons" => Some(app.ui.nav_buttons),
"camera.perspective" => Some(!app.session.camera.ortho),
"camera.orthographic" => Some(app.session.camera.ortho),
id => crate::docking::view_panel(id).map(|p| app.ui.dock.is_open(p)),
};
if let Some(c) = checked {
@@ -369,11 +401,18 @@ pub fn shortcuts(app: &mut TextureCraftApp, ctx: &egui::Context) {
// Escape closes a dropdown before Properties, the rail popup, color picking or the stroke
let popup_open = egui::Popup::is_any_open(ctx);
let no_widget_focused = ctx.memory(|memory| memory.focused().is_none());
#[cfg(not(target_arch = "wasm32"))]
let nothing_focused = ctx.memory(|memory| memory.focused().is_none());
let commands_to_invoke = ctx.input_mut(|input| {
// egui's label selection copies on these events at the end of the frame
let copies: Vec<_> = input.events.iter().filter(|event| matches!(event, egui::Event::Copy | egui::Event::Cut)).cloned().collect();
// Escape and Enter answer the Reset UI question first, even when a shortcut binds them
let confirming_reset = app.ui.windows.confirm_reset_ui;
if confirming_reset && !popup_open {
crate::windows::reset_ui_keys(app, input, no_widget_focused);
}
let commands = app.bindings.dispatch(input);
for copy in copies {
if !input.events.contains(&copy) {
@@ -390,7 +429,12 @@ pub fn shortcuts(app: &mut TextureCraftApp, ctx: &egui::Context) {
app.session.tool.brush.size = (app.session.tool.brush.size * scale).clamp(MIN_BRUSH_SIZE, MAX_BRUSH_SIZE);
}
if app.ui.windows.project_config.is_some() {
if confirming_reset {
// Its keys were handled before the shortcuts ran
} else if app.ui.export.ask.is_some() && input.consume_key(Modifiers::NONE, Key::Escape) {
// The Output templates question: Escape answers it with the safe choice
app.ui.export.ask = None;
} else if app.ui.windows.project_config.is_some() {
// Its keys are Escape (close) and Enter (OK); a stroke in progress isn't touched
#[cfg(not(target_arch = "wasm32"))]
crate::project_config::keys_in(app, input, nothing_focused, popup_open);
@@ -400,6 +444,8 @@ pub fn shortcuts(app: &mut TextureCraftApp, ctx: &egui::Context) {
app.ui.rail_panel = None;
} else if !popup_open && app.picking_id_color.is_some() && input.consume_key(Modifiers::NONE, Key::Escape) {
crate::id_color_pick::IdColorPick::end(app);
} else if app.picking_symmetry_plane && input.consume_key(Modifiers::NONE, Key::Escape) {
app.picking_symmetry_plane = false;
} else if app.ui.mode == Mode::Painting && !popup_open && input.consume_key(Modifiers::NONE, Key::Escape) {
app.session.cancel_stroke();
app.session.cancel_path();
+6
View File
@@ -0,0 +1,6 @@
/// Why a name cannot be used
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum NameError {
Empty,
Taken,
}
Loaded 100 of 167 files, more files were not shown because too many files have changed in this diff. Show more