mirror of
https://github.com/storytold/texturecraft.git
synced 2026-11-25 00:40:47 +01:00
Merge main and resolve translation conflicts
This commit is contained in:
commit
74c68e005a
115 files changed
+5647
-1035
No files matched your search
@@ -25,6 +25,8 @@ jobs:
|
||||
craft-fonts-ref: aced4137c022f1f587624d48e81ec77e1914a9cc
|
||||
os: '["ubuntu-24.04","windows-latest"]'
|
||||
toolchain: "1.96.0"
|
||||
# xtask ci runs cargo test (including doctests), not cargo nextest.
|
||||
tools: ""
|
||||
packages: >-
|
||||
libxkbcommon-dev libwayland-dev libx11-dev libxrandr-dev libxi-dev libgl1-mesa-dev
|
||||
libgtk-3-dev
|
||||
@@ -0,0 +1,50 @@
|
||||
/// Deviations of ±0.5 (curvature − 0.5) stored as 16-bit integers.
|
||||
pub const DEVIATION_SCALE: f32 = i16::MAX as f32 * 2.0;
|
||||
|
||||
/// Curvature blurred at one detail size: deviations from flat, stored `step` times coarser than the map.
|
||||
pub struct CurvatureSizeLevel {
|
||||
pub step: u32,
|
||||
pub width: u32,
|
||||
pub height: u32,
|
||||
/// UV tile dimensions in stored texels; interpolation must stay inside one tile
|
||||
pub block: (u32, u32),
|
||||
pub deviation: Vec<i16>,
|
||||
}
|
||||
|
||||
impl CurvatureSizeLevel {
|
||||
/// The deviation at map texel `(x, y)`, interpolated within its UV tile
|
||||
pub fn sample(&self, x: u32, y: u32) -> f32 {
|
||||
if self.width == 0 || self.height == 0 {
|
||||
return 0.0;
|
||||
}
|
||||
|
||||
let step = self.step.max(1);
|
||||
let axis = |texel: u32, block: u32, length: u32| {
|
||||
let block = block.max(1);
|
||||
let first = if block >= length { 0 } else { (texel / block.saturating_mul(step) * block).min(length - 1) };
|
||||
let last = first.saturating_add(block - 1).min(length - 1);
|
||||
let position = ((texel as f32 + 0.5) / step as f32 - 0.5).clamp(first as f32, last as f32);
|
||||
let lower = position.floor() as u32;
|
||||
(lower, (lower + 1).min(last), position - lower as f32)
|
||||
};
|
||||
let (x0, x1, blend_x) = axis(x, self.block.0, self.width);
|
||||
let (y0, y1, blend_y) = axis(y, self.block.1, self.height);
|
||||
let stored = |x: u32, y: u32| self.deviation.get((y * self.width + x) as usize).map_or(0.0, |value| f32::from(*value) / DEVIATION_SCALE);
|
||||
let top = stored(x0, y0) + (stored(x1, y0) - stored(x0, y0)) * blend_x;
|
||||
let bottom = stored(x0, y1) + (stored(x1, y1) - stored(x0, y1)) * blend_x;
|
||||
top + (bottom - top) * blend_y
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn samples_blend_the_stored_texels() {
|
||||
let level = CurvatureSizeLevel { step: 2, width: 2, height: 1, block: (2, 1), deviation: vec![0, (0.25 * DEVIATION_SCALE) as i16] };
|
||||
assert!(level.sample(0, 0).abs() < 1e-4, "the first stored texel covers map texels 0 and 1");
|
||||
assert!((level.sample(3, 0) - 0.25).abs() < 1e-3);
|
||||
assert!(level.sample(2, 0) > 0.0 && level.sample(2, 0) < 0.25, "between stored texels the value blends");
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,447 @@
|
||||
//! The baked curvature map at the detail sizes of curvature generators, built once per map and layout.
|
||||
|
||||
use std::sync::atomic::{AtomicBool, Ordering};
|
||||
use std::sync::{Arc, Mutex, Weak};
|
||||
|
||||
use rayon::prelude::*;
|
||||
use texturecraft_core::{BakedMap, BlockScales, CurvatureDetail};
|
||||
use texturecraft_texel::dilate::{DilationMap, NONE};
|
||||
|
||||
use crate::curvature_size_level::{CurvatureSizeLevel, DEVIATION_SCALE};
|
||||
use crate::eval::{BLUR_BOX_PASSES, Inputs, blur};
|
||||
|
||||
/// The curvature map padded past its UV islands and blurred at each size of [`CurvatureDetail::SIZES`] after the first.
|
||||
pub struct CurvatureSizes {
|
||||
/// One per blurred size, built once a generator gives that size a weight above 0.
|
||||
pub levels: Vec<Option<Arc<CurvatureSizeLevel>>>,
|
||||
}
|
||||
|
||||
/// The bake map size, its UV tile block and the working texture size a cache entry was built for.
|
||||
type CacheKey = ((u32, u32), (u32, u32), (u32, u32));
|
||||
|
||||
/// Built sizes by the curvature data they come from, their layout and the tiles' scales.
|
||||
type CacheEntry = (Weak<Vec<f32>>, CacheKey, BlockScales, Arc<CurvatureSizes>);
|
||||
|
||||
static CACHE: Mutex<Vec<CacheEntry>> = Mutex::new(Vec::new());
|
||||
|
||||
// Undo snapshots keep old maps alive; their derived levels must not grow with the history
|
||||
const CACHE_BYTES: usize = 256 << 20;
|
||||
const CACHE_MAPS: usize = 16;
|
||||
|
||||
impl CurvatureSizes {
|
||||
/// The sizes of the texture set `inp` composites, holding at least those `needed` marks (one flag per blurred size); None without a baked curvature map or a needed size.
|
||||
pub fn of(inp: &Inputs, needed: &[bool]) -> Option<Arc<CurvatureSizes>> {
|
||||
let curvature = inp.baked.maps.get(&BakedMap::Curvature)?;
|
||||
let (width, height) = (inp.baked.resolution, inp.baked.height(BakedMap::Curvature));
|
||||
if !needed.contains(&true) || width == 0 || height == 0 {
|
||||
return None;
|
||||
}
|
||||
|
||||
let grid = inp.project.texture_set(inp.ts).ok().and_then(|set| set.tile_grid());
|
||||
let block = grid.map_or((width, height), |grid| (width / grid.cols.max(1), height / grid.rows.max(1)));
|
||||
let key = ((width, height), block, (inp.gbuf.width, inp.gbuf.height));
|
||||
let built = cached(curvature, key, &inp.block_scales);
|
||||
if let Some(sizes) = built.as_ref().filter(|sizes| sizes.holds(needed)) {
|
||||
return Some(sizes.clone());
|
||||
}
|
||||
|
||||
// Built without the cache locked: the build runs parallel work, and a thread waiting on it may composite a tile that asks the cache again
|
||||
let covered = covered_texels(inp, (width, height));
|
||||
let sizes = CurvatureSizes::build(curvature, (width, height), &covered, block, needed, built.as_deref());
|
||||
Some(store(curvature, key, &inp.block_scales, sizes))
|
||||
}
|
||||
|
||||
/// Whether every size `needed` marks is built.
|
||||
fn holds(&self, needed: &[bool]) -> bool {
|
||||
needed.iter().zip(&self.levels).all(|(needs, level)| !needs || level.is_some())
|
||||
}
|
||||
|
||||
/// Pad and blur each UV tile at the requested sizes, reusing levels already in `built`
|
||||
fn build(
|
||||
curvature: &[f32],
|
||||
(width, height): (u32, u32),
|
||||
covered: &[bool],
|
||||
block: (u32, u32),
|
||||
needed: &[bool],
|
||||
built: Option<&CurvatureSizes>,
|
||||
) -> CurvatureSizes {
|
||||
let padding = DilationMap::in_rectangular_blocks(covered, width, height, None, block);
|
||||
let deviation: Vec<f32> =
|
||||
padding.src.par_iter().map(|&source| if source == NONE { 0.0 } else { curvature.get(source as usize).copied().unwrap_or(0.5) - 0.5 }).collect();
|
||||
let (block_width, block_height) = (block.0.max(1).min(width), block.1.max(1).min(height));
|
||||
|
||||
let levels = CurvatureDetail::SIZES
|
||||
.iter()
|
||||
.skip(1)
|
||||
.enumerate()
|
||||
.map(|(level, size)| {
|
||||
if let Some(existing) = built.and_then(|sizes| sizes.levels.get(level)).and_then(Option::clone) {
|
||||
return Some(existing);
|
||||
}
|
||||
if !needed.get(level).copied().unwrap_or(false) {
|
||||
return None;
|
||||
}
|
||||
|
||||
// Sizes are texels at 2K; a blur this wide holds nothing finer than half its radius, so it is stored that much coarser
|
||||
let radius = (size * block_width as f32 / 2048.0).round().max(1.0) as u32;
|
||||
let mut step = (radius / 2).max(1).next_power_of_two();
|
||||
// A coarse cell must not average curvature from different UV tiles
|
||||
while !block_width.is_multiple_of(step) || !block_height.is_multiple_of(step) {
|
||||
step /= 2;
|
||||
}
|
||||
|
||||
let mut blurred = deviation.clone();
|
||||
for block_y in (0..height).step_by(block_height as usize) {
|
||||
for block_x in (0..width).step_by(block_width as usize) {
|
||||
let region = (block_x, block_y, block_width.min(width - block_x), block_height.min(height - block_y));
|
||||
blur_block(&mut blurred, width, region, radius);
|
||||
}
|
||||
}
|
||||
Some(Arc::new(coarsen(&blurred, (width, height), step, (block_width, block_height))))
|
||||
})
|
||||
.collect();
|
||||
CurvatureSizes { levels }
|
||||
}
|
||||
}
|
||||
|
||||
/// The cached sizes of `curvature` for layout `key` and tile `scales`, if any
|
||||
fn cached(curvature: &Arc<Vec<f32>>, key: CacheKey, scales: &BlockScales) -> Option<Arc<CurvatureSizes>> {
|
||||
let mut cache = CACHE.lock().unwrap_or_else(|poisoned| poisoned.into_inner());
|
||||
cache.retain(|(source, ..)| source.strong_count() > 0);
|
||||
let index = cache.iter().position(|entry| is_entry_for(entry, curvature, key, scales))?;
|
||||
let entry = cache.remove(index);
|
||||
let sizes = entry.3.clone();
|
||||
cache.push(entry);
|
||||
Some(sizes)
|
||||
}
|
||||
|
||||
/// Cache `sizes`, merging any levels another thread stored meanwhile
|
||||
fn store(curvature: &Arc<Vec<f32>>, key: CacheKey, scales: &BlockScales, sizes: CurvatureSizes) -> Arc<CurvatureSizes> {
|
||||
let mut cache = CACHE.lock().unwrap_or_else(|poisoned| poisoned.into_inner());
|
||||
let sizes = if let Some((.., cached_sizes)) = cache.iter().find(|entry| is_entry_for(entry, curvature, key, scales)) {
|
||||
let levels = cached_sizes.levels.iter().zip(sizes.levels).map(|(cached, built)| cached.clone().or(built)).collect();
|
||||
CurvatureSizes { levels }
|
||||
} else {
|
||||
sizes
|
||||
};
|
||||
|
||||
// One layout per curvature map, with the most recently used map at the end
|
||||
cache.retain(|(source, ..)| source.strong_count() > 0 && !std::ptr::eq(source.as_ptr(), Arc::as_ptr(curvature)));
|
||||
let sizes = Arc::new(sizes);
|
||||
cache.push((Arc::downgrade(curvature), key, scales.clone(), sizes.clone()));
|
||||
trim_cache(&mut cache, CACHE_BYTES);
|
||||
sizes
|
||||
}
|
||||
|
||||
/// Evict the least recently used maps, retaining the newest even if it alone exceeds the budget
|
||||
fn trim_cache(cache: &mut Vec<CacheEntry>, budget: usize) {
|
||||
// Keeping the newest prevents a large atlas from rebuilding its levels for every tile
|
||||
let mut bytes = 0usize;
|
||||
let mut keep = 0;
|
||||
for (.., sizes) in cache.iter().rev() {
|
||||
let size = sizes.levels.iter().flatten().map(|level| level.deviation.len().saturating_mul(size_of::<i16>())).fold(0usize, usize::saturating_add);
|
||||
bytes = bytes.saturating_add(size);
|
||||
if keep > 0 && (bytes > budget || keep == CACHE_MAPS) {
|
||||
break;
|
||||
}
|
||||
keep += 1;
|
||||
}
|
||||
cache.drain(..cache.len() - keep);
|
||||
}
|
||||
|
||||
/// Whether cache `entry` holds the sizes of `curvature` for layout `key` and tile `scales`.
|
||||
fn is_entry_for((source, cached_key, cached_scales, _): &CacheEntry, curvature: &Arc<Vec<f32>>, key: CacheKey, scales: &BlockScales) -> bool {
|
||||
source.upgrade().is_some_and(|data| Arc::ptr_eq(&data, curvature)) && *cached_key == key && cached_scales == scales
|
||||
}
|
||||
|
||||
/// The bake atlas texels (`width × height`) overlapped by covered working texels of `inp`
|
||||
fn covered_texels(inp: &Inputs, (width, height): (u32, u32)) -> Vec<bool> {
|
||||
let working_size = (inp.gbuf.width, inp.gbuf.height);
|
||||
if working_size == (width, height) && inp.block_scales == BlockScales::default() {
|
||||
return (0..width * height).into_par_iter().map(|texel| inp.gbuf.covered(texel as usize)).collect();
|
||||
}
|
||||
|
||||
let covered: Vec<AtomicBool> = (0..width * height).map(|_| AtomicBool::new(false)).collect();
|
||||
(0..working_size.0 * working_size.1).into_par_iter().filter(|texel| inp.gbuf.covered(*texel as usize)).for_each(|texel| {
|
||||
let (x, y) = (texel % working_size.0, texel / working_size.0);
|
||||
let uv = [(x as f32 + 0.5) / working_size.0 as f32, (y as f32 + 0.5) / working_size.1 as f32];
|
||||
if let Some(baked_uv) = inp.block_scales.bake_uv(uv, working_size) {
|
||||
// A lower-resolution working texel covers a whole rectangle in the bake, not just its center
|
||||
let scale = inp.block_scales.at(x, y);
|
||||
let footprint = |center: f32, baked: u32, working: u32| {
|
||||
let half_width = 0.5 * baked as f32 / (working as f32 * scale);
|
||||
let center = center * baked as f32;
|
||||
((center - half_width).floor().max(0.0) as u32)..((center + half_width).ceil() as u32).min(baked)
|
||||
};
|
||||
let columns = footprint(baked_uv[0], width, working_size.0);
|
||||
for baked_y in footprint(baked_uv[1], height, working_size.1) {
|
||||
for baked_x in columns.clone() {
|
||||
if let Some(slot) = covered.get((baked_y * width + baked_x) as usize) {
|
||||
slot.store(true, Ordering::Relaxed);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
});
|
||||
covered.into_iter().map(AtomicBool::into_inner).collect()
|
||||
}
|
||||
|
||||
/// Blur the `(left, top, region_width, region_height)` block of `data` (`width` texels per row) in place, reading nothing outside it.
|
||||
fn blur_block(data: &mut [f32], width: u32, (left, top, region_width, region_height): (u32, u32, u32, u32), radius: u32) {
|
||||
let rows = top..top + region_height;
|
||||
let mut block: Vec<f32> =
|
||||
rows.flat_map(|y| (left..left + region_width).map(move |x| (y * width + x) as usize)).map(|index| data.get(index).copied().unwrap_or(0.0)).collect();
|
||||
blur(&mut block, region_width as usize, region_height as usize, radius as usize);
|
||||
|
||||
// The blur reads zero past the block's edges; dividing by the share of its window inside the block keeps the edges at full strength
|
||||
let column_weights = window_inside(region_width as usize, radius as usize);
|
||||
let row_weights = window_inside(region_height as usize, radius as usize);
|
||||
for (values, row_weight) in block.chunks_mut(region_width as usize).zip(&row_weights) {
|
||||
for (value, column_weight) in values.iter_mut().zip(&column_weights) {
|
||||
*value /= row_weight * column_weight;
|
||||
}
|
||||
}
|
||||
|
||||
for (row, values) in block.chunks(region_width as usize).enumerate() {
|
||||
let start = ((top + row as u32) * width + left) as usize;
|
||||
if let Some(target) = data.get_mut(start..start + values.len()) {
|
||||
target.copy_from_slice(values);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// The share of the [`blur`] window at each texel of a line `length` long that falls inside it: 1 from three radii in.
|
||||
fn window_inside(length: usize, radius: usize) -> Vec<f32> {
|
||||
let window = (2 * radius + 1) as f64;
|
||||
let mut weights = vec![1.0f64; length];
|
||||
for _ in 0..BLUR_BOX_PASSES {
|
||||
let running_totals: Vec<f64> = std::iter::once(0.0)
|
||||
.chain(weights.iter().scan(0.0, |total, weight| {
|
||||
*total += weight;
|
||||
Some(*total)
|
||||
}))
|
||||
.collect();
|
||||
let total_at = |end: usize| running_totals.get(end.min(length)).copied().unwrap_or(0.0);
|
||||
weights = (0..length).map(|texel| (total_at(texel + radius + 1) - total_at(texel.saturating_sub(radius))) / window).collect();
|
||||
}
|
||||
weights.into_iter().map(|weight| weight as f32).collect()
|
||||
}
|
||||
|
||||
/// `data` averaged over `step × step` squares, clipping the last cells to the map
|
||||
fn coarsen(data: &[f32], (width, height): (u32, u32), step: u32, block: (u32, u32)) -> CurvatureSizeLevel {
|
||||
let (coarse_width, coarse_height) = (width.div_ceil(step), height.div_ceil(step));
|
||||
let deviation = (0..coarse_width * coarse_height)
|
||||
.into_par_iter()
|
||||
.map(|cell| {
|
||||
let (cell_x, cell_y) = (cell % coarse_width, cell / coarse_width);
|
||||
let columns = cell_x * step..((cell_x + 1) * step).min(width);
|
||||
let rows = cell_y * step..((cell_y + 1) * step).min(height);
|
||||
let count = (columns.len() * rows.len()).max(1) as f32;
|
||||
let texels = rows.flat_map(|y| columns.clone().map(move |x| (y * width + x) as usize));
|
||||
let mean = texels.map(|index| data.get(index).copied().unwrap_or(0.0)).sum::<f32>() / count;
|
||||
(mean * DEVIATION_SCALE).round().clamp(i16::MIN as f32, i16::MAX as f32) as i16
|
||||
})
|
||||
.collect();
|
||||
CurvatureSizeLevel { step, width: coarse_width, height: coarse_height, block: (block.0.div_ceil(step), block.1.div_ceil(step)), deviation }
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn coarse_sizes_do_not_blend_between_uv_tiles() {
|
||||
let (width, height) = (512, 512);
|
||||
let block = (256, 256);
|
||||
let curvature: Vec<f32> = (0..width * height).map(|texel| if (texel % width) / block.0 == (texel / width) / block.1 { 0.8 } else { 0.2 }).collect();
|
||||
let covered = vec![true; curvature.len()];
|
||||
let sizes = CurvatureSizes::build(&curvature, (width, height), &covered, block, &[true; CurvatureDetail::BLURRED_SIZES], None);
|
||||
|
||||
for level in sizes.levels.iter().flatten() {
|
||||
for (x, y) in [(255, 128), (256, 128), (128, 255), (128, 256), (255, 255), (256, 256)] {
|
||||
let expected = curvature[(y * width + x) as usize] - 0.5;
|
||||
assert!((level.sample(x, y) - expected).abs() < 0.001, "step {} at ({x}, {y}): {} instead of {expected}", level.step, level.sample(x, y));
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn coverage_preserves_bake_texels_above_the_working_resolution() {
|
||||
use texturecraft_core::{Project, TextureSet};
|
||||
use texturecraft_geom::{UvGBuffer, primitives};
|
||||
|
||||
let mesh = primitives::plane(2.0, 1);
|
||||
let mut project = Project::new("Coverage", "builtin:plane");
|
||||
project.texture_sets.push(TextureSet::new("Plane", 0, 64));
|
||||
let gbuf = UvGBuffer::new(&mesh, 0, 64, 64);
|
||||
let pixels = Default::default();
|
||||
let images = Default::default();
|
||||
let baked = Default::default();
|
||||
let inputs = Inputs {
|
||||
project: &project,
|
||||
ts: 0,
|
||||
mesh: &mesh,
|
||||
gbuf: &gbuf,
|
||||
pixels: &pixels,
|
||||
baked: &baked,
|
||||
block_scales: BlockScales::default(),
|
||||
preview: None,
|
||||
images: &images,
|
||||
bounds: mesh.bounds(),
|
||||
};
|
||||
|
||||
for size in [(32, 32), (64, 64), (128, 128), (128, 32)] {
|
||||
let coverage = covered_texels(&inputs, size);
|
||||
assert!(coverage.iter().all(|covered| *covered), "the plane covers the entire {size:?} bake, including between working texel centers");
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn coverage_expands_scaled_tiles_without_crossing_block_borders() {
|
||||
use texturecraft_core::{Project, TextureSet};
|
||||
use texturecraft_geom::{NO_TRI, UvGBuffer, primitives};
|
||||
|
||||
let mesh = primitives::plane(2.0, 1);
|
||||
let mut project = Project::new("Tile coverage", "builtin:plane");
|
||||
let mut set = TextureSet::new("Tiles", 0, 64);
|
||||
set.uv_tiles = vec![1001, 1002, 1003];
|
||||
set.tile_resolutions.insert(1002, 32);
|
||||
let scales = set.block_scales();
|
||||
project.texture_sets.push(set);
|
||||
let mut gbuf = UvGBuffer::new(&mesh, 0, 192, 64);
|
||||
for (index, triangle) in gbuf.tri.iter_mut().enumerate() {
|
||||
if !(64..96).contains(&(index % 192)) || index / 192 >= 32 {
|
||||
*triangle = NO_TRI;
|
||||
}
|
||||
}
|
||||
let pixels = Default::default();
|
||||
let images = Default::default();
|
||||
let baked = Default::default();
|
||||
let inputs = Inputs {
|
||||
project: &project,
|
||||
ts: 0,
|
||||
mesh: &mesh,
|
||||
gbuf: &gbuf,
|
||||
pixels: &pixels,
|
||||
baked: &baked,
|
||||
block_scales: scales,
|
||||
preview: None,
|
||||
images: &images,
|
||||
bounds: mesh.bounds(),
|
||||
};
|
||||
|
||||
let covered = covered_texels(&inputs, (384, 128));
|
||||
for (index, covered) in covered.iter().enumerate() {
|
||||
assert_eq!(*covered, (128..256).contains(&(index % 384)), "bake texel ({}, {})", index % 384, index / 384);
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn unused_maps_are_evicted_even_while_undo_keeps_the_sources_alive() {
|
||||
let sources: Vec<_> = (0..=CACHE_MAPS).map(|_| Arc::new(vec![0.5; 16])).collect();
|
||||
let scales = BlockScales::default();
|
||||
let key = ((4, 4), (4, 4), (4, 4));
|
||||
let sizes = store(&sources[0], key, &scales, CurvatureSizes { levels: Vec::new() });
|
||||
let first = Arc::downgrade(&sizes);
|
||||
drop(sizes);
|
||||
for source in sources.iter().skip(1) {
|
||||
store(source, key, &scales, CurvatureSizes { levels: Vec::new() });
|
||||
}
|
||||
|
||||
assert!(first.upgrade().is_none(), "undo history may retain the bake, but not an unlimited number of derived maps");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn cache_budget_evicts_old_levels_but_keeps_one_large_map() {
|
||||
let source = Arc::new(vec![0.5]);
|
||||
let key = ((1, 1), (1, 1), (1, 1));
|
||||
let entry = || {
|
||||
let level = CurvatureSizeLevel { step: 1, width: 4, height: 1, block: (4, 1), deviation: vec![0; 4] };
|
||||
let sizes = CurvatureSizes { levels: vec![Some(Arc::new(level))] };
|
||||
(Arc::downgrade(&source), key, BlockScales::default(), Arc::new(sizes))
|
||||
};
|
||||
let mut cache = vec![entry(), entry(), entry()];
|
||||
let oldest = Arc::downgrade(&cache[0].3);
|
||||
let newest = cache[2].3.clone();
|
||||
|
||||
trim_cache(&mut cache, 16);
|
||||
assert_eq!(cache.len(), 2);
|
||||
assert!(oldest.upgrade().is_none());
|
||||
trim_cache(&mut cache, 1);
|
||||
assert_eq!(cache.len(), 1, "the active map must not rebuild once per composite tile");
|
||||
assert!(Arc::ptr_eq(&cache[0].3, &newest));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn padding_keeps_an_island_border_from_reading_flat() {
|
||||
let map_size: u32 = 64;
|
||||
let left_half = |texel: u32| texel % map_size < map_size / 2;
|
||||
let curvature: Vec<f32> = (0..map_size * map_size).map(|texel| if left_half(texel) { 1.0 } else { 0.0 }).collect();
|
||||
let covered: Vec<bool> = (0..map_size * map_size).map(left_half).collect();
|
||||
let shape = (map_size, map_size);
|
||||
let sizes = CurvatureSizes::build(&curvature, shape, &covered, shape, &[true; CurvatureDetail::BLURRED_SIZES], None);
|
||||
|
||||
// The last covered column, halfway down
|
||||
let (border_x, border_y) = (map_size / 2 - 1, map_size / 2);
|
||||
for level in sizes.levels.iter().flatten() {
|
||||
assert!((level.sample(border_x, border_y) - 0.5).abs() < 0.01, "the border keeps the island's curvature, not the empty texels beside it");
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn uniform_curvature_keeps_its_strength_at_block_borders() {
|
||||
let (map_width, map_height): (u32, u32) = (256, 256);
|
||||
// Curvature 0.8 reads 0.3 above the neutral 0.5 at every size
|
||||
const CURVATURE: f32 = 0.8;
|
||||
let expected = CURVATURE - 0.5;
|
||||
let curvature = vec![CURVATURE; (map_width * map_height) as usize];
|
||||
let covered = vec![true; curvature.len()];
|
||||
let block = (map_width / 2, map_height);
|
||||
let sizes = CurvatureSizes::build(&curvature, (map_width, map_height), &covered, block, &[true; CurvatureDetail::BLURRED_SIZES], None);
|
||||
|
||||
// The map's corner, then the last texel of the left block and the first of the right one, halfway down
|
||||
let border_texels = [(0, 0), (block.0 - 1, map_height / 2), (block.0, map_height / 2)];
|
||||
for level in sizes.levels.iter().flatten() {
|
||||
for (x, y) in border_texels {
|
||||
assert!((level.sample(x, y) - expected).abs() < 0.01, "texel ({x}, {y}) reads {} instead of the uniform {expected}", level.sample(x, y));
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_new_layout_replaces_the_sizes_of_the_old_one() {
|
||||
let curvature = Arc::new(vec![0.5; 16]);
|
||||
let scales = BlockScales::default();
|
||||
let entries_for_curvature = || {
|
||||
let cache = CACHE.lock().unwrap_or_else(|poisoned| poisoned.into_inner());
|
||||
cache.iter().filter(|(source, ..)| std::ptr::eq(source.as_ptr(), Arc::as_ptr(&curvature))).count()
|
||||
};
|
||||
|
||||
store(&curvature, ((4, 4), (4, 4), (4, 4)), &scales, CurvatureSizes { levels: Vec::new() });
|
||||
store(&curvature, ((4, 4), (2, 2), (8, 8)), &scales, CurvatureSizes { levels: Vec::new() });
|
||||
assert_eq!(entries_for_curvature(), 1, "only the latest layout of a curvature map stays cached");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn sizes_built_on_demand_match_a_full_build() {
|
||||
let map_size: u32 = 64;
|
||||
let curvature: Vec<f32> =
|
||||
(0..map_size * map_size).map(|texel| 0.5 + 0.4 * ((texel % map_size) as f32 * 0.3).sin() * ((texel / map_size) as f32 * 0.2).cos()).collect();
|
||||
let covered = vec![true; (map_size * map_size) as usize];
|
||||
let shape = (map_size, map_size);
|
||||
let all = vec![true; CurvatureDetail::BLURRED_SIZES];
|
||||
let full = CurvatureSizes::build(&curvature, shape, &covered, shape, &all, None);
|
||||
|
||||
let even: Vec<bool> = (0..all.len()).map(|level| level % 2 == 0).collect();
|
||||
let partial = CurvatureSizes::build(&curvature, shape, &covered, shape, &even, None);
|
||||
assert!(partial.levels.iter().zip(&even).all(|(level, needed)| level.is_some() == *needed), "only the needed sizes are built");
|
||||
|
||||
let completed = CurvatureSizes::build(&curvature, shape, &covered, shape, &all, Some(&partial));
|
||||
for ((built, expected), earlier) in completed.levels.iter().zip(&full.levels).zip(&partial.levels) {
|
||||
assert_eq!(built.as_ref().map(|level| &level.deviation), expected.as_ref().map(|level| &level.deviation), "the same values either way");
|
||||
if let (Some(built), Some(earlier)) = (built, earlier) {
|
||||
assert!(Arc::ptr_eq(built, earlier), "sizes already built are kept, not rebuilt");
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
+265
-91
@@ -4,17 +4,20 @@
|
||||
|
||||
use std::borrow::Cow;
|
||||
use std::collections::{BTreeMap, HashMap};
|
||||
use std::sync::Arc;
|
||||
|
||||
use rayon::prelude::*;
|
||||
use texturecraft_core::{
|
||||
BakedMap, BlendMode, BlockScales, Channel, ChannelKind, CompareOp, Effect, EffectKind, Fill, Filter, Generator, GeneratorKind, HeightMask, Layer, LayerId,
|
||||
LayerKind, Mask, MaskBackground, NormalFormat, Project, Projection, Source, TextureSet, TileGrid, blend1, blend3, lum, mix3, per_unit,
|
||||
BakedMap, BlendMode, BlockScales, Channel, ChannelKind, CompareOp, CurvatureDetail, CurvatureMode, Effect, EffectKind, Fill, Filter, Generator,
|
||||
GeneratorKind, HeightMask, Layer, LayerId, LayerKind, Mask, MaskBackground, NormalFormat, Project, Projection, Source, TextureSet, TileGrid, blend1,
|
||||
blend3, lum, mix3, per_unit,
|
||||
};
|
||||
use texturecraft_geom::glam::{Vec2, Vec3};
|
||||
use texturecraft_geom::{Mesh, NO_TRI, UvGBuffer};
|
||||
use texturecraft_texel::{DilationMap, TILE, TILE_AREA, TileImage, from_u16, noise, to_u16, to_u16_signed};
|
||||
|
||||
use crate::below::{Band, BelowCache, Level};
|
||||
use crate::curvature_sizes::CurvatureSizes;
|
||||
use crate::pattern::{Coords, decal_uv, image_samples, procedural, world_noise};
|
||||
use crate::store::{BakedMaps, ImageStore, PixelStore, decode};
|
||||
|
||||
@@ -204,6 +207,8 @@ struct EffectPlan<'a> {
|
||||
opacity: f32,
|
||||
data: Option<Cow<'a, [u16]>>,
|
||||
preview: bool,
|
||||
/// The curvature detail sizes a generator with detail reads.
|
||||
curvature_sizes: Option<Arc<CurvatureSizes>>,
|
||||
}
|
||||
|
||||
struct MaskPlan<'a> {
|
||||
@@ -304,6 +309,12 @@ fn direction(angle: f32) -> [f32; 2] {
|
||||
[cs, -sn]
|
||||
}
|
||||
|
||||
/// Gain on the curvature map's own deviation from flat (±0.5 reaches black and white).
|
||||
const MAP_GAIN: f32 = 2.0;
|
||||
|
||||
/// Gain per texel of a detail size: blurring spreads an edge over about twice its radius, so wider sizes need proportionally more to reach full strength.
|
||||
const GAIN_PER_DETAIL_TEXEL: f32 = 2.0 * std::f32::consts::SQRT_2;
|
||||
|
||||
/// Samples along a directional or slope blur at most (beyond, samples spread out).
|
||||
const LINE_SAMPLES: i32 = 24;
|
||||
|
||||
@@ -421,17 +432,20 @@ fn gather(op: Op, orig: &[f32], cover: &[f32], comps: usize, (x0, y0, w, h): (u3
|
||||
/// the region it is computed in, so tiles composited in any grouping agree exactly.
|
||||
const FIX: f64 = (1u64 << 24) as f64;
|
||||
|
||||
/// Three running-sum box blurs (≈ Gaussian) of a `w × h` image along rows then along columns.
|
||||
/// Rows (and columns, transposed) blur in parallel.
|
||||
fn blur(data: &mut [f32], w: usize, h: usize, r: usize) {
|
||||
let fix = |v: &f32| if v.is_finite() { (f64::from(v.clamp(-1e6, 1e6)) * FIX).round() as i64 } else { 0 };
|
||||
let mut v: Vec<i64> = data.par_iter().map(fix).collect();
|
||||
blur_rows(&mut v, w, r);
|
||||
let mut t = transpose(&v, w, h);
|
||||
blur_rows(&mut t, h, r);
|
||||
data.par_iter_mut().zip(transpose(&t, h, w)).for_each(|(d, s)| *d = (s as f64 / FIX) as f32);
|
||||
/// Three running-sum box blurs (≈ Gaussian) of a `width × height` image along its rows, then its columns, each in parallel.
|
||||
pub(crate) fn blur(data: &mut [f32], width: usize, height: usize, radius: usize) {
|
||||
let to_fixed = |value: &f32| if value.is_finite() { (f64::from(value.clamp(-1e6, 1e6)) * FIX).round() as i64 } else { 0 };
|
||||
let mut fixed: Vec<i64> = data.par_iter().map(to_fixed).collect();
|
||||
blur_rows(&mut fixed, width, radius);
|
||||
|
||||
let mut columns = transpose(&fixed, width, height);
|
||||
blur_rows(&mut columns, height, radius);
|
||||
data.par_iter_mut().zip(transpose(&columns, height, width)).for_each(|(target, blurred)| *target = (blurred as f64 / FIX) as f32);
|
||||
}
|
||||
|
||||
/// The box blurs `blur` runs along each axis
|
||||
pub(crate) const BLUR_BOX_PASSES: usize = 3;
|
||||
|
||||
/// Three box blurs of radius `r` along every row (`w` long) of `data`.
|
||||
fn blur_rows(data: &mut [i64], w: usize, r: usize) {
|
||||
if w == 0 {
|
||||
@@ -439,7 +453,7 @@ fn blur_rows(data: &mut [i64], w: usize, r: usize) {
|
||||
}
|
||||
data.par_chunks_mut(w).for_each(|row| {
|
||||
let mut tmp = vec![0i64; row.len()];
|
||||
for _ in 0..3 {
|
||||
for _ in 0..BLUR_BOX_PASSES {
|
||||
box_line(row, &mut tmp, r);
|
||||
row.copy_from_slice(&tmp);
|
||||
}
|
||||
@@ -760,28 +774,53 @@ fn fields_of(inp: &Inputs, channels: &[Channel], list: &[LayerId], tiles: &[(u32
|
||||
if tiles.is_empty() || inp.gbuf.width == 0 {
|
||||
return out;
|
||||
}
|
||||
let res = inp.gbuf.width;
|
||||
|
||||
let working_width = inp.gbuf.width;
|
||||
let mut order = Vec::new();
|
||||
draw_order(inp.project, list, 0, &mut order);
|
||||
prepare_curvature_sizes(inp, &order);
|
||||
|
||||
for id in order {
|
||||
let Some(layer) = inp.project.content_layer(id) else { continue };
|
||||
if let Some(m) = layer_mask(inp.project, id).filter(|m| m.enabled && neighbourhood(&m.effects, res).is_some())
|
||||
&& let Some(f) = field(inp, channels, &out, id, Job::Mask(m), tiles)
|
||||
|
||||
if let Some(mask) = layer_mask(inp.project, id).filter(|mask| mask.enabled && neighbourhood(&mask.effects, working_width).is_some())
|
||||
&& let Some(filtered) = field(inp, channels, &out, id, Job::Mask(mask), tiles)
|
||||
{
|
||||
out.insert(FieldKey::Mask(id), f);
|
||||
out.insert(FieldKey::Mask(id), filtered);
|
||||
}
|
||||
if layer.is_group() || neighbourhood(&layer.content_effects, res).is_none() {
|
||||
|
||||
if layer.is_group() || neighbourhood(&layer.content_effects, working_width).is_none() {
|
||||
continue;
|
||||
}
|
||||
for ch in channels.iter().filter(|c| layer.channels.contains_key(c)) {
|
||||
if let Some(f) = field(inp, channels, &out, id, Job::Content(*ch), tiles) {
|
||||
out.insert(FieldKey::Content(id, *ch), f);
|
||||
for channel in channels.iter().filter(|channel| layer.channels.contains_key(channel)) {
|
||||
if let Some(filtered) = field(inp, channels, &out, id, Job::Content(*channel), tiles) {
|
||||
out.insert(FieldKey::Content(id, *channel), filtered);
|
||||
}
|
||||
}
|
||||
}
|
||||
out
|
||||
}
|
||||
|
||||
/// Build the curvature detail sizes every visible generator of `layers` reads, once, before tiles composite in parallel.
|
||||
fn prepare_curvature_sizes(inp: &Inputs, layers: &[LayerId]) {
|
||||
let visible = layers.iter().filter(|id| inp.project.layers.get(id).is_some_and(|layer| layer.visible));
|
||||
let masks = visible.filter_map(|id| layer_mask(inp.project, *id)).filter(|mask| mask.enabled);
|
||||
prepare_mask_curvature_sizes(inp, masks);
|
||||
}
|
||||
|
||||
/// Build the curvature detail sizes the visible generators of `masks` read, once, before tiles composite in parallel.
|
||||
fn prepare_mask_curvature_sizes<'a>(inp: &Inputs, masks: impl Iterator<Item = &'a Mask>) {
|
||||
let mut needed = [false; CurvatureDetail::BLURRED_SIZES];
|
||||
for effect in masks.flat_map(|mask| &mask.effects).filter(|effect| effect.visible) {
|
||||
if let EffectKind::Generator(Generator { detail: Some(detail), .. }) = &effect.kind {
|
||||
for (slot, in_use) in needed.iter_mut().zip(detail.blurred_sizes_in_use()) {
|
||||
*slot |= in_use;
|
||||
}
|
||||
}
|
||||
}
|
||||
CurvatureSizes::of(inp, &needed);
|
||||
}
|
||||
|
||||
struct Node<'a> {
|
||||
id: LayerId,
|
||||
content: Content<'a>,
|
||||
@@ -799,21 +838,26 @@ struct Node<'a> {
|
||||
|
||||
/// Plans of the visible effects of a stack: mask effects (`channel` None) or the content
|
||||
/// effects of one channel (paint effects then read that channel's pixels).
|
||||
fn effect_plans<'a>(inp: &Inputs<'a>, effects: &'a [Effect], tx: u32, ty: u32, channel: Option<Channel>) -> Vec<EffectPlan<'a>> {
|
||||
fn effect_plans<'a>(inp: &Inputs<'a>, effects: &'a [Effect], tile_x: u32, tile_y: u32, channel: Option<Channel>) -> Vec<EffectPlan<'a>> {
|
||||
effects
|
||||
.iter()
|
||||
.filter(|e| e.visible)
|
||||
.map(|e| {
|
||||
let (img, target) = match channel {
|
||||
Some(c) => (inp.pixels.layer(e.id, c), PaintTarget::Layer(e.id)),
|
||||
None => (inp.pixels.masks.get(&e.id), PaintTarget::Mask(e.id)),
|
||||
.filter(|effect| effect.visible)
|
||||
.map(|effect| {
|
||||
let (image, target) = match channel {
|
||||
Some(channel) => (inp.pixels.layer(effect.id, channel), PaintTarget::Layer(effect.id)),
|
||||
None => (inp.pixels.masks.get(&effect.id), PaintTarget::Mask(effect.id)),
|
||||
};
|
||||
let curvature_sizes = match &effect.kind {
|
||||
EffectKind::Generator(Generator { detail: Some(detail), .. }) => CurvatureSizes::of(inp, &detail.blurred_sizes_in_use()),
|
||||
_ => None,
|
||||
};
|
||||
EffectPlan {
|
||||
kind: &e.kind,
|
||||
blend: e.blend,
|
||||
opacity: e.opacity,
|
||||
data: if e.kind.painted() { tile_of(inp, img, tx, ty, channel) } else { None },
|
||||
kind: &effect.kind,
|
||||
blend: effect.blend,
|
||||
opacity: effect.opacity,
|
||||
data: if effect.kind.painted() { tile_of(inp, image, tile_x, tile_y, channel) } else { None },
|
||||
preview: previews(inp, target),
|
||||
curvature_sizes,
|
||||
}
|
||||
})
|
||||
.collect()
|
||||
@@ -1166,94 +1210,142 @@ impl<'a, 'b> Texel<'a, 'b> {
|
||||
}
|
||||
}
|
||||
|
||||
fn generator(&mut self, g: &Generator) -> f32 {
|
||||
let c = self.coords();
|
||||
let s = match g.kind {
|
||||
GeneratorKind::EdgeWear => (self.baked(BakedMap::Curvature).unwrap_or(0.5) - 0.5) * 2.0,
|
||||
GeneratorKind::Curvature => self.baked(BakedMap::Curvature).unwrap_or(0.5),
|
||||
GeneratorKind::Dirt => 1.0 - self.baked(BakedMap::AmbientOcclusion).unwrap_or(1.0),
|
||||
GeneratorKind::AmbientOcclusion => self.baked(BakedMap::AmbientOcclusion).unwrap_or(1.0),
|
||||
GeneratorKind::ThinAreas => 1.0 - self.baked(BakedMap::Thickness).unwrap_or(1.0),
|
||||
GeneratorKind::Position => c.pos.dot(Vec3::from(g.direction).try_normalize().unwrap_or(Vec3::Y)) * 0.5 + 0.5,
|
||||
GeneratorKind::Direction => c.nrm.dot(Vec3::from(g.direction).try_normalize().unwrap_or(Vec3::Y)) * 0.5 + 0.5,
|
||||
fn generator(&mut self, generator: &Generator, curvature_sizes: Option<&CurvatureSizes>) -> f32 {
|
||||
let coords = self.coords();
|
||||
let signal = match (generator.kind, &generator.detail) {
|
||||
(GeneratorKind::Curvature | GeneratorKind::EdgeWear, Some(detail)) => self.curvature_detail(detail, curvature_sizes),
|
||||
(GeneratorKind::EdgeWear, None) => (self.baked(BakedMap::Curvature).unwrap_or(0.5) - 0.5) * 2.0,
|
||||
(GeneratorKind::Curvature, None) => self.baked(BakedMap::Curvature).unwrap_or(0.5),
|
||||
(GeneratorKind::Dirt, _) => 1.0 - self.baked(BakedMap::AmbientOcclusion).unwrap_or(1.0),
|
||||
(GeneratorKind::AmbientOcclusion, _) => self.baked(BakedMap::AmbientOcclusion).unwrap_or(1.0),
|
||||
(GeneratorKind::ThinAreas, _) => 1.0 - self.baked(BakedMap::Thickness).unwrap_or(1.0),
|
||||
(GeneratorKind::Position, _) => coords.pos.dot(Vec3::from(generator.direction).try_normalize().unwrap_or(Vec3::Y)) * 0.5 + 0.5,
|
||||
(GeneratorKind::Direction, _) => coords.nrm.dot(Vec3::from(generator.direction).try_normalize().unwrap_or(Vec3::Y)) * 0.5 + 0.5,
|
||||
};
|
||||
let s = if g.noise_amount > 0.0 { s + (world_noise(c.pos, g.noise_scale, g.seed) - 0.5) * g.noise_amount } else { s };
|
||||
let th = 1.0 - g.level.clamp(0.0, 1.0);
|
||||
let soft = g.softness.max(1e-3);
|
||||
let t = ((s - (th - soft)) / (2.0 * soft)).clamp(0.0, 1.0);
|
||||
let v = t * t * (3.0 - 2.0 * t);
|
||||
if g.invert { 1.0 - v } else { v }
|
||||
let signal = if generator.noise_amount > 0.0 {
|
||||
let noise = world_noise(coords.pos, generator.noise_scale, generator.seed);
|
||||
if let (GeneratorKind::Curvature | GeneratorKind::EdgeWear, Some(detail)) = (generator.kind, &generator.detail) {
|
||||
// Break up curvature without inventing edges or cavities on a flat surface
|
||||
let neutral = if detail.mode == CurvatureMode::Raw { 0.5 } else { 0.0 };
|
||||
neutral + (signal - neutral) * (1.0 - noise * generator.noise_amount).max(0.0)
|
||||
} else {
|
||||
signal + (noise - 0.5) * generator.noise_amount
|
||||
}
|
||||
} else {
|
||||
signal
|
||||
};
|
||||
|
||||
// A smooth step from black to white over 2 × softness around 1 − level
|
||||
let threshold = 1.0 - generator.level.clamp(0.0, 1.0);
|
||||
let softness = generator.softness.max(1e-3);
|
||||
let ramp = ((signal - (threshold - softness)) / (2.0 * softness)).clamp(0.0, 1.0);
|
||||
let value = ramp * ramp * (3.0 - 2.0 * ramp);
|
||||
if generator.invert { 1.0 - value } else { value }
|
||||
}
|
||||
|
||||
fn mask(&mut self, m: &MaskPlan) -> f32 {
|
||||
let mut v = m.background;
|
||||
let mut skip = 0;
|
||||
if let Some((k, field)) = m.start
|
||||
&& let Some(f) = field.get(self.x, self.y).and_then(|d| d.first().copied())
|
||||
{
|
||||
v = f;
|
||||
skip = k + 1;
|
||||
/// The curvature of `detail`'s mode at this texel: each detail size's edges and cavities, weighted and combined like a screen blend.
|
||||
fn curvature_detail(&self, detail: &CurvatureDetail, curvature_sizes: Option<&CurvatureSizes>) -> f32 {
|
||||
let combine = |edges: f32, cavities: f32| match detail.mode {
|
||||
CurvatureMode::Edges => edges,
|
||||
CurvatureMode::Cavities => cavities,
|
||||
CurvatureMode::Both => 1.0 - (1.0 - edges) * (1.0 - cavities),
|
||||
CurvatureMode::Raw => 0.5 + 0.5 * (edges - cavities),
|
||||
};
|
||||
|
||||
// Without curvature to read the texel is flat: no edges or cavities
|
||||
let Some(curvature) = self.baked(BakedMap::Curvature) else { return combine(0.0, 0.0) };
|
||||
|
||||
let working_size = (self.res, self.inp.gbuf.height);
|
||||
let texel_uv = [(self.x as f32 + 0.5) / working_size.0.max(1) as f32, (self.y as f32 + 0.5) / working_size.1.max(1) as f32];
|
||||
let Some(baked_uv) = self.inp.block_scales.bake_uv(texel_uv, working_size) else { return combine(0.0, 0.0) };
|
||||
|
||||
let baked_size = (self.inp.baked.resolution, self.inp.baked.height(BakedMap::Curvature));
|
||||
let (baked_x, baked_y) = ((baked_uv[0] * baked_size.0 as f32) as u32, (baked_uv[1] * baked_size.1 as f32) as u32);
|
||||
let blurred = |index: usize| {
|
||||
curvature_sizes.and_then(|sizes| sizes.levels.get(index)).and_then(Option::as_deref).map_or(0.0, |level| level.sample(baked_x, baked_y))
|
||||
};
|
||||
let (mut edges, mut cavities) = (0.0f32, 0.0f32);
|
||||
for (index, (size, weight)) in CurvatureDetail::SIZES.iter().zip(detail.weights).enumerate() {
|
||||
let deviation = if index == 0 { curvature - 0.5 } else { blurred(index - 1) };
|
||||
|
||||
let response = deviation * if *size == 0.0 { MAP_GAIN } else { GAIN_PER_DETAIL_TEXEL * size };
|
||||
let weight = weight.clamp(0.0, 1.0);
|
||||
edges = 1.0 - (1.0 - edges) * (1.0 - weight * response.clamp(0.0, 1.0));
|
||||
cavities = 1.0 - (1.0 - cavities) * (1.0 - weight * (-response).clamp(0.0, 1.0));
|
||||
}
|
||||
for e in m.effects.iter().skip(skip) {
|
||||
let o = e.opacity.clamp(0.0, 1.0);
|
||||
match e.kind {
|
||||
|
||||
combine(edges, cavities)
|
||||
}
|
||||
|
||||
fn mask(&mut self, plan: &MaskPlan) -> f32 {
|
||||
let mut value = plan.background;
|
||||
let mut skip = 0;
|
||||
if let Some((filtered_index, field)) = plan.start
|
||||
&& let Some(filtered) = field.get(self.x, self.y).and_then(|texel| texel.first().copied())
|
||||
{
|
||||
value = filtered;
|
||||
skip = filtered_index + 1;
|
||||
}
|
||||
|
||||
for effect in plan.effects.iter().skip(skip) {
|
||||
let opacity = effect.opacity.clamp(0.0, 1.0);
|
||||
match effect.kind {
|
||||
EffectKind::Paint | EffectKind::Path(_) => {
|
||||
let (mut pv, mut cov) = match e.data.as_deref() {
|
||||
Some(d) => (from_u16(d.get(self.o * 2).copied().unwrap_or(0)), from_u16(d.get(self.o * 2 + 1).copied().unwrap_or(0))),
|
||||
let (mut painted, mut cov) = match effect.data.as_deref() {
|
||||
Some(data) => (from_u16(data.get(self.o * 2).copied().unwrap_or(0)), from_u16(data.get(self.o * 2 + 1).copied().unwrap_or(0))),
|
||||
None => (0.0, 0.0),
|
||||
};
|
||||
if e.preview
|
||||
&& let Some(p) = self.inp.preview
|
||||
if effect.preview
|
||||
&& let Some(preview) = self.inp.preview
|
||||
{
|
||||
let a = (self.stroke * p.opacity).clamp(0.0, 1.0);
|
||||
if p.erase {
|
||||
pv *= 1.0 - a;
|
||||
cov *= 1.0 - a;
|
||||
let stroke = (self.stroke * preview.opacity).clamp(0.0, 1.0);
|
||||
if preview.erase {
|
||||
painted *= 1.0 - stroke;
|
||||
cov *= 1.0 - stroke;
|
||||
} else {
|
||||
pv = p.mask_value * a + pv * (1.0 - a);
|
||||
cov = a + cov * (1.0 - a);
|
||||
painted = preview.mask_value * stroke + painted * (1.0 - stroke);
|
||||
cov = stroke + cov * (1.0 - stroke);
|
||||
}
|
||||
}
|
||||
if cov > 0.0 {
|
||||
let val = pv / cov.max(1e-5);
|
||||
v += (blend1(e.blend, v, val) - v) * cov * o;
|
||||
let layer_value = painted / cov.max(1e-5);
|
||||
value += (blend1(effect.blend, value, layer_value) - value) * cov * opacity;
|
||||
}
|
||||
}
|
||||
EffectKind::Fill { source, projection } => {
|
||||
let val = self.source(source, projection, ChannelKind::Scalar)[0];
|
||||
v += (blend1(e.blend, v, val) - v) * o * self.cover(std::iter::once(source), projection);
|
||||
let fill = self.source(source, projection, ChannelKind::Scalar)[0];
|
||||
value += (blend1(effect.blend, value, fill) - value) * opacity * self.cover(std::iter::once(source), projection);
|
||||
}
|
||||
EffectKind::Generator(g) => {
|
||||
let val = self.generator(g);
|
||||
v += (blend1(e.blend, v, val) - v) * o;
|
||||
EffectKind::Generator(generator) => {
|
||||
let generated = self.generator(generator, effect.curvature_sizes.as_deref());
|
||||
value += (blend1(effect.blend, value, generated) - value) * opacity;
|
||||
}
|
||||
EffectKind::Levels(l) => v += (l.apply(v) - v) * o,
|
||||
EffectKind::Filter(f) => {
|
||||
// A mask is gray (HSL only changes its lightness); neighbourhood filters come
|
||||
// precomputed through `MaskPlan::start`.
|
||||
let val = f.point(ChannelKind::Scalar, [v; 3]).map_or(v, |x| x[0]);
|
||||
v += (val - v) * o;
|
||||
EffectKind::Levels(levels) => value += (levels.apply(value) - value) * opacity,
|
||||
EffectKind::Filter(filter) => {
|
||||
// A mask is gray (HSL only changes its lightness); neighbourhood filters come precomputed through `MaskPlan::start`
|
||||
let filtered = filter.point(ChannelKind::Scalar, [value; 3]).map_or(value, |gray| gray[0]);
|
||||
value += (filtered - value) * opacity;
|
||||
}
|
||||
EffectKind::ColorSelection { colors, tolerance } => {
|
||||
let id = self.baked_color(BakedMap::Id);
|
||||
let hit = id.is_some_and(|c| colors.iter().any(|k| (k[0] - c[0]).abs().max((k[1] - c[1]).abs()).max((k[2] - c[2]).abs()) <= *tolerance));
|
||||
let val = if hit { 1.0 } else { 0.0 };
|
||||
v += (blend1(e.blend, v, val) - v) * o;
|
||||
let within = |picked: &[f32; 3], color: [f32; 3]| (0..3).all(|component| (picked[component] - color[component]).abs() <= *tolerance);
|
||||
let selected = if id.is_some_and(|color| colors.iter().any(|picked| within(picked, color))) { 1.0 } else { 0.0 };
|
||||
value += (blend1(effect.blend, value, selected) - value) * opacity;
|
||||
}
|
||||
EffectKind::Compare { op, value, tolerance } => {
|
||||
EffectKind::Compare { op, value: compared, tolerance } => {
|
||||
let pass = match op {
|
||||
CompareOp::LesserThan => v < *value,
|
||||
CompareOp::GreaterThan => v > *value,
|
||||
CompareOp::WithinTolerance => (v - value).abs() <= *tolerance,
|
||||
CompareOp::LesserThan => value < *compared,
|
||||
CompareOp::GreaterThan => value > *compared,
|
||||
CompareOp::WithinTolerance => (value - compared).abs() <= *tolerance,
|
||||
};
|
||||
let val = if pass { 1.0 } else { 0.0 };
|
||||
v += (val - v) * o;
|
||||
let result = if pass { 1.0 } else { 0.0 };
|
||||
value += (result - value) * opacity;
|
||||
}
|
||||
// Content-only effects.
|
||||
// Content-only effects
|
||||
EffectKind::Material(_) | EffectKind::Anchor => {}
|
||||
}
|
||||
}
|
||||
v.clamp(0.0, 1.0)
|
||||
value.clamp(0.0, 1.0)
|
||||
}
|
||||
|
||||
/// Composite `nodes` over `acc`, recording anchors. Returns true when it reached the `stop`
|
||||
@@ -1898,6 +1990,10 @@ pub fn mask_image(inputs: &Inputs, id: LayerId, size: u32) -> Option<Vec<u8>> {
|
||||
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 tiles: HashMap<(u32, u32), Vec<u8>> = coordinates
|
||||
.par_iter()
|
||||
@@ -1951,6 +2047,10 @@ pub fn mask_at(inputs: &Inputs, id: LayerId, texels: &[(u32, u32)]) -> Option<Ve
|
||||
}
|
||||
|
||||
let channels = inputs.project.texture_set(inputs.ts).map(|set| set.channel_list()).unwrap_or_default();
|
||||
|
||||
// A hidden layer's mask is left out of the stack's preparation
|
||||
prepare_mask_curvature_sizes(inputs, std::iter::once(mask));
|
||||
|
||||
// Filters and anchors can depend on texels outside the requested tiles
|
||||
let fields = neighbourhood_fields(inputs, &channels, &all_tiles(inputs.gbuf.width, inputs.gbuf.height));
|
||||
let values: Vec<(usize, f32)> = requested
|
||||
@@ -2455,6 +2555,80 @@ mod tests {
|
||||
assert!(blurred_then_warped.iter().zip(&warped).any(|(chained, single)| (chained - single).abs() > 0.1), "the blur under the warp still runs");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn larger_curvature_detail_sizes_reach_further_from_an_edge() {
|
||||
let mut fixture = fixture();
|
||||
fixture.gbuf = UvGBuffer::new(&fixture.mesh, 0, 256, 256);
|
||||
fixture.project.texture_sets[0].resolution = 256;
|
||||
let ridge: Vec<f32> = (0..256 * 256).map(|texel| if texel % 256 == 128 { 1.0 } else { 0.5 }).collect();
|
||||
fixture.baked = BakedMaps { resolution: 256, maps: [(BakedMap::Curvature, Arc::new(ridge))].into() };
|
||||
let layer = fill_layer(&mut fixture.project, [1.0; 3], 1.0);
|
||||
let row_with = |fixture: &mut Fixture, weights: [f32; 7]| -> Vec<f32> {
|
||||
let detail = CurvatureDetail { mode: CurvatureMode::Edges, weights };
|
||||
let generator = Generator { level: 0.5, softness: 0.5, noise_amount: 0.0, detail: Some(detail), ..Generator::new(GeneratorKind::Curvature) };
|
||||
let mut mask = Mask::new(MaskBackground::Black);
|
||||
mask.effects.push(Effect::new(fixture.project.alloc_id(), EffectKind::Generator(generator)));
|
||||
fixture.project.layer_mut(layer).unwrap().mask = Some(mask);
|
||||
let images = Default::default();
|
||||
let inputs = Inputs {
|
||||
project: &fixture.project,
|
||||
ts: 0,
|
||||
mesh: &fixture.mesh,
|
||||
gbuf: &fixture.gbuf,
|
||||
pixels: &fixture.pixels,
|
||||
baked: &fixture.baked,
|
||||
block_scales: BlockScales::default(),
|
||||
preview: None,
|
||||
images: &images,
|
||||
bounds: fixture.mesh.bounds(),
|
||||
};
|
||||
mask_at(&inputs, layer, &(120..137).map(|x| (x, 128)).collect::<Vec<_>>()).unwrap()
|
||||
};
|
||||
|
||||
// The row starts at x 120: the ridge is its ninth texel, five texels left of it the fourth
|
||||
let (ridge, five_texels_away) = (8, 3);
|
||||
let finest = row_with(&mut fixture, [1.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0]);
|
||||
let largest = row_with(&mut fixture, [0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 1.0]);
|
||||
assert!(finest[ridge] > 0.99 && finest[five_texels_away] < 0.01, "the map itself marks only the ridge: {finest:?}");
|
||||
assert!(largest[ridge] > 0.99 && largest[five_texels_away] > 0.5, "the largest size reaches texels away from it: {largest:?}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn curvature_detail_noise_keeps_flat_areas_neutral() {
|
||||
let mut fixture = fixture();
|
||||
fixture.baked = BakedMaps { resolution: 64, maps: [(BakedMap::Curvature, Arc::new(vec![0.5; 64 * 64]))].into() };
|
||||
let layer = fill_layer(&mut fixture.project, [1.0; 3], 1.0);
|
||||
let texels: Vec<_> = (0..64).map(|x| (x, 32)).collect();
|
||||
|
||||
for kind in [GeneratorKind::Curvature, GeneratorKind::EdgeWear] {
|
||||
for mode in CurvatureMode::ALL {
|
||||
let detail = CurvatureDetail { mode, weights: [1.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0] };
|
||||
let generator = Generator { level: 0.5, softness: 0.5, noise_amount: 2.0, detail: Some(detail), ..Generator::new(kind) };
|
||||
let mut mask = Mask::new(MaskBackground::Black);
|
||||
mask.effects.push(Effect::new(fixture.project.alloc_id(), EffectKind::Generator(generator)));
|
||||
fixture.project.layer_mut(layer).unwrap().mask = Some(mask);
|
||||
|
||||
let values = assert_sparse_mask_matches_image(&fixture, layer, &texels).unwrap();
|
||||
let expected = if mode == CurvatureMode::Raw { 0.5 } else { 0.0 };
|
||||
assert!(values.iter().all(|value| (value - expected).abs() < 0.001), "{kind:?} {mode:?} paints noise on flat curvature: {values:?}");
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn raw_curvature_reads_mid_gray_without_a_curvature_map() {
|
||||
let mut fixture = fixture();
|
||||
let layer = fill_layer(&mut fixture.project, [1.0; 3], 1.0);
|
||||
let detail = CurvatureDetail { mode: CurvatureMode::Raw, ..CurvatureDetail::default() };
|
||||
let generator = Generator { level: 0.5, softness: 0.5, noise_amount: 0.0, detail: Some(detail), ..Generator::new(GeneratorKind::Curvature) };
|
||||
let mut mask = Mask::new(MaskBackground::Black);
|
||||
mask.effects.push(Effect::new(fixture.project.alloc_id(), EffectKind::Generator(generator)));
|
||||
fixture.project.layer_mut(layer).unwrap().mask = Some(mask);
|
||||
|
||||
let values = assert_sparse_mask_matches_image(&fixture, layer, &[(32, 32)]).unwrap();
|
||||
assert!(values.iter().all(|value| (value - 0.5).abs() < 0.01), "flat curvature is mid gray in raw mode, not black: {values:?}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn blur_filter_softens_mask_edges() {
|
||||
let mut f = fixture();
|
||||
|
||||
@@ -9,6 +9,8 @@
|
||||
|
||||
mod baked_maps;
|
||||
pub mod below;
|
||||
mod curvature_size_level;
|
||||
pub mod curvature_sizes;
|
||||
pub mod display;
|
||||
pub mod eval;
|
||||
pub mod pattern;
|
||||
|
||||
@@ -6,6 +6,12 @@ use serde::{Deserialize, Serialize};
|
||||
|
||||
use crate::{BlendMode, Channel, ChannelKind, lum};
|
||||
|
||||
mod curvature_detail;
|
||||
mod curvature_mode;
|
||||
|
||||
pub use curvature_detail::CurvatureDetail;
|
||||
pub use curvature_mode::CurvatureMode;
|
||||
|
||||
/// Id of a layer or effect (one id space per project).
|
||||
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash, PartialOrd, Ord, Serialize, Deserialize)]
|
||||
pub struct LayerId(pub u64);
|
||||
@@ -540,17 +546,26 @@ pub struct Generator {
|
||||
/// Direction for `Position` / `Direction` generators (world space).
|
||||
pub direction: [f32; 3],
|
||||
pub invert: bool,
|
||||
/// Mode and detail sizes of `Curvature` / `EdgeWear` generators (None: the curvature map as baked, as before detail sizes existed).
|
||||
#[serde(default, skip_serializing_if = "Option::is_none")]
|
||||
pub detail: Option<CurvatureDetail>,
|
||||
}
|
||||
|
||||
impl Generator {
|
||||
pub fn new(kind: GeneratorKind) -> Generator {
|
||||
let (level, softness, noise_amount) = match kind {
|
||||
GeneratorKind::EdgeWear => (0.6, 0.12, 0.5),
|
||||
GeneratorKind::EdgeWear => (0.5, 0.25, 0.3),
|
||||
GeneratorKind::Curvature => (0.5, 0.5, 0.0),
|
||||
GeneratorKind::Dirt => (0.55, 0.25, 0.35),
|
||||
GeneratorKind::ThinAreas => (0.3, 0.2, 0.0),
|
||||
_ => (0.5, 0.25, 0.0),
|
||||
};
|
||||
Generator { kind, level, softness, noise_amount, noise_scale: 8.0, seed: 7, direction: [0.0, 1.0, 0.0], invert: false }
|
||||
let detail = match kind {
|
||||
GeneratorKind::Curvature => Some(CurvatureDetail::default()),
|
||||
GeneratorKind::EdgeWear => Some(CurvatureDetail { mode: CurvatureMode::Edges, weights: CurvatureDetail::EDGE_WEIGHTS }),
|
||||
_ => None,
|
||||
};
|
||||
Generator { kind, level, softness, noise_amount, noise_scale: 8.0, seed: 7, direction: [0.0, 1.0, 0.0], invert: false, detail }
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1050,6 +1065,17 @@ impl Effect {
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn curvature_generators_saved_before_detail_sizes_load_without_them() {
|
||||
let mut saved = serde_json::to_value(Generator::new(GeneratorKind::Curvature)).unwrap();
|
||||
assert!(saved.get("detail").is_some(), "new curvature generators have detail sizes");
|
||||
|
||||
saved.as_object_mut().unwrap().remove("detail");
|
||||
let loaded: Generator = serde_json::from_value(saved).unwrap();
|
||||
assert_eq!(loaded.detail, None);
|
||||
assert_eq!(Generator::new(GeneratorKind::Dirt).detail, None, "only curvature and edge wear generators have detail sizes");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn levels_map_range_and_gamma() {
|
||||
let l = Levels { in_low: 0.2, in_high: 0.6, gamma: 1.0, out_low: 0.0, out_high: 1.0 };
|
||||
|
||||
@@ -0,0 +1,36 @@
|
||||
use serde::{Deserialize, Serialize};
|
||||
|
||||
use super::curvature_mode::CurvatureMode;
|
||||
|
||||
/// How a curvature generator reads the curvature map: its mode and how much each detail size adds.
|
||||
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
|
||||
pub struct CurvatureDetail {
|
||||
pub mode: CurvatureMode,
|
||||
/// Weight (0..1) of each size in [`CurvatureDetail::SIZES`], finest first.
|
||||
pub weights: [f32; CurvatureDetail::SIZES.len()],
|
||||
}
|
||||
|
||||
impl CurvatureDetail {
|
||||
/// Detail sizes as blur radii in texels at 2K: the map itself, then doubling radii.
|
||||
pub const SIZES: [f32; 7] = [0.0, 1.0, 2.0, 4.0, 8.0, 16.0, 32.0];
|
||||
|
||||
/// Weights falling off with size, tuned by eye on hard-surface bakes: sharp edges first, broad shapes lit faintly.
|
||||
pub const BROAD_WEIGHTS: [f32; 7] = [1.0, 0.85, 0.7, 0.55, 0.4, 0.25, 0.15];
|
||||
|
||||
/// Mostly the finer sizes, tuned the same way: worn edges are thin lines.
|
||||
pub const EDGE_WEIGHTS: [f32; 7] = [1.0, 0.8, 0.5, 0.25, 0.1, 0.0, 0.0];
|
||||
|
||||
/// How many sizes are blurred copies of the map (all but the first).
|
||||
pub const BLURRED_SIZES: usize = CurvatureDetail::SIZES.len() - 1;
|
||||
|
||||
/// Which blurred sizes this detail reads: those with a weight above 0.
|
||||
pub fn blurred_sizes_in_use(&self) -> [bool; CurvatureDetail::BLURRED_SIZES] {
|
||||
std::array::from_fn(|blurred| self.weights.get(blurred + 1).is_some_and(|weight| *weight > 0.0))
|
||||
}
|
||||
}
|
||||
|
||||
impl Default for CurvatureDetail {
|
||||
fn default() -> Self {
|
||||
CurvatureDetail { mode: CurvatureMode::Edges, weights: CurvatureDetail::BROAD_WEIGHTS }
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,34 @@
|
||||
use serde::{Deserialize, Serialize};
|
||||
|
||||
/// Which side of the curvature map a curvature generator shows.
|
||||
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash, Serialize, Deserialize)]
|
||||
pub enum CurvatureMode {
|
||||
/// Convex edges white.
|
||||
#[default]
|
||||
Edges,
|
||||
/// Concave cavities white.
|
||||
Cavities,
|
||||
/// Edges and cavities both white.
|
||||
Both,
|
||||
/// Signed curvature around mid gray (cavities dark, edges light).
|
||||
Raw,
|
||||
}
|
||||
|
||||
impl CurvatureMode {
|
||||
pub const ALL: [CurvatureMode; 4] = [CurvatureMode::Edges, CurvatureMode::Cavities, CurvatureMode::Both, CurvatureMode::Raw];
|
||||
|
||||
pub fn label(self) -> &'static str {
|
||||
match self {
|
||||
CurvatureMode::Edges => "Edges",
|
||||
CurvatureMode::Cavities => "Cavities",
|
||||
CurvatureMode::Both => "Edges and cavities",
|
||||
CurvatureMode::Raw => "Raw curvature",
|
||||
}
|
||||
}
|
||||
|
||||
/// The mode named `name` (its variant or label, any case).
|
||||
pub fn parse(name: &str) -> Option<CurvatureMode> {
|
||||
let normalized = |text: &str| text.to_ascii_lowercase().replace([' ', '_', '-'], "");
|
||||
CurvatureMode::ALL.into_iter().find(|mode| normalized(&format!("{mode:?}")) == normalized(name) || normalized(mode.label()) == normalized(name))
|
||||
}
|
||||
}
|
||||
@@ -24,8 +24,9 @@ pub use bake::{
|
||||
pub use blend::{BlendMode, blend1, blend3, lum, mix3};
|
||||
pub use channel::{Channel, ChannelFormat, ChannelKind};
|
||||
pub use layer::{
|
||||
ChannelBlend, CompareOp, Decal, Effect, EffectKind, Fill, Filter, Generator, GeneratorKind, HeightMask, Layer, LayerId, LayerKind, Levels, LinkParam,
|
||||
LinkPreset, Mask, MaskBackground, MaterialLink, PathShape, Procedural, ProceduralKind, Projection, Source, gradient, hsl_adjust, per_unit,
|
||||
ChannelBlend, CompareOp, CurvatureDetail, CurvatureMode, Decal, Effect, EffectKind, Fill, Filter, Generator, GeneratorKind, HeightMask, Layer, LayerId,
|
||||
LayerKind, Levels, LinkParam, LinkPreset, Mask, MaskBackground, MaterialLink, PathShape, Procedural, ProceduralKind, Projection, Source, gradient,
|
||||
hsl_adjust, per_unit,
|
||||
};
|
||||
pub use project::{
|
||||
AoMixing, BlockScales, Camera, DepthOfField, DisplaySettings, FORMAT_VERSION, MAX_RESOLUTION, MIN_RESOLUTION, NormalFormat, NormalMixing, Project,
|
||||
|
||||
@@ -0,0 +1,83 @@
|
||||
//! Which polygons a polygon fill box selects.
|
||||
|
||||
use serde::{Deserialize, Serialize};
|
||||
use texturecraft_geom::glam::Vec2;
|
||||
|
||||
/// How a polygon fill box decides whether it selects a polygon
|
||||
#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize, Default)]
|
||||
pub enum FillHitTest {
|
||||
/// Any part of the polygon inside the box or crossing it
|
||||
#[default]
|
||||
Intersection,
|
||||
/// The polygon's center point inside the box
|
||||
ContainedCenter,
|
||||
}
|
||||
|
||||
impl FillHitTest {
|
||||
/// Whether the box from `low` to `high` selects the polygon made of `triangles` (their corners)
|
||||
pub fn selects(self, triangles: &[[Vec2; 3]], low: Vec2, high: Vec2) -> bool {
|
||||
match self {
|
||||
FillHitTest::Intersection => triangles.iter().any(|corners| triangle_overlaps_box(*corners, low, high)),
|
||||
FillHitTest::ContainedCenter => center(triangles).is_some_and(|point| point.cmpge(low).all() && point.cmple(high).all()),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Area-weighted center of the triangles (their corners' mean when they have no area)
|
||||
fn center(triangles: &[[Vec2; 3]]) -> Option<Vec2> {
|
||||
if triangles.is_empty() {
|
||||
return None;
|
||||
}
|
||||
|
||||
// One pass: total area, area-weighted centroids and plain centroids
|
||||
let (total_area, weighted, centroids) = triangles.iter().fold((0.0, Vec2::ZERO, Vec2::ZERO), |(total_area, weighted, centroids), corners| {
|
||||
let area = (corners[1] - corners[0]).perp_dot(corners[2] - corners[0]).abs();
|
||||
let centroid = (corners[0] + corners[1] + corners[2]) / 3.0;
|
||||
(total_area + area, weighted + centroid * area, centroids + centroid)
|
||||
});
|
||||
Some(if total_area > 0.0 { weighted / total_area } else { centroids / triangles.len() as f32 })
|
||||
}
|
||||
|
||||
/// Separating axis test of a triangle against an axis-aligned box
|
||||
fn triangle_overlaps_box(corners: [Vec2; 3], low: Vec2, high: Vec2) -> bool {
|
||||
let triangle_low = corners[0].min(corners[1]).min(corners[2]);
|
||||
let triangle_high = corners[0].max(corners[1]).max(corners[2]);
|
||||
if triangle_high.cmplt(low).any() || triangle_low.cmpgt(high).any() {
|
||||
return false;
|
||||
}
|
||||
|
||||
let box_corners = [low, Vec2::new(high.x, low.y), high, Vec2::new(low.x, high.y)];
|
||||
(0..3).all(|edge| {
|
||||
let axis = (corners[(edge + 1) % 3] - corners[edge]).perp();
|
||||
let span = |points: &[Vec2]| points.iter().fold((f32::MAX, f32::MIN), |(min, max), point| (min.min(axis.dot(*point)), max.max(axis.dot(*point))));
|
||||
let (triangle_min, triangle_max) = span(&corners);
|
||||
let (box_min, box_max) = span(&box_corners);
|
||||
triangle_max >= box_min && box_max >= triangle_min
|
||||
})
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
const TRIANGLE: [Vec2; 3] = [Vec2::new(0.0, 0.0), Vec2::new(4.0, 0.0), Vec2::new(0.0, 4.0)];
|
||||
|
||||
#[test]
|
||||
fn intersection_selects_any_overlap() {
|
||||
assert!(FillHitTest::Intersection.selects(&[TRIANGLE], Vec2::splat(1.0), Vec2::splat(6.0)), "a box cutting the triangle");
|
||||
assert!(!FillHitTest::Intersection.selects(&[TRIANGLE], Vec2::splat(3.0), Vec2::splat(5.0)), "inside the bounds, past the long edge");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn contained_center_selects_only_by_the_center() {
|
||||
assert!(!FillHitTest::ContainedCenter.selects(&[TRIANGLE], Vec2::splat(2.0), Vec2::splat(6.0)), "the center (4/3, 4/3) lies outside");
|
||||
assert!(FillHitTest::ContainedCenter.selects(&[TRIANGLE], Vec2::splat(1.0), Vec2::splat(2.0)));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_polygon_center_weighs_its_triangles_by_area() {
|
||||
let square = [[Vec2::ZERO, Vec2::new(2.0, 0.0), Vec2::new(2.0, 2.0)], [Vec2::ZERO, Vec2::new(2.0, 2.0), Vec2::new(0.0, 2.0)]];
|
||||
assert_eq!(center(&square), Some(Vec2::ONE));
|
||||
assert_eq!(center(&[]), None);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,17 @@
|
||||
//! What one polygon fill target grows to.
|
||||
|
||||
use serde::{Deserialize, Serialize};
|
||||
|
||||
/// Polygon fill granularity: what a clicked triangle or a boxed polygon grows to
|
||||
#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize, Default)]
|
||||
pub enum FillMode {
|
||||
/// The triangle itself
|
||||
#[default]
|
||||
Triangle,
|
||||
/// The source polygon (quad or n-gon) the importer split into triangles
|
||||
Polygon,
|
||||
/// The UV island: triangles sharing edges in UV space
|
||||
UvIsland,
|
||||
/// The connected geometry: triangles sharing edges by position
|
||||
Mesh,
|
||||
}
|
||||
@@ -19,6 +19,20 @@ pub struct FilterDef {
|
||||
pub mask: bool,
|
||||
}
|
||||
|
||||
impl FilterDef {
|
||||
/// Whether it builds a filter effect (levels and material finishes are effect types of their own)
|
||||
pub fn is_filter_effect(&self) -> bool {
|
||||
matches!(build(self.id, &Value::Null), Ok(EffectKind::Filter(_)))
|
||||
}
|
||||
}
|
||||
|
||||
/// The library entries that build filter effects, in shelf order, worked out once
|
||||
pub fn filter_effects() -> &'static [&'static FilterDef] {
|
||||
static FILTER_EFFECTS: std::sync::LazyLock<Vec<&'static FilterDef>> =
|
||||
std::sync::LazyLock::new(|| FILTERS.iter().filter(|def| def.is_filter_effect()).collect());
|
||||
&FILTER_EFFECTS
|
||||
}
|
||||
|
||||
const fn def(id: &'static str, label: &'static str, group: &'static str, mask: bool) -> FilterDef {
|
||||
FilterDef { id, label, group, mask }
|
||||
}
|
||||
|
||||
@@ -2,7 +2,7 @@
|
||||
//! without a screenshot.
|
||||
|
||||
use serde_json::{Value, json};
|
||||
use texturecraft_core::{Effect, EffectKind, Fill, Filter, Layer, LayerKind, NormalFormat, Projection, Source};
|
||||
use texturecraft_core::{Effect, EffectKind, Fill, Filter, Generator, Layer, LayerKind, NormalFormat, Projection, Source};
|
||||
|
||||
use crate::Session;
|
||||
use crate::session::StackTarget;
|
||||
@@ -34,38 +34,45 @@ fn fill_json(f: &Fill) -> Value {
|
||||
}
|
||||
|
||||
/// A mask or content (`content`) effect.
|
||||
fn effect_json(s: &Session, e: &Effect, content: bool) -> Value {
|
||||
let mut ej = json!({ "id": e.id.0, "name": e.name, "kind": e.kind.name(), "visible": e.visible, "blend": e.blend.label(), "opacity": e.opacity });
|
||||
match &e.kind {
|
||||
EffectKind::Generator(g) => {
|
||||
ej["generator"] = json!({ "type": format!("{:?}", g.kind), "level": g.level, "softness": g.softness, "noise": g.noise_amount, "invert": g.invert })
|
||||
}
|
||||
EffectKind::Levels(lv) => ej["levels"] = json!([lv.in_low, lv.in_high, lv.gamma, lv.out_low, lv.out_high]),
|
||||
fn effect_json(session: &Session, effect: &Effect, content: bool) -> Value {
|
||||
let mut out = json!({ "id": effect.id.0, "name": effect.name, "kind": effect.kind.name(), "visible": effect.visible, "blend": effect.blend.label(), "opacity": effect.opacity });
|
||||
let mask_tiles = || session.doc.pixels.masks.get(&effect.id).map_or(0, |image| image.allocated_count());
|
||||
let content_tiles = || session.doc.pixels.layers.iter().filter(|((id, _), _)| *id == effect.id).map(|(_, image)| image.allocated_count()).sum::<usize>();
|
||||
|
||||
match &effect.kind {
|
||||
EffectKind::Generator(generator) => out["generator"] = generator_json(generator),
|
||||
EffectKind::Levels(levels) => out["levels"] = json!([levels.in_low, levels.in_high, levels.gamma, levels.out_low, levels.out_high]),
|
||||
EffectKind::Path(paths) => {
|
||||
ej["paths"] = json!(paths.iter().map(|p| json!({ "points": p.points.len(), "uv": p.uv, "closed": p.closed, "fill": p.fill })).collect::<Vec<_>>());
|
||||
ej["tiles"] = json!(if content {
|
||||
s.doc.pixels.layers.iter().filter(|((id, _), _)| *id == e.id).map(|(_, img)| img.allocated_count()).sum::<usize>()
|
||||
} else {
|
||||
s.doc.pixels.masks.get(&e.id).map(|i| i.allocated_count()).unwrap_or(0)
|
||||
});
|
||||
out["paths"] = json!(
|
||||
paths.iter().map(|path| json!({ "points": path.points.len(), "uv": path.uv, "closed": path.closed, "fill": path.fill })).collect::<Vec<_>>()
|
||||
);
|
||||
out["tiles"] = json!(if content { content_tiles() } else { mask_tiles() });
|
||||
}
|
||||
EffectKind::Paint if content => {
|
||||
ej["tiles"] = json!(s.doc.pixels.layers.iter().filter(|((id, _), _)| *id == e.id).map(|(_, img)| img.allocated_count()).sum::<usize>())
|
||||
}
|
||||
EffectKind::Paint => ej["tiles"] = json!(s.doc.pixels.masks.get(&e.id).map(|i| i.allocated_count()).unwrap_or(0)),
|
||||
EffectKind::Fill { source, .. } => ej["source"] = source_json(source),
|
||||
EffectKind::Material(f) => ej["fill"] = fill_json(f),
|
||||
EffectKind::Filter(f) => {
|
||||
ej["filter"] = json!(f);
|
||||
match f {
|
||||
Filter::Hsl { hue, saturation, lightness } => ej["hsl"] = json!([hue, saturation, lightness]),
|
||||
Filter::Blur { radius } => ej["radius"] = json!(radius),
|
||||
EffectKind::Paint if content => out["tiles"] = json!(content_tiles()),
|
||||
EffectKind::Paint => out["tiles"] = json!(mask_tiles()),
|
||||
EffectKind::Fill { source, .. } => out["source"] = source_json(source),
|
||||
EffectKind::Material(fill) => out["fill"] = fill_json(fill),
|
||||
EffectKind::Filter(filter) => {
|
||||
out["filter"] = json!(filter);
|
||||
match filter {
|
||||
Filter::Hsl { hue, saturation, lightness } => out["hsl"] = json!([hue, saturation, lightness]),
|
||||
Filter::Blur { radius } => out["radius"] = json!(radius),
|
||||
_ => {}
|
||||
}
|
||||
}
|
||||
_ => {}
|
||||
}
|
||||
ej
|
||||
out
|
||||
}
|
||||
|
||||
/// A generator's settings, with its curvature mode and detail size weights when it has them.
|
||||
fn generator_json(generator: &Generator) -> Value {
|
||||
let mut out = json!({ "type": format!("{:?}", generator.kind), "level": generator.level, "softness": generator.softness, "noise": generator.noise_amount, "invert": generator.invert });
|
||||
if let Some(detail) = &generator.detail {
|
||||
out["mode"] = json!(format!("{:?}", detail.mode));
|
||||
out["sizes"] = json!(detail.weights);
|
||||
}
|
||||
out
|
||||
}
|
||||
|
||||
fn layer_json(s: &Session, l: &Layer, depth: usize) -> Value {
|
||||
|
||||
@@ -15,6 +15,8 @@ pub mod commands;
|
||||
pub mod decal_cmds;
|
||||
pub mod effect_clipboard;
|
||||
pub mod file_cmds;
|
||||
pub mod fill_hit_test;
|
||||
pub mod fill_mode;
|
||||
pub mod filter_lib;
|
||||
pub mod inspect;
|
||||
pub mod instance_cmds;
|
||||
@@ -22,15 +24,18 @@ pub mod layer_cmds;
|
||||
pub mod layer_ops;
|
||||
pub mod link_cmds;
|
||||
pub mod mask_cmds;
|
||||
pub mod mask_preview;
|
||||
mod mask_preview_camera;
|
||||
mod mask_preview_pixel;
|
||||
pub mod material_lib;
|
||||
mod material_preview_pixel;
|
||||
pub mod materials;
|
||||
pub mod materialx_cmds;
|
||||
pub mod meshmap_cmds;
|
||||
mod orb_camera;
|
||||
pub mod orb_preview;
|
||||
pub mod painting;
|
||||
pub mod path_tool;
|
||||
mod polygon_fill;
|
||||
mod polygon_fill_drag;
|
||||
// Mesh reimport reads files: native only.
|
||||
#[cfg(not(target_arch = "wasm32"))]
|
||||
mod preserve;
|
||||
@@ -45,14 +50,18 @@ pub mod smart_masks;
|
||||
pub mod template_cmds;
|
||||
pub mod text_cmds;
|
||||
pub mod tool_cmds;
|
||||
mod triangle_partition;
|
||||
mod uv_stroke_state;
|
||||
pub mod uv_tile_cmds;
|
||||
pub mod view_cmds;
|
||||
|
||||
pub use bake::{BakeMesh, BakeMeshes, BakeTask};
|
||||
pub use commands::{CommandSpec, command_specs, execute, find};
|
||||
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, FillMode, Session, SetCache, StackTarget, StencilState, Tool, ToolState, ViewMode};
|
||||
pub use session::{CloneFrom, CloneSource, Document, Session, SetCache, StackTarget, StencilState, Tool, ToolState, ViewMode};
|
||||
pub use set_cmds::{ResizeOutput, ResizeTask};
|
||||
|
||||
pub use texturecraft_compose as compose;
|
||||
|
||||
+147
-55
@@ -2,8 +2,8 @@
|
||||
|
||||
use serde_json::{Value, json};
|
||||
use texturecraft_core::{
|
||||
BlendMode, Channel, CompareOp, Effect, EffectKind, Filter, Generator, GeneratorKind, LayerId, Levels, Mask, MaskBackground, Procedural, ProceduralKind,
|
||||
Project, Source,
|
||||
BlendMode, Channel, CompareOp, CurvatureDetail, CurvatureMode, Effect, EffectKind, Filter, Generator, GeneratorKind, LayerId, Levels, Mask, MaskBackground,
|
||||
Procedural, ProceduralKind, Project, Source,
|
||||
};
|
||||
|
||||
use crate::commands::{CommandSpec, always, bad, blend_param, boolp, channel_param, color_param, f32p, has_layer, layer_param, strp, u64p};
|
||||
@@ -49,7 +49,7 @@ pub fn specs() -> Vec<CommandSpec> {
|
||||
"Add generator",
|
||||
["Layers", "Effects"],
|
||||
None,
|
||||
"{layer?, name?, generator?: edgeWear|dirt|thinAreas|curvature|ambientOcclusion|position|direction, level?, softness?, noise?, invert?}",
|
||||
"{layer?, name?, generator?: edgeWear|dirt|thinAreas|curvature|ambientOcclusion|position|direction, level?, softness?, noise?, invert?, mode?: edges|cavities|both|raw, sizes?: [7 weights 0..1, finest first] (curvature and edgeWear)}",
|
||||
has_layer,
|
||||
add_generator
|
||||
),
|
||||
@@ -94,7 +94,7 @@ pub fn specs() -> Vec<CommandSpec> {
|
||||
"Edit effect",
|
||||
[],
|
||||
None,
|
||||
"{effect, visible?, blend?, opacity?, name?, level?, softness?, noise?, noiseScale?, invert?, value?, anchor?, anchorChannel?, inLow?, inHigh?, gamma?, outLow?, outHigh?, tolerance?, filter parameters (see effect.add.filter)}",
|
||||
"{effect, visible?, blend?, opacity?, name?, filter?: id from filter.list (a filter effect only: swaps its type, keeping position, blend and opacity; its current id edits it in place), level?, softness?, noise?, noiseScale?, invert?, mode?, sizes?, value?, anchor?, anchorChannel?, inLow?, inHigh?, gamma?, outLow?, outHigh?, tolerance?, filter parameters (see effect.add.filter)}",
|
||||
has_layer,
|
||||
set
|
||||
),
|
||||
@@ -314,39 +314,76 @@ fn add_fill(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
push_effect(s, p, EffectKind::Fill { source, projection }, blend)
|
||||
}
|
||||
|
||||
fn generator_from(p: &Value, g: &mut Generator) {
|
||||
if let Some(v) = f32p(p, "level") {
|
||||
g.level = v.clamp(0.0, 1.0);
|
||||
/// Apply `params` to `generator`, using `command` in errors
|
||||
fn generator_from(command: &str, params: &Value, generator: &mut Generator) -> Result<()> {
|
||||
if let Some(level) = f32p(params, "level") {
|
||||
generator.level = level.clamp(0.0, 1.0);
|
||||
}
|
||||
if let Some(v) = f32p(p, "softness") {
|
||||
g.softness = v.clamp(0.0, 1.0);
|
||||
if let Some(softness) = f32p(params, "softness") {
|
||||
generator.softness = softness.clamp(0.0, 1.0);
|
||||
}
|
||||
if let Some(v) = f32p(p, "noise") {
|
||||
g.noise_amount = v.clamp(0.0, 2.0);
|
||||
if let Some(noise) = f32p(params, "noise") {
|
||||
generator.noise_amount = noise.clamp(0.0, 2.0);
|
||||
}
|
||||
if let Some(v) = f32p(p, "noiseScale") {
|
||||
g.noise_scale = v.clamp(0.01, 1000.0);
|
||||
if let Some(noise_scale) = f32p(params, "noiseScale") {
|
||||
generator.noise_scale = noise_scale.clamp(0.01, 1000.0);
|
||||
}
|
||||
if let Some(v) = u64p(p, "seed") {
|
||||
g.seed = v as u32;
|
||||
if let Some(seed) = u64p(params, "seed") {
|
||||
generator.seed = seed as u32;
|
||||
}
|
||||
if let Some(v) = boolp(p, "invert") {
|
||||
g.invert = v;
|
||||
if let Some(invert) = boolp(params, "invert") {
|
||||
generator.invert = invert;
|
||||
}
|
||||
if let Some(d) = color_param(p, "direction") {
|
||||
g.direction = d;
|
||||
if let Some(direction) = color_param(params, "direction") {
|
||||
generator.direction = direction;
|
||||
}
|
||||
|
||||
// A mode or sizes also give a curvature generator saved before detail sizes its detail
|
||||
let mode = params
|
||||
.get("mode")
|
||||
.map(|value| {
|
||||
let name = value.as_str().ok_or_else(|| bad(command, "`mode` must be a string"))?;
|
||||
CurvatureMode::parse(name).ok_or_else(|| bad(command, format!("unknown curvature mode `{name}`")))
|
||||
})
|
||||
.transpose()?;
|
||||
let weights = params.get("sizes").map(|value| size_weights(command, value)).transpose()?;
|
||||
if mode.is_none() && weights.is_none() {
|
||||
return Ok(());
|
||||
}
|
||||
if !matches!(generator.kind, GeneratorKind::Curvature | GeneratorKind::EdgeWear) {
|
||||
return Err(bad(command, "only curvature and edge wear generators have a mode and detail sizes"));
|
||||
}
|
||||
|
||||
let detail = generator.detail.get_or_insert_with(CurvatureDetail::default);
|
||||
if let Some(mode) = mode {
|
||||
detail.mode = mode;
|
||||
}
|
||||
if let Some(weights) = weights {
|
||||
detail.weights = weights;
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn add_generator(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
let kind = match strp(p, "generator") {
|
||||
Some(k) => GeneratorKind::parse(k).ok_or_else(|| bad("effect.add.generator", format!("unknown generator `{k}`")))?,
|
||||
/// Read one weight (0..1) per size of [`CurvatureDetail::SIZES`], finest first
|
||||
fn size_weights(command: &str, value: &Value) -> Result<[f32; CurvatureDetail::SIZES.len()]> {
|
||||
let invalid = || bad(command, format!("`sizes` takes {} numbers, finest first", CurvatureDetail::SIZES.len()));
|
||||
let items = value.as_array().filter(|items| items.len() == CurvatureDetail::SIZES.len()).ok_or_else(invalid)?;
|
||||
let mut weights = [0.0; CurvatureDetail::SIZES.len()];
|
||||
for (weight, item) in weights.iter_mut().zip(items) {
|
||||
*weight = item.as_f64().ok_or_else(invalid)?.clamp(0.0, 1.0) as f32;
|
||||
}
|
||||
Ok(weights)
|
||||
}
|
||||
|
||||
fn add_generator(session: &mut Session, params: &Value) -> Result<Value> {
|
||||
let kind = match strp(params, "generator") {
|
||||
Some(name) => GeneratorKind::parse(name).ok_or_else(|| bad("effect.add.generator", format!("unknown generator `{name}`")))?,
|
||||
None => GeneratorKind::EdgeWear,
|
||||
};
|
||||
let mut g = Generator::new(kind);
|
||||
generator_from(p, &mut g);
|
||||
let blend = blend_param("effect.add.generator", p, "blend")?.unwrap_or(BlendMode::Normal);
|
||||
push_effect(s, p, EffectKind::Generator(g), blend)
|
||||
let mut generator = Generator::new(kind);
|
||||
generator_from("effect.add.generator", params, &mut generator)?;
|
||||
let blend = blend_param("effect.add.generator", params, "blend")?.unwrap_or(BlendMode::Normal);
|
||||
push_effect(session, params, EffectKind::Generator(generator), blend)
|
||||
}
|
||||
|
||||
pub(crate) fn levels_from(p: &Value, l: &mut Levels) {
|
||||
@@ -413,55 +450,78 @@ fn histogram(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
Ok(if content { json!({"target": "content", "channel": channel.id(), "bins": counts}) } else { json!({"target": "mask", "bins": counts}) })
|
||||
}
|
||||
|
||||
fn set(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
let eid = effect_id(s, p, "effect.set")?;
|
||||
let blend = blend_param("effect.set", p, "blend")?;
|
||||
// A fill reading an anchor: `anchor` picks the anchor point, `anchorChannel` alone
|
||||
// re-targets the current one.
|
||||
let anchor = match s.doc.project.effect(eid) {
|
||||
/// Edit visibility, blending, name, effect parameters, or a filter's type
|
||||
fn set(session: &mut Session, params: &Value) -> Result<Value> {
|
||||
const CMD: &str = "effect.set";
|
||||
let effect = effect_id(session, params, CMD)?;
|
||||
let blend = blend_param(CMD, params, "blend")?;
|
||||
|
||||
// `anchor` picks a fill's anchor point, `anchorChannel` alone re-targets the current one
|
||||
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),
|
||||
_ => (None, Channel::Height),
|
||||
};
|
||||
let channel_param = channel_param("effect.set", p, "anchorChannel")?;
|
||||
match u64p(p, "anchor").map(LayerId).or(current.filter(|_| channel_param.is_some())) {
|
||||
Some(a) => Some(anchor_source(s, "effect.set", owner, a, channel_param.unwrap_or(channel))?),
|
||||
let channel_param = channel_param(CMD, params, "anchorChannel")?;
|
||||
match u64p(params, "anchor").map(LayerId).or(current.filter(|_| channel_param.is_some())) {
|
||||
Some(anchor) => Some(anchor_source(session, CMD, owner, anchor, channel_param.unwrap_or(channel))?),
|
||||
None => None,
|
||||
}
|
||||
}
|
||||
_ => None,
|
||||
};
|
||||
s.edit("Edit effect", |s| {
|
||||
let e = s.doc.project.effect_mut(eid).ok_or_else(|| bad("effect.set", format!("no effect {}", eid.0)))?;
|
||||
if let Some(v) = boolp(p, "visible") {
|
||||
e.visible = v;
|
||||
|
||||
// Naming the filter the effect already is edits its parameters like a plain effect.set
|
||||
let swapped = match strp(params, "filter") {
|
||||
Some(filter) if crate::filter_lib::find(filter).is_some_and(|def| current_filter_id(session, effect) == Some(def.id)) => None,
|
||||
Some(filter) => Some(swapped_filter(session, effect, filter, params)?),
|
||||
None => None,
|
||||
};
|
||||
let swaps_filter = swapped.is_some();
|
||||
|
||||
session.edit("Edit effect", |session| {
|
||||
let edited = session.doc.project.effect_mut(effect).ok_or_else(|| bad(CMD, format!("no effect {}", effect.0)))?;
|
||||
if let Some((kind, label)) = swapped {
|
||||
if let EffectKind::Filter(old) = &edited.kind
|
||||
&& edited.name == old.label()
|
||||
{
|
||||
edited.name = label.to_string();
|
||||
}
|
||||
edited.kind = kind;
|
||||
}
|
||||
if let Some(b) = blend {
|
||||
e.blend = b;
|
||||
|
||||
if let Some(visible) = boolp(params, "visible") {
|
||||
edited.visible = visible;
|
||||
}
|
||||
if let Some(o) = f32p(p, "opacity") {
|
||||
e.opacity = o.clamp(0.0, 1.0);
|
||||
if let Some(blend) = blend {
|
||||
edited.blend = blend;
|
||||
}
|
||||
if let Some(n) = name_param(p) {
|
||||
e.name = n.to_string();
|
||||
if let Some(opacity) = f32p(params, "opacity") {
|
||||
edited.opacity = opacity.clamp(0.0, 1.0);
|
||||
}
|
||||
match &mut e.kind {
|
||||
EffectKind::Generator(g) => generator_from(p, g),
|
||||
EffectKind::Levels(l) => levels_from(p, l),
|
||||
EffectKind::Filter(f) => crate::filter_lib::apply(p, f, "effect.set")?,
|
||||
if let Some(name) = name_param(params) {
|
||||
edited.name = name.to_string();
|
||||
}
|
||||
|
||||
match &mut edited.kind {
|
||||
EffectKind::Generator(generator) => generator_from(CMD, params, generator)?,
|
||||
EffectKind::Levels(levels) => levels_from(params, levels),
|
||||
// The swapped filter was built with the parameters already
|
||||
EffectKind::Filter(_) if swaps_filter => {}
|
||||
EffectKind::Filter(filter) => crate::filter_lib::apply(params, filter, CMD)?,
|
||||
EffectKind::Fill { source, .. } => {
|
||||
if let Some(a) = anchor {
|
||||
*source = a;
|
||||
} else if let Some(x) = f32p(p, "value")
|
||||
if let Some(anchor) = anchor {
|
||||
*source = anchor;
|
||||
} else if let Some(value) = f32p(params, "value")
|
||||
&& matches!(source, Source::Uniform(_) | Source::Anchor { .. })
|
||||
{
|
||||
*source = Source::Uniform([x.clamp(0.0, 1.0); 3]);
|
||||
*source = Source::Uniform([value.clamp(0.0, 1.0); 3]);
|
||||
}
|
||||
}
|
||||
EffectKind::ColorSelection { tolerance, .. } | EffectKind::Compare { tolerance, .. } => {
|
||||
if let Some(x) = f32p(p, "tolerance") {
|
||||
*tolerance = x.clamp(0.0, 1.0);
|
||||
if let Some(value) = f32p(params, "tolerance") {
|
||||
*tolerance = value.clamp(0.0, 1.0);
|
||||
}
|
||||
}
|
||||
_ => {}
|
||||
@@ -471,6 +531,38 @@ fn set(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
Ok(Value::Null)
|
||||
}
|
||||
|
||||
/// The library id of the filter effect `effect` is, if it is one
|
||||
fn current_filter_id(s: &Session, effect: LayerId) -> Option<&'static str> {
|
||||
match &s.doc.project.effect(effect)?.1.kind {
|
||||
EffectKind::Filter(filter) => crate::filter_lib::find(filter.label()).map(|def| def.id),
|
||||
_ => None,
|
||||
}
|
||||
}
|
||||
|
||||
/// Filter `id` built with `p` and its label, to replace filter effect `effect`
|
||||
fn swapped_filter(s: &Session, effect: LayerId, id: &str, p: &Value) -> Result<(EffectKind, &'static str)> {
|
||||
const CMD: &str = "effect.set";
|
||||
let (owner, current) = s.doc.project.effect(effect).ok_or_else(|| bad(CMD, format!("no effect {}", effect.0)))?;
|
||||
if !matches!(current.kind, EffectKind::Filter(_)) {
|
||||
return Err(bad(CMD, format!("`filter` changes filter effects only, not {}", current.kind.name().to_ascii_lowercase())));
|
||||
}
|
||||
|
||||
let def = crate::filter_lib::find(id).ok_or_else(|| bad(CMD, format!("unknown filter `{id}` (see filter.list)")))?;
|
||||
let mut kind = crate::filter_lib::build(def.id, &Value::Null)?;
|
||||
let EffectKind::Filter(filter) = &mut kind else {
|
||||
return Err(bad(CMD, format!("{} is its own effect type: add it with effect.add.filter", def.label)));
|
||||
};
|
||||
|
||||
let mask = s.doc.project.layer(owner)?.mask.as_ref();
|
||||
let on_mask = mask.is_some_and(|mask| mask.effects.iter().any(|masked| masked.id == effect));
|
||||
if on_mask && !def.mask {
|
||||
return Err(bad(CMD, format!("{} goes on layer content, not on masks", def.label)));
|
||||
}
|
||||
|
||||
crate::filter_lib::apply(p, filter, CMD)?;
|
||||
Ok((kind, def.label))
|
||||
}
|
||||
|
||||
/// The stack (a mask's or a layer's content effects) holding effect `eid`, and its position there.
|
||||
fn stack_of(project: &mut Project, eid: LayerId) -> Option<(&mut Vec<Effect>, usize)> {
|
||||
project.layers.values_mut().find_map(|l| {
|
||||
|
||||
@@ -1,161 +0,0 @@
|
||||
//! Smart mask previews share one baked [`primitives::preview_orb`]
|
||||
//! Presets use `mask.smart.apply` and the compositor, matching document masks
|
||||
|
||||
use serde_json::json;
|
||||
use texturecraft_core::{BakeResolution, BakedMap, CurvatureMethod, LayerId};
|
||||
use texturecraft_geom::glam::Vec3;
|
||||
use texturecraft_geom::primitives;
|
||||
|
||||
use crate::mask_preview_camera::MaskPreviewCamera;
|
||||
pub use crate::mask_preview_pixel::MaskPreviewPixel;
|
||||
use crate::{EngineError, Result, Session};
|
||||
|
||||
/// Bake resolution in texels; 256 loses the thin edge lines
|
||||
const TEXTURE_PX: u32 = 512;
|
||||
/// Camera rays per preview pixel along each axis (anti-aliased outline)
|
||||
const SUPERSAMPLE: usize = 2;
|
||||
/// Bound camera samples and output allocations for shelf previews
|
||||
pub const MAX_PREVIEW_SIZE_PX: usize = 512;
|
||||
/// AO and thickness rays per texel; thumbnail detail needs fewer than the default
|
||||
const OCCLUSION_RAYS: u32 = 12;
|
||||
/// Curvature rays per texel; thumbnail detail needs fewer than the default
|
||||
const CURVATURE_RAYS: u32 = 12;
|
||||
/// Radius relative to the bounding box; isolates panel edges from the round body
|
||||
const CURVATURE_RADIUS: f32 = 0.005;
|
||||
/// The mesh maps the smart mask generators read
|
||||
const MAPS: [BakedMap; 3] = [BakedMap::Curvature, BakedMap::AmbientOcclusion, BakedMap::Thickness];
|
||||
/// Keep camera views for the thumbnail and hover preview sizes
|
||||
const CAMERAS_KEPT: usize = 2;
|
||||
|
||||
/// The baked preview shape and, per preview size, what its camera sees
|
||||
pub struct MaskPreview {
|
||||
session: Session,
|
||||
layer: LayerId,
|
||||
/// Cached camera views, least recently used first
|
||||
cameras: Vec<MaskPreviewCamera>,
|
||||
}
|
||||
|
||||
impl MaskPreview {
|
||||
/// Bake the preview shape once (previews of any size reuse it)
|
||||
pub fn new() -> Result<MaskPreview> {
|
||||
let mut session = Session::new_project("Mask preview", primitives::preview_orb(), "builtin:preview_orb", None, TEXTURE_PX)?;
|
||||
let set = session.doc.project.texture_set_mut(0)?;
|
||||
set.bake.common.resolution = BakeResolution::from_pixels(TEXTURE_PX).ok_or_else(|| EngineError::Other("invalid bake resolution".into()))?;
|
||||
set.bake.high_poly.use_low_as_high = true;
|
||||
set.bake.maps.curvature.parameters.method = CurvatureMethod::Mesh;
|
||||
set.bake.maps.curvature.parameters.mesh.sampling_radius = CURVATURE_RADIUS;
|
||||
set.bake.maps.curvature.parameters.mesh.rays = CURVATURE_RAYS;
|
||||
set.bake.maps.ao.parameters.rays.rays = OCCLUSION_RAYS;
|
||||
set.bake.maps.thickness.parameters.rays.rays = OCCLUSION_RAYS;
|
||||
for map in BakedMap::ALL {
|
||||
set.bake.maps.set_enabled(map, MAPS.contains(&map));
|
||||
}
|
||||
let layer = *set.stack.first().ok_or_else(|| EngineError::Other("the preview has no layer".into()))?;
|
||||
session.bake_now(0, false)?;
|
||||
|
||||
Ok(MaskPreview { session, layer, cameras: Vec::new() })
|
||||
}
|
||||
|
||||
/// Row-major `size²` pixels, with None outside the shape
|
||||
/// Returns None for unknown masks or sizes outside 1..=[`MAX_PREVIEW_SIZE_PX`]
|
||||
pub fn render(&mut self, id: &str, size: usize) -> Option<Vec<Option<MaskPreviewPixel>>> {
|
||||
if !(1..=MAX_PREVIEW_SIZE_PX).contains(&size) {
|
||||
return None;
|
||||
}
|
||||
|
||||
crate::execute(&mut self.session, "mask.smart.apply", &json!({ "name": id, "layer": self.layer.0 })).ok()?;
|
||||
// Previews need no undo history; retaining snapshots grows memory across presets
|
||||
self.session.undo.clear();
|
||||
|
||||
let camera = camera_for(&mut self.cameras, &self.session, size)?;
|
||||
let values = self.session.mask_at(self.layer, &camera.texels)?;
|
||||
|
||||
let sub_pixels = (SUPERSAMPLE * SUPERSAMPLE) as f32;
|
||||
let pixels = (0..size * size)
|
||||
.map(|i| {
|
||||
let (x, y) = (i % size, i / size);
|
||||
let (mut mask, mut normal, mut hits) = (0.0, Vec3::ZERO, 0.0);
|
||||
for sy in 0..SUPERSAMPLE {
|
||||
for sx in 0..SUPERSAMPLE {
|
||||
let ray = (y * SUPERSAMPLE + sy) * camera.rays_per_side + x * SUPERSAMPLE + sx;
|
||||
let Some(&Some((texel, n))) = camera.samples.get(ray) else { continue };
|
||||
|
||||
mask += values.get(texel).copied().unwrap_or(0.0);
|
||||
normal += n;
|
||||
hits += 1.0;
|
||||
}
|
||||
}
|
||||
(hits > 0.0).then(|| MaskPreviewPixel { mask: mask / hits, normal: normal.normalize_or_zero(), coverage: hits / sub_pixels })
|
||||
})
|
||||
.collect();
|
||||
Some(pixels)
|
||||
}
|
||||
}
|
||||
|
||||
/// Cache one camera per preview size, evicting the least recently used view
|
||||
fn camera_for<'a>(cameras: &'a mut Vec<MaskPreviewCamera>, session: &Session, size: usize) -> Option<&'a MaskPreviewCamera> {
|
||||
let rays_per_side = size * SUPERSAMPLE;
|
||||
let camera = match cameras.iter().position(|c| c.rays_per_side == rays_per_side) {
|
||||
Some(i) => cameras.remove(i),
|
||||
None => MaskPreviewCamera::new(session, TEXTURE_PX, rays_per_side),
|
||||
};
|
||||
if cameras.len() >= CAMERAS_KEPT {
|
||||
cameras.remove(0);
|
||||
}
|
||||
|
||||
cameras.push(camera);
|
||||
cameras.last()
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
/// Mean absolute difference of the masks of two previews over the pixels both see
|
||||
fn difference(a: &[Option<MaskPreviewPixel>], b: &[Option<MaskPreviewPixel>]) -> f32 {
|
||||
let pairs: Vec<(f32, f32)> = a.iter().zip(b).filter_map(|(a, b)| Some((a.as_ref()?.mask, b.as_ref()?.mask))).collect();
|
||||
pairs.iter().map(|(a, b)| (a - b).abs()).sum::<f32>() / pairs.len().max(1) as f32
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn invalid_preview_sizes_are_rejected_before_changing_the_shape() {
|
||||
let session = Session::new_project("Mask preview", primitives::cube(2.0), "builtin:cube", None, 128).unwrap();
|
||||
let layer = session.doc.project.texture_set(0).unwrap().stack[0];
|
||||
let mut preview = MaskPreview { session, layer, cameras: Vec::new() };
|
||||
for size in [0, MAX_PREVIEW_SIZE_PX + 1, usize::MAX / 2 + 1, usize::MAX] {
|
||||
assert!(preview.render("edges_sharp", size).is_none(), "size {size} should be rejected before rendering");
|
||||
assert!(preview.cameras.is_empty(), "invalid sizes must not allocate a camera");
|
||||
assert!(preview.session.doc.project.layer(layer).unwrap().mask.is_none(), "invalid sizes must not apply a mask");
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn smart_mask_previews_are_in_range_tell_edges_from_cavities_and_render_at_any_size() {
|
||||
let size = 24;
|
||||
let mut preview = MaskPreview::new().unwrap();
|
||||
for sm in crate::smart_masks::SMART_MASKS {
|
||||
let px = preview.render(sm.id, size).unwrap_or_else(|| panic!("{}", sm.id));
|
||||
assert_eq!(px.len(), size * size, "{}", sm.id);
|
||||
assert!(px[0].is_none(), "{}: the corners are outside the shape", sm.id);
|
||||
let seen: Vec<&MaskPreviewPixel> = px.iter().flatten().collect();
|
||||
assert!(seen.len() > size * size / 3, "{}: the shape fills the frame", sm.id);
|
||||
for p in seen {
|
||||
assert!((0.0..=1.0).contains(&p.mask) && (0.0..=1.0).contains(&p.coverage) && p.coverage > 0.0, "{}: {p:?}", sm.id);
|
||||
assert!(p.normal.is_finite(), "{}: {p:?}", sm.id);
|
||||
}
|
||||
}
|
||||
|
||||
let (edges, cavities) = (preview.render("edges_sharp", size).unwrap(), preview.render("dirt_cavities", size).unwrap());
|
||||
let shows = |px: &[Option<MaskPreviewPixel>]| px.iter().flatten().any(|p| p.mask > 0.5);
|
||||
assert!(shows(&edges) && shows(&cavities), "both masks find something on the shape");
|
||||
assert!(difference(&edges, &cavities) > 0.05, "edges and cavities differ: {}", difference(&edges, &cavities));
|
||||
assert!(preview.render("nope", size).is_none());
|
||||
|
||||
let big = preview.render("edges_sharp", size * 3).unwrap();
|
||||
let mean = |px: &[Option<MaskPreviewPixel>]| px.iter().flatten().map(|p| p.mask).sum::<f32>() / px.iter().flatten().count().max(1) as f32;
|
||||
assert_eq!(big.len(), size * size * 9);
|
||||
assert!((mean(&big) - mean(&edges)).abs() < 0.05, "{} vs {}", mean(&big), mean(&edges));
|
||||
preview.render("edges_sharp", size * 2).unwrap();
|
||||
assert_eq!(preview.cameras.len(), CAMERAS_KEPT, "only the most recent sizes keep their camera");
|
||||
}
|
||||
}
|
||||
@@ -1,4 +1,4 @@
|
||||
//! One pixel of a smart mask preview (see [`crate::mask_preview::MaskPreview`]).
|
||||
//! One pixel of a smart mask preview (see [`crate::orb_preview::OrbPreview::mask`])
|
||||
|
||||
use texturecraft_geom::glam::Vec3;
|
||||
|
||||
|
||||
@@ -0,0 +1,16 @@
|
||||
//! One pixel of a smart material preview (see [`crate::orb_preview::OrbPreview::material`])
|
||||
|
||||
use texturecraft_geom::glam::Vec3;
|
||||
|
||||
use crate::preview::Sample;
|
||||
|
||||
/// The material values seen at a preview pixel, with what a display needs to light the shape
|
||||
#[derive(Clone, Copy, Debug, PartialEq)]
|
||||
pub struct MaterialPreviewPixel {
|
||||
/// Linear material values, averaged over the pixel
|
||||
pub sample: Sample,
|
||||
/// Surface normal in view space (+X right, +Y up, +Z towards the viewer)
|
||||
pub normal: Vec3,
|
||||
/// Fraction of the pixel the shape covers (0..=1, anti-aliased outline)
|
||||
pub coverage: f32,
|
||||
}
|
||||
@@ -1,4 +1,4 @@
|
||||
//! Cached camera rays for one smart mask preview size
|
||||
//! Cached camera rays for one preview orb size
|
||||
|
||||
use std::collections::HashMap;
|
||||
|
||||
@@ -11,11 +11,11 @@ use crate::Session;
|
||||
const CAMERA_PITCH_DEG: f32 = 35.0;
|
||||
const CAMERA_YAW_DEG: f32 = -34.4;
|
||||
|
||||
/// Index into [`MaskPreviewCamera::texels`] and view-space normal; None on a miss
|
||||
/// Index into [`OrbCamera::texels`] and view-space normal; None on a miss
|
||||
pub(crate) type CameraSample = Option<(usize, Vec3)>;
|
||||
|
||||
/// What each ray of a square orthographic view of the preview shape sees
|
||||
pub(crate) struct MaskPreviewCamera {
|
||||
/// What each ray of a square orthographic view of the orb sees
|
||||
pub(crate) struct OrbCamera {
|
||||
/// Rays along each side of the view
|
||||
pub rays_per_side: usize,
|
||||
/// The texels (x, y) the camera sees, each once
|
||||
@@ -24,12 +24,12 @@ pub(crate) struct MaskPreviewCamera {
|
||||
pub samples: Vec<CameraSample>,
|
||||
}
|
||||
|
||||
impl MaskPreviewCamera {
|
||||
impl OrbCamera {
|
||||
/// Trace a square orthographic view onto a `texture_px²` texture
|
||||
pub fn new(session: &Session, texture_px: u32, rays_per_side: usize) -> MaskPreviewCamera {
|
||||
let (lo, hi) = session.mesh.bounds();
|
||||
let center = (lo + hi) * 0.5;
|
||||
let radius = session.mesh.positions.iter().map(|p| p.distance(center)).fold(0.0f32, f32::max);
|
||||
pub fn new(session: &Session, texture_px: u32, rays_per_side: usize) -> OrbCamera {
|
||||
let (min, max) = session.mesh.bounds();
|
||||
let center = (min + max) * 0.5;
|
||||
let radius = session.mesh.positions.iter().map(|position| position.distance(center)).fold(0.0f32, f32::max);
|
||||
let pitch = CAMERA_PITCH_DEG.to_radians();
|
||||
let turn = Quat::from_rotation_y(CAMERA_YAW_DEG.to_radians());
|
||||
let forward = turn * Vec3::new(0.0, -pitch.sin(), -pitch.cos());
|
||||
@@ -40,9 +40,9 @@ impl MaskPreviewCamera {
|
||||
let mut texels = Vec::new();
|
||||
let mut index_of = HashMap::new();
|
||||
let samples = (0..rays_per_side * rays_per_side)
|
||||
.map(|i| {
|
||||
.map(|ray| {
|
||||
let side = rays_per_side as f32;
|
||||
let ndc = Vec2::new(((i % rays_per_side) as f32 + 0.5) / side * 2.0 - 1.0, 1.0 - ((i / rays_per_side) as f32 + 0.5) / side * 2.0);
|
||||
let ndc = Vec2::new(((ray % rays_per_side) as f32 + 0.5) / side * 2.0 - 1.0, 1.0 - ((ray / rays_per_side) as f32 + 0.5) / side * 2.0);
|
||||
// Start well outside the shape so every ray enters it from the front
|
||||
let origin = center + (right * ndc.x + up * ndc.y) * radius - forward * radius * 4.0;
|
||||
let hit = session.bvh.closest(origin, forward, radius * 8.0)?;
|
||||
@@ -52,10 +52,12 @@ impl MaskPreviewCamera {
|
||||
texels.push(texel);
|
||||
texels.len() - 1
|
||||
});
|
||||
let n = surface.nrm;
|
||||
Some((index, Vec3::new(n.dot(right), n.dot(up), -n.dot(forward))))
|
||||
|
||||
let normal = surface.nrm;
|
||||
Some((index, Vec3::new(normal.dot(right), normal.dot(up), -normal.dot(forward))))
|
||||
})
|
||||
.collect();
|
||||
MaskPreviewCamera { rays_per_side, texels, samples }
|
||||
|
||||
OrbCamera { rays_per_side, texels, samples }
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,297 @@
|
||||
//! Smart mask and smart material previews share one baked [`primitives::preview_orb`]
|
||||
//! Presets use `mask.smart.apply`, materials use [`materials::apply`], both read back from the compositor
|
||||
|
||||
use std::collections::{BTreeMap, BTreeSet};
|
||||
|
||||
use serde_json::json;
|
||||
use texturecraft_core::{BakeResolution, BakedMap, Channel, CurvatureMethod, LayerId};
|
||||
use texturecraft_geom::glam::Vec3;
|
||||
use texturecraft_geom::primitives;
|
||||
use texturecraft_texel::TILE;
|
||||
|
||||
pub use crate::mask_preview_pixel::MaskPreviewPixel;
|
||||
pub use crate::material_preview_pixel::MaterialPreviewPixel;
|
||||
use crate::orb_camera::OrbCamera;
|
||||
use crate::preview::Sample;
|
||||
use crate::session::Document;
|
||||
use crate::{EngineError, Result, Session, materials};
|
||||
|
||||
/// Bake resolution in texels; 256 loses the thin edge lines
|
||||
const TEXTURE_PX: u32 = 512;
|
||||
/// Camera rays per preview pixel along each axis (anti-aliased outline)
|
||||
const SUPERSAMPLE: usize = 2;
|
||||
/// Bound camera samples and output allocations for shelf previews
|
||||
pub const MAX_PREVIEW_SIZE_PX: usize = 512;
|
||||
/// AO and thickness rays per texel; thumbnail detail needs fewer than the default
|
||||
const OCCLUSION_RAYS: u32 = 12;
|
||||
/// Curvature rays per texel; thumbnail detail needs fewer than the default
|
||||
const CURVATURE_RAYS: u32 = 12;
|
||||
/// Radius relative to the bounding box; isolates panel edges from the round body
|
||||
const CURVATURE_RADIUS: f32 = 0.005;
|
||||
/// The mesh maps the smart mask generators read; smart materials build on the same presets
|
||||
const MAPS: [BakedMap; 3] = [BakedMap::Curvature, BakedMap::AmbientOcclusion, BakedMap::Thickness];
|
||||
/// Keep camera views for the thumbnail and hover preview sizes
|
||||
const CAMERAS_KEPT: usize = 2;
|
||||
/// The channels a material preview shows, in [`Sample`] order
|
||||
const MATERIAL_CHANNELS: [Channel; 4] = [Channel::BaseColor, Channel::Metallic, Channel::Roughness, Channel::Height];
|
||||
/// The orb's only texture set
|
||||
const SET: usize = 0;
|
||||
|
||||
/// The baked orb and, per preview size, what its camera sees
|
||||
pub struct OrbPreview {
|
||||
session: Session,
|
||||
/// The layer smart masks are applied to
|
||||
layer: LayerId,
|
||||
/// The baked document and selection, restored before each material
|
||||
bare: (Document, BTreeMap<usize, LayerId>),
|
||||
/// Cached camera views, least recently used first
|
||||
cameras: Vec<OrbCamera>,
|
||||
}
|
||||
|
||||
impl OrbPreview {
|
||||
/// Bake the orb once (previews of any size reuse it)
|
||||
pub fn new() -> Result<OrbPreview> {
|
||||
let mut session = Session::new_project("Orb preview", primitives::preview_orb(), "builtin:preview_orb", None, TEXTURE_PX)?;
|
||||
let set = session.doc.project.texture_set_mut(SET)?;
|
||||
set.bake.common.resolution = BakeResolution::from_pixels(TEXTURE_PX).ok_or_else(|| EngineError::Other("invalid bake resolution".into()))?;
|
||||
set.bake.high_poly.use_low_as_high = true;
|
||||
set.bake.maps.curvature.parameters.method = CurvatureMethod::Mesh;
|
||||
set.bake.maps.curvature.parameters.mesh.sampling_radius = CURVATURE_RADIUS;
|
||||
set.bake.maps.curvature.parameters.mesh.rays = CURVATURE_RAYS;
|
||||
set.bake.maps.ao.parameters.rays.rays = OCCLUSION_RAYS;
|
||||
set.bake.maps.thickness.parameters.rays.rays = OCCLUSION_RAYS;
|
||||
for map in BakedMap::ALL {
|
||||
set.bake.maps.set_enabled(map, MAPS.contains(&map));
|
||||
}
|
||||
let layer = *set.stack.first().ok_or_else(|| EngineError::Other("the preview has no layer".into()))?;
|
||||
session.bake_now(SET, false)?;
|
||||
|
||||
let bare = (session.doc.clone(), session.selected.clone());
|
||||
Ok(OrbPreview { session, layer, bare, cameras: Vec::new() })
|
||||
}
|
||||
|
||||
/// Row-major `size²` pixels of smart mask `id`, with None outside the shape
|
||||
/// Returns None for unknown masks or sizes outside 1..=[`MAX_PREVIEW_SIZE_PX`]
|
||||
pub fn mask(&mut self, id: &str, size: usize) -> Option<Vec<Option<MaskPreviewPixel>>> {
|
||||
if !valid_size(size) {
|
||||
return None;
|
||||
}
|
||||
|
||||
crate::execute(&mut self.session, "mask.smart.apply", &json!({ "name": id, "layer": self.layer.0 })).ok()?;
|
||||
// Previews need no undo history; retaining snapshots grows memory across presets
|
||||
self.session.undo.clear();
|
||||
|
||||
let camera = camera_for(&mut self.cameras, &self.session, size)?;
|
||||
let values = self.session.mask_at(self.layer, &camera.texels)?;
|
||||
|
||||
let sub_pixels = (SUPERSAMPLE * SUPERSAMPLE) as f32;
|
||||
let pixels = (0..size * size)
|
||||
.map(|pixel| {
|
||||
let (mut mask_sum, mut normal_sum, mut hits) = (0.0, Vec3::ZERO, 0.0);
|
||||
for (texel, normal) in pixel_hits(camera, size, pixel) {
|
||||
mask_sum += values.get(texel).copied().unwrap_or(0.0);
|
||||
normal_sum += normal;
|
||||
hits += 1.0;
|
||||
}
|
||||
|
||||
(hits > 0.0).then(|| MaskPreviewPixel { mask: mask_sum / hits, normal: normal_sum.normalize_or_zero(), coverage: hits / sub_pixels })
|
||||
})
|
||||
.collect();
|
||||
Some(pixels)
|
||||
}
|
||||
|
||||
/// Row-major `size²` pixels of built-in material `id`, with None outside the shape
|
||||
/// Returns None for unknown materials or sizes outside 1..=[`MAX_PREVIEW_SIZE_PX`]
|
||||
pub fn material(&mut self, id: &str, size: usize) -> Option<Vec<Option<MaterialPreviewPixel>>> {
|
||||
if !valid_size(size) {
|
||||
return None;
|
||||
}
|
||||
|
||||
// Each material goes on the bare shape, not over the previous one
|
||||
(self.session.doc, self.session.selected) = self.bare.clone();
|
||||
let applied = materials::apply(&mut self.session, id);
|
||||
// Previews need no undo history; retaining snapshots grows memory across materials
|
||||
self.session.undo.clear();
|
||||
applied.ok()?;
|
||||
|
||||
let camera = camera_for(&mut self.cameras, &self.session, size)?;
|
||||
let values = material_at(&self.session, &camera.texels)?;
|
||||
|
||||
let sub_pixels = (SUPERSAMPLE * SUPERSAMPLE) as f32;
|
||||
let pixels = (0..size * size)
|
||||
.map(|pixel| {
|
||||
let mut sum = Sample { base: [0.0; 3], metallic: 0.0, roughness: 0.0, height: 0.0 };
|
||||
let (mut normal_sum, mut hits) = (Vec3::ZERO, 0.0);
|
||||
for (texel, normal) in pixel_hits(camera, size, pixel) {
|
||||
let Some(value) = values.get(texel) else { continue };
|
||||
|
||||
sum.base = [0, 1, 2].map(|component| sum.base[component] + value.base[component]);
|
||||
sum.metallic += value.metallic;
|
||||
sum.roughness += value.roughness;
|
||||
sum.height += value.height;
|
||||
normal_sum += normal;
|
||||
hits += 1.0;
|
||||
}
|
||||
|
||||
(hits > 0.0).then(|| {
|
||||
let mean = Sample {
|
||||
base: sum.base.map(|component| component / hits),
|
||||
metallic: sum.metallic / hits,
|
||||
roughness: sum.roughness / hits,
|
||||
height: sum.height / hits,
|
||||
};
|
||||
MaterialPreviewPixel { sample: mean, normal: normal_sum.normalize_or_zero(), coverage: hits / sub_pixels }
|
||||
})
|
||||
})
|
||||
.collect();
|
||||
Some(pixels)
|
||||
}
|
||||
}
|
||||
|
||||
/// Preview sizes the camera may allocate
|
||||
fn valid_size(size: usize) -> bool {
|
||||
(1..=MAX_PREVIEW_SIZE_PX).contains(&size)
|
||||
}
|
||||
|
||||
/// The rays through `pixel` of a `size²` preview that hit the shape, as (texel index, view-space normal)
|
||||
fn pixel_hits(camera: &OrbCamera, size: usize, pixel: usize) -> impl Iterator<Item = (usize, Vec3)> + '_ {
|
||||
let (x, y) = (pixel % size, pixel / size);
|
||||
(0..SUPERSAMPLE * SUPERSAMPLE).filter_map(move |sub_pixel| {
|
||||
let (sub_x, sub_y) = (sub_pixel % SUPERSAMPLE, sub_pixel / SUPERSAMPLE);
|
||||
let ray = (y * SUPERSAMPLE + sub_y) * camera.rays_per_side + x * SUPERSAMPLE + sub_x;
|
||||
camera.samples.get(ray).copied().flatten()
|
||||
})
|
||||
}
|
||||
|
||||
/// The material values at `texels`, compositing only the tiles that hold them
|
||||
fn material_at(session: &Session, texels: &[(u32, u32)]) -> Option<Vec<Sample>> {
|
||||
let tiles: BTreeSet<(u32, u32)> = texels.iter().map(|(x, y)| (x / TILE, y / TILE)).collect();
|
||||
let tiles: Vec<(u32, u32)> = tiles.into_iter().collect();
|
||||
|
||||
session.with_inputs(SET, |inputs| {
|
||||
let mut composite = texturecraft_compose::Composite::new(&MATERIAL_CHANNELS, TEXTURE_PX);
|
||||
texturecraft_compose::composite_tiles(inputs, &mut composite, &tiles);
|
||||
|
||||
let samples = texels
|
||||
.iter()
|
||||
.map(|&(x, y)| {
|
||||
let [base, metallic, roughness, height] = MATERIAL_CHANNELS.map(|channel| composite.value(channel, x, y));
|
||||
Sample { base, metallic: metallic[0], roughness: roughness[0], height: height[0] }
|
||||
})
|
||||
.collect();
|
||||
Some(samples)
|
||||
})
|
||||
}
|
||||
|
||||
/// Cache one camera per preview size, evicting the least recently used view
|
||||
fn camera_for<'a>(cameras: &'a mut Vec<OrbCamera>, session: &Session, size: usize) -> Option<&'a OrbCamera> {
|
||||
let rays_per_side = size * SUPERSAMPLE;
|
||||
let camera = match cameras.iter().position(|camera| camera.rays_per_side == rays_per_side) {
|
||||
Some(index) => cameras.remove(index),
|
||||
None => OrbCamera::new(session, TEXTURE_PX, rays_per_side),
|
||||
};
|
||||
if cameras.len() >= CAMERAS_KEPT {
|
||||
cameras.remove(0);
|
||||
}
|
||||
|
||||
cameras.push(camera);
|
||||
cameras.last()
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
/// Mean absolute difference of the masks of two previews over the pixels both see
|
||||
fn difference(a: &[Option<MaskPreviewPixel>], b: &[Option<MaskPreviewPixel>]) -> f32 {
|
||||
let pairs: Vec<(f32, f32)> = a.iter().zip(b).filter_map(|(a, b)| Some((a.as_ref()?.mask, b.as_ref()?.mask))).collect();
|
||||
pairs.iter().map(|(a, b)| (a - b).abs()).sum::<f32>() / pairs.len().max(1) as f32
|
||||
}
|
||||
|
||||
/// Mean mask value over the pixels a preview sees
|
||||
fn mean_mask(pixels: &[Option<MaskPreviewPixel>]) -> f32 {
|
||||
pixels.iter().flatten().map(|pixel| pixel.mask).sum::<f32>() / pixels.iter().flatten().count().max(1) as f32
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn invalid_preview_sizes_are_rejected_before_changing_the_shape() {
|
||||
let session = Session::new_project("Orb preview", primitives::cube(2.0), "builtin:cube", None, 128).unwrap();
|
||||
let layer = session.doc.project.texture_set(SET).unwrap().stack[0];
|
||||
let bare = (session.doc.clone(), session.selected.clone());
|
||||
let mut preview = OrbPreview { session, layer, bare, cameras: Vec::new() };
|
||||
let stack_size = preview.session.doc.project.texture_set(SET).unwrap().stack.len();
|
||||
for size in [0, MAX_PREVIEW_SIZE_PX + 1, usize::MAX / 2 + 1, usize::MAX] {
|
||||
assert!(preview.mask("edges_sharp", size).is_none(), "size {size} should be rejected before rendering");
|
||||
assert!(preview.material("steel_painted_worn", size).is_none(), "size {size} should be rejected before rendering");
|
||||
assert!(preview.cameras.is_empty(), "invalid sizes must not allocate a camera");
|
||||
assert!(preview.session.doc.project.layer(layer).unwrap().mask.is_none(), "invalid sizes must not apply a mask");
|
||||
assert_eq!(preview.session.doc.project.texture_set(SET).unwrap().stack.len(), stack_size, "invalid sizes must not apply a material");
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn smart_mask_previews_are_in_range_tell_edges_from_cavities_and_render_at_any_size() {
|
||||
let size = 24;
|
||||
let mut preview = OrbPreview::new().unwrap();
|
||||
for smart_mask in crate::smart_masks::SMART_MASKS {
|
||||
let id = smart_mask.id;
|
||||
let pixels = preview.mask(id, size).unwrap_or_else(|| panic!("{id}"));
|
||||
assert_eq!(pixels.len(), size * size, "{id}");
|
||||
assert!(pixels[0].is_none(), "{id}: the corners are outside the shape");
|
||||
|
||||
let seen: Vec<&MaskPreviewPixel> = pixels.iter().flatten().collect();
|
||||
assert!(seen.len() > size * size / 3, "{id}: the shape fills the frame");
|
||||
for pixel in seen {
|
||||
assert!((0.0..=1.0).contains(&pixel.mask) && (0.0..=1.0).contains(&pixel.coverage) && pixel.coverage > 0.0, "{id}: {pixel:?}");
|
||||
assert!(pixel.normal.is_finite(), "{id}: {pixel:?}");
|
||||
}
|
||||
}
|
||||
|
||||
let (edges, cavities) = (preview.mask("edges_sharp", size).unwrap(), preview.mask("dirt_cavities", size).unwrap());
|
||||
let shows = |pixels: &[Option<MaskPreviewPixel>]| pixels.iter().flatten().any(|pixel| pixel.mask > 0.5);
|
||||
assert!(shows(&edges) && shows(&cavities), "both masks find something on the shape");
|
||||
assert!(difference(&edges, &cavities) > 0.05, "edges and cavities differ: {}", difference(&edges, &cavities));
|
||||
assert!(preview.mask("nope", size).is_none());
|
||||
|
||||
// The same bake renders other sizes, showing the same mask
|
||||
let big = preview.mask("edges_sharp", size * 3).unwrap();
|
||||
assert_eq!(big.len(), size * size * 9);
|
||||
assert!((mean_mask(&big) - mean_mask(&edges)).abs() < 0.05, "{} vs {}", mean_mask(&big), mean_mask(&edges));
|
||||
|
||||
preview.mask("edges_sharp", size * 2).unwrap();
|
||||
assert_eq!(preview.cameras.len(), CAMERAS_KEPT, "only the most recent sizes keep their camera");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn smart_materials_render_on_the_orb_and_show_their_wear() {
|
||||
let size = 24;
|
||||
let mut preview = OrbPreview::new().unwrap();
|
||||
for material in materials::MATERIALS.iter().filter(|material| material.smart) {
|
||||
let id = material.id;
|
||||
let pixels = preview.material(id, size).unwrap_or_else(|| panic!("{id}"));
|
||||
assert_eq!(pixels.len(), size * size, "{id}");
|
||||
assert!(pixels[0].is_none(), "{id}: the corners are outside the shape");
|
||||
|
||||
for pixel in pixels.iter().flatten() {
|
||||
let sample = pixel.sample;
|
||||
let values = sample.base.into_iter().chain([sample.metallic, sample.roughness, sample.height]);
|
||||
assert!(values.into_iter().all(f32::is_finite), "{id}: {pixel:?}");
|
||||
assert!(pixel.normal.is_finite() && pixel.coverage > 0.0, "{id}: {pixel:?}");
|
||||
}
|
||||
}
|
||||
assert!(preview.material("nope", size).is_none());
|
||||
|
||||
// Paint chipped at the edges shows the steel under it: the smart material is not its base
|
||||
let (worn, steel) = (preview.material("steel_painted_worn", size).unwrap(), preview.material("steel", size).unwrap());
|
||||
let metallic_pixels = |pixels: &[Option<MaterialPreviewPixel>]| pixels.iter().flatten().filter(|pixel| pixel.sample.metallic > 0.5).count();
|
||||
let (worn_metallic, steel_metallic) = (metallic_pixels(&worn), metallic_pixels(&steel));
|
||||
assert!(worn_metallic > 0 && worn_metallic < steel_metallic / 2, "bare steel only at the worn edges: {worn_metallic} of {steel_metallic}");
|
||||
|
||||
let base_colors = |pixels: &[Option<MaterialPreviewPixel>]| pixels.iter().flatten().map(|pixel| pixel.sample.base).collect::<Vec<_>>();
|
||||
assert_ne!(base_colors(&worn), base_colors(&steel));
|
||||
|
||||
// Each material starts from the bare orb: rendering another one in between changes nothing
|
||||
preview.material("iron_rusted", size).unwrap();
|
||||
assert_eq!(preview.material("steel_painted_worn", size).unwrap(), worn);
|
||||
}
|
||||
}
|
||||
+82
-136
@@ -7,13 +7,23 @@ use texturecraft_compose::PaintTarget;
|
||||
use texturecraft_core::{Channel, Effect, EffectKind, LayerId, LayerKind, Mask, MaskBackground};
|
||||
use texturecraft_geom::glam::Vec2;
|
||||
use texturecraft_paint::{
|
||||
CommitSource, EyeDepth, PickCtx, Pickup, PickupMode, RasterCtx, Shape, Staging, Stroke, StrokeCanvas, SurfaceHit, commit_layer, commit_mask,
|
||||
fill_triangles, pick, rasterize,
|
||||
CommitSource, EyeDepth, PickCtx, Pickup, PickupMode, RasterCtx, Shape, Staging, Stroke, StrokeCanvas, SurfaceHit, commit_layer, commit_mask, pick,
|
||||
rasterize,
|
||||
};
|
||||
|
||||
use crate::session::{ActiveStroke, CloneFrom, FillMode, Session, StackTarget, Tool};
|
||||
use crate::session::{ActiveStroke, CloneFrom, Session, StackTarget, Tool};
|
||||
use crate::uv_stroke_state::UvStrokeState;
|
||||
use crate::{EngineError, Result};
|
||||
|
||||
/// 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;
|
||||
|
||||
/// 2D view stamps rasterized together, bounding the memory of one batch.
|
||||
const UV_STAMP_BATCH: usize = 4096;
|
||||
|
||||
/// Covers a UV diagonal at the minimum step (about 142k stamps), including light pen pressure, while bounding hostile coordinates
|
||||
const MAX_UV_STAMPS_PER_SAMPLE: usize = 150_000;
|
||||
|
||||
impl Session {
|
||||
/// Camera visibility for a stroke at `viewport` (cached until the camera, size or mesh change).
|
||||
fn eye_depth(&mut self, viewport: Vec2) -> std::sync::Arc<EyeDepth> {
|
||||
@@ -234,7 +244,7 @@ impl Session {
|
||||
stroke,
|
||||
canvas,
|
||||
depth,
|
||||
uv: uv_mode.then_some((None, 0.0)),
|
||||
uv: uv_mode.then(UvStrokeState::default),
|
||||
camera: self.camera,
|
||||
viewport,
|
||||
values,
|
||||
@@ -301,12 +311,15 @@ impl Session {
|
||||
Ok(self.continue_stroke(screen, pressure))
|
||||
}
|
||||
|
||||
/// Start a stroke in the 2D view at texture coordinate `uv`.
|
||||
/// Start a stroke in the 2D view at texture coordinate `uv` (polygon fill fills there).
|
||||
pub fn begin_stroke_uv(&mut self, uv: Vec2, pressure: f32) -> Result<()> {
|
||||
self.cancel_stroke();
|
||||
if matches!(self.tool.tool, Tool::PolygonFill | Tool::ColorPicker | Tool::GeometryMask) {
|
||||
return Err(EngineError::Other("use this tool in the 3D view".into()));
|
||||
match self.tool.tool {
|
||||
Tool::PolygonFill => return self.polygon_fill_uv(uv).map(|_| ()),
|
||||
Tool::ColorPicker | Tool::GeometryMask => return Err(EngineError::Other("use this tool in the 3D view".into())),
|
||||
_ => {}
|
||||
}
|
||||
|
||||
self.start_stroke(self.viewport, true, Some(uv))?;
|
||||
self.continue_stroke_uv(uv, pressure);
|
||||
Ok(())
|
||||
@@ -314,40 +327,49 @@ impl Session {
|
||||
|
||||
/// Add a 2D view sample (texture coordinates). Brush size is relative to the UV square.
|
||||
pub fn continue_stroke_uv(&mut self, uv: Vec2, pressure: f32) {
|
||||
let Some(st) = self.stroke.as_mut() else { return };
|
||||
let Some((last, carry)) = st.uv.as_mut() else { return };
|
||||
let Some(cache) = self.caches.get_mut(st.ts) else { return };
|
||||
let b = &st.stroke.settings;
|
||||
let p = pressure.clamp(0.0, 1.0);
|
||||
let radius = b.size * 2.0 * if p < 1.0 { b.min_size + (1.0 - b.min_size) * p } else { 1.0 };
|
||||
let step = (b.spacing * 2.0 * radius).max(1e-5);
|
||||
let mut points = Vec::new();
|
||||
match *last {
|
||||
None => points.push(uv),
|
||||
Some(prev) => {
|
||||
let seg = uv - prev;
|
||||
let len = seg.length();
|
||||
let mut t = step - *carry;
|
||||
while t <= len && points.len() < 4096 {
|
||||
points.push(prev + seg * (t / len.max(1e-9)));
|
||||
t += step;
|
||||
}
|
||||
*carry = len - (t - step);
|
||||
}
|
||||
}
|
||||
// Follow path: turn the stamp with the stroke direction (y up on screen, v grows down).
|
||||
let angle = match *last {
|
||||
Some(prev) if b.follow_path && uv != prev => b.angle + (prev.y - uv.y).atan2(uv.x - prev.x).to_degrees() - 90.0,
|
||||
_ => b.angle,
|
||||
let Some(active) = self.stroke.as_mut() else { return };
|
||||
let Some(progress) = active.uv.as_mut() else { return };
|
||||
let Some(cache) = self.caches.get_mut(active.ts) else { return };
|
||||
|
||||
let settings = &active.stroke.settings;
|
||||
let pressure = pressure.clamp(0.0, 1.0);
|
||||
let size_scale = if pressure < 1.0 { settings.min_size + (1.0 - settings.min_size) * pressure } else { 1.0 };
|
||||
let radius = settings.size * 2.0 * size_scale;
|
||||
let step = (settings.spacing * 2.0 * radius).max(MIN_UV_STAMP_STEP);
|
||||
|
||||
// Follow path: turn the stamp with the stroke direction (y up on screen, v grows down)
|
||||
let angle = match progress.last {
|
||||
Some(previous) if settings.follow_path && uv != previous => settings.angle + (previous.y - uv.y).atan2(uv.x - previous.x).to_degrees() - 90.0,
|
||||
_ => settings.angle,
|
||||
};
|
||||
*last = Some(uv);
|
||||
let n0 = st.stroke.stamps.len() as u32;
|
||||
let stamps: Vec<texturecraft_paint::UvStamp> = points
|
||||
.iter()
|
||||
.enumerate()
|
||||
.map(|(i, c)| texturecraft_paint::UvStamp { center: *c, radius, angle, flow: b.flow, hardness: b.hardness, seed: n0 + i as u32 })
|
||||
.collect();
|
||||
texturecraft_paint::rasterize_uv(&mut st.canvas, &cache.gbuf, Self::shape(&self.images, b), &stamps);
|
||||
|
||||
// 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);
|
||||
let mut batch = Vec::new();
|
||||
let mut stamped = 0;
|
||||
while distance <= length && stamped < MAX_UV_STAMPS_PER_SAMPLE {
|
||||
let batch_size = UV_STAMP_BATCH.min(MAX_UV_STAMPS_PER_SAMPLE - stamped);
|
||||
batch.clear();
|
||||
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 });
|
||||
distance += step;
|
||||
}
|
||||
|
||||
stamped += batch.len();
|
||||
texturecraft_paint::rasterize_uv(&mut active.canvas, &cache.gbuf, shape, &batch);
|
||||
}
|
||||
|
||||
// At most one step, so a segment cut off at the stamp limit can't push the next one's stamps backwards
|
||||
progress.carry = (length - (distance - step)).min(step);
|
||||
progress.stamps = progress.stamps.wrapping_add(stamped as u32);
|
||||
self.stroke_painted();
|
||||
}
|
||||
|
||||
@@ -482,21 +504,6 @@ impl Session {
|
||||
Ok(tiles)
|
||||
}
|
||||
|
||||
/// Polygon fill: fill the triangle / UV island / whole mesh under `screen`.
|
||||
pub fn polygon_fill(&mut self, screen: Vec2, viewport: Vec2) -> Result<usize> {
|
||||
let hit = self.pick(screen, viewport).ok_or_else(|| EngineError::Other("nothing under the cursor".into()))?;
|
||||
let ts = self.ts();
|
||||
let material = self.doc.project.texture_set(ts)?.material;
|
||||
if hit.material != material {
|
||||
return Err(EngineError::Other("that surface belongs to another texture set".into()));
|
||||
}
|
||||
let tris = self.fill_set(hit.tri, material);
|
||||
let (gbuf, mut canvas) = self.fill_canvas(ts)?;
|
||||
fill_triangles(&mut canvas, &gbuf, &tris);
|
||||
self.commit_fill("Polygon fill", ts, &canvas)?;
|
||||
Ok(tris.len())
|
||||
}
|
||||
|
||||
/// The G-buffer of texture set `ts` and an empty canvas for a one-shot fill, limited by the
|
||||
/// quick mask unless the fill edits it.
|
||||
pub(crate) fn fill_canvas(&self, ts: usize) -> Result<(std::sync::Arc<texturecraft_geom::UvGBuffer>, StrokeCanvas)> {
|
||||
@@ -510,61 +517,31 @@ impl Session {
|
||||
|
||||
/// Commit a one-shot fill with the tool's material (one undo step), or into the quick mask.
|
||||
pub(crate) fn commit_fill(&mut self, label: &str, ts: usize, canvas: &StrokeCanvas) -> Result<()> {
|
||||
let size = (canvas.alpha.width(), canvas.alpha.height());
|
||||
let src = |opacity| CommitSource { alpha: &canvas.alpha, tiles: &canvas.dirty, opacity, erase: false, per_texel: None, carried: None };
|
||||
if self.quick_mask.editing {
|
||||
self.commit_quick_mask(ts, size, src(self.tool.brush.opacity));
|
||||
return Ok(());
|
||||
return self.paint_fill(ts, canvas);
|
||||
}
|
||||
self.edit(label, |s| {
|
||||
let target = s.paint_target()?;
|
||||
let values = s.stroke_values(target);
|
||||
match target {
|
||||
PaintTarget::Layer(id) => commit_layer(&mut s.doc.pixels, id, size, &values, src(s.tool.brush.opacity), &mut Staging::default()),
|
||||
PaintTarget::Mask(eid) => commit_mask(&mut s.doc.pixels, eid, size, s.tool.mask_value, src(s.tool.brush.opacity), &mut Staging::default()),
|
||||
}
|
||||
Ok(())
|
||||
})
|
||||
|
||||
// Each fill is its own step, never merged into a box drag's step of the same label
|
||||
self.edit_merging(label, false, |session| session.paint_fill(ts, canvas))
|
||||
}
|
||||
|
||||
/// Triangles filled by the current fill mode starting from `tri`.
|
||||
fn fill_set(&self, tri: u32, material: usize) -> BTreeSet<u32> {
|
||||
let m = &self.mesh;
|
||||
match self.tool.fill_mode {
|
||||
FillMode::Triangle => [tri].into_iter().collect(),
|
||||
FillMode::Mesh => m.triangles_of(material).map(|t| t as u32).collect(),
|
||||
FillMode::UvIsland => {
|
||||
// Triangles sharing an edge in UV space form a UV island: imported meshes often
|
||||
// split vertices along hard edges (or per face) where the UVs run on, so shared
|
||||
// vertex indices alone break an island into its polygons.
|
||||
let corner = |i: usize| m.uvs.get(i).map(|uv| [(uv.x * 1e5).round() as i64, (uv.y * 1e5).round() as i64]);
|
||||
let edges = |t: usize| match m.tri(t).map(|v| v.map(corner)) {
|
||||
Some([Some(a), Some(b), Some(c)]) => [(a, b), (b, c), (c, a)].map(|(p, q)| (p.min(q), p.max(q))).to_vec(),
|
||||
_ => Vec::new(),
|
||||
};
|
||||
let mut by_edge: BTreeMap<_, Vec<u32>> = BTreeMap::new();
|
||||
for t in m.triangles_of(material) {
|
||||
for e in edges(t) {
|
||||
by_edge.entry(e).or_default().push(t as u32);
|
||||
}
|
||||
}
|
||||
let mut seen = BTreeSet::new();
|
||||
let mut stack = vec![tri];
|
||||
while let Some(t) = stack.pop() {
|
||||
if !seen.insert(t) {
|
||||
continue;
|
||||
}
|
||||
for e in edges(t as usize) {
|
||||
for n in by_edge.get(&e).map(Vec::as_slice).unwrap_or(&[]) {
|
||||
if !seen.contains(n) {
|
||||
stack.push(*n);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
seen
|
||||
}
|
||||
/// Paint a one-shot fill with the tool's material into the paint target, or into the quick mask while it is edited (no undo step)
|
||||
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 };
|
||||
if self.quick_mask.editing {
|
||||
self.commit_quick_mask(ts, size, source);
|
||||
return Ok(());
|
||||
}
|
||||
|
||||
let target = self.paint_target()?;
|
||||
let values = self.stroke_values(target);
|
||||
match target {
|
||||
PaintTarget::Layer(id) => commit_layer(&mut self.doc.pixels, id, size, &values, source, &mut Staging::default()),
|
||||
PaintTarget::Mask(effect) => commit_mask(&mut self.doc.pixels, effect, size, self.tool.mask_value, source, &mut Staging::default()),
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// Color picker: copy the material under the cursor into the tool's paint values.
|
||||
@@ -627,34 +604,3 @@ fn with_commit_source<R>(
|
||||
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 })
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use texturecraft_geom::glam::{Vec2, Vec3};
|
||||
use texturecraft_geom::mesh::Mesh;
|
||||
use texturecraft_geom::primitives;
|
||||
|
||||
use crate::session::{FillMode, Session};
|
||||
|
||||
#[test]
|
||||
fn uv_island_fill_follows_uvs_across_split_vertices() {
|
||||
// Two copies of a plane, each triangle with its own three vertices (as hard edges or
|
||||
// per-face imports leave a mesh), the second copy apart in UV space.
|
||||
let plane = primitives::plane(2.0, 4);
|
||||
let (mut positions, mut uvs) = (Vec::<Vec3>::new(), Vec::<Vec2>::new());
|
||||
for shift in [0.0, 0.5] {
|
||||
for i in plane.indices.iter().map(|i| *i as usize) {
|
||||
positions.push(plane.positions[i] + Vec3::Y * shift);
|
||||
uvs.push(plane.uvs[i] * 0.5 + shift);
|
||||
}
|
||||
}
|
||||
let indices = (0..positions.len() as u32).collect();
|
||||
let mesh = Mesh::from_parts(positions, None, uvs, indices, "m").unwrap();
|
||||
let n = plane.triangle_count();
|
||||
assert_eq!(mesh.vertex_count(), 6 * n, "no vertex is shared");
|
||||
let mut s = Session::new_project("t", mesh, "test", None, 128).unwrap();
|
||||
s.tool.fill_mode = FillMode::UvIsland;
|
||||
assert_eq!(s.fill_set(0, 0).len(), n, "the whole first island");
|
||||
assert_eq!(s.fill_set(n as u32, 0).len(), n, "only the second island");
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,607 @@
|
||||
//! Polygon fill: fill the triangles, polygons, UV islands or connected meshes under a click or inside a dragged box, in either view.
|
||||
|
||||
use std::borrow::Cow;
|
||||
use std::collections::{BTreeSet, HashSet};
|
||||
|
||||
use texturecraft_geom::glam::Vec2;
|
||||
use texturecraft_geom::{Mesh, NO_TRI};
|
||||
use texturecraft_paint::{EyeDepth, fill_triangles, screen_point};
|
||||
|
||||
use crate::fill_mode::FillMode;
|
||||
use crate::polygon_fill_drag::PolygonFillDrag;
|
||||
use crate::session::Session;
|
||||
use crate::triangle_partition::TrianglePartition;
|
||||
use crate::{EngineError, Result};
|
||||
|
||||
/// Corners closer than one step of this grid (per unit of position or UV) count as the same corner
|
||||
const CORNER_GRID_STEPS: f32 = 1e5;
|
||||
|
||||
impl Session {
|
||||
/// Fill the triangle / polygon / UV island / connected mesh under viewport pixel `screen`
|
||||
pub fn polygon_fill(&mut self, screen: Vec2, viewport: Vec2) -> Result<usize> {
|
||||
let hit = self.pick(screen, viewport).ok_or_else(|| EngineError::Other("nothing under the cursor".into()))?;
|
||||
if hit.material != self.fill_material()? {
|
||||
return Err(EngineError::Other("that surface belongs to another texture set".into()));
|
||||
}
|
||||
|
||||
self.fill_group_of(hit.tri)
|
||||
}
|
||||
|
||||
/// Fill like [`Session::polygon_fill`] at texture coordinate `uv` (the 2D view): the triangle covering that texel's center, so slivers thinner than a texel can't be clicked
|
||||
pub fn polygon_fill_uv(&mut self, uv: Vec2) -> Result<usize> {
|
||||
let gbuf = self.caches.get(self.ts()).map(|cache| cache.gbuf.clone()).ok_or_else(|| EngineError::Other("texture set not ready".into()))?;
|
||||
let size = Vec2::new(gbuf.width as f32, gbuf.height as f32);
|
||||
let texel = (uv * size).floor();
|
||||
let triangle = (texel.cmpge(Vec2::ZERO).all() && texel.cmplt(size).all())
|
||||
.then(|| gbuf.tri.get(texel.y as usize * gbuf.width as usize + texel.x as usize).copied())
|
||||
.flatten()
|
||||
.filter(|triangle| *triangle != NO_TRI)
|
||||
.ok_or_else(|| EngineError::Other("nothing under the cursor".into()))?;
|
||||
|
||||
self.fill_group_of(triangle)
|
||||
}
|
||||
|
||||
/// Fill what the box between viewport pixels `corner` and `opposite` selects (one undo step)
|
||||
pub fn polygon_fill_box(&mut self, corner: Vec2, opposite: Vec2, viewport: Vec2) -> Result<usize> {
|
||||
// A scripted box stands alone: it finishes any drag under way, and ends even when it fails
|
||||
self.end_polygon_fill_box();
|
||||
let shown = self.drag_polygon_fill_box(corner, opposite, viewport);
|
||||
let filled = self.end_polygon_fill_box();
|
||||
shown.map(|_| filled)
|
||||
}
|
||||
|
||||
/// Fill what the box between texture coordinates `corner` and `opposite` selects (the 2D view, one undo step)
|
||||
pub fn polygon_fill_box_uv(&mut self, corner: Vec2, opposite: Vec2) -> Result<usize> {
|
||||
self.end_polygon_fill_box();
|
||||
let shown = self.drag_polygon_fill_box_uv(corner, opposite);
|
||||
let filled = self.end_polygon_fill_box();
|
||||
shown.map(|_| filled)
|
||||
}
|
||||
|
||||
/// Show the fill of a box being dragged between viewport pixels `corner` and `opposite`
|
||||
pub fn drag_polygon_fill_box(&mut self, corner: Vec2, opposite: Vec2, viewport: Vec2) -> Result<usize> {
|
||||
// Whole pixels, as the visibility buffer is rendered at
|
||||
self.drag_polygon_fill(corner, opposite, Some(viewport.round().max(Vec2::ONE)))
|
||||
}
|
||||
|
||||
/// Show the fill of a box being dragged between texture coordinates `corner` and `opposite` (the 2D view)
|
||||
pub fn drag_polygon_fill_box_uv(&mut self, corner: Vec2, opposite: Vec2) -> Result<usize> {
|
||||
self.drag_polygon_fill(corner, opposite, None)
|
||||
}
|
||||
|
||||
/// Finish the dragged box: what it filled becomes one undo step. Returns the filled triangle count
|
||||
pub fn end_polygon_fill_box(&mut self) -> usize {
|
||||
let Some(drag) = self.polygon_fill_drag.take() else { return 0 };
|
||||
|
||||
let filled = drag.filled.len();
|
||||
// Quick mask edits keep no history, as with its strokes
|
||||
if filled > 0 && drag.quick_mask_before.is_none() {
|
||||
self.push_history("Polygon fill", drag.before);
|
||||
}
|
||||
filled
|
||||
}
|
||||
|
||||
/// Show the fill of a box from `corner` to `opposite` in the 3D view of size `viewport`, or in the 2D view when None
|
||||
fn drag_polygon_fill(&mut self, corner: Vec2, opposite: Vec2, viewport: Option<Vec2>) -> Result<usize> {
|
||||
if !corner.is_finite() || !opposite.is_finite() {
|
||||
return Err(EngineError::Other("the box corners must be finite".into()));
|
||||
}
|
||||
|
||||
let (low, high) = (corner.min(opposite), corner.max(opposite));
|
||||
self.start_polygon_fill_drag(viewport)?;
|
||||
let Some(drag) = self.polygon_fill_drag.as_mut() else { return Ok(0) };
|
||||
|
||||
if drag.failed || drag.last_box == Some((low, high)) {
|
||||
return Ok(drag.filled.len());
|
||||
}
|
||||
|
||||
drag.last_box = Some((low, high));
|
||||
let selected = self.box_selection(low, high);
|
||||
self.show_box_fill(selected)
|
||||
}
|
||||
|
||||
/// Continue a box drag only while its view, paint target and quick mask state still match
|
||||
fn start_polygon_fill_drag(&mut self, viewport: Option<Vec2>) -> Result<()> {
|
||||
let ts = self.ts();
|
||||
let target = (self.selected_layer(), self.target);
|
||||
let quick_mask = self.quick_mask.editing;
|
||||
// Finish the old target before another preview can restore its earlier document snapshot
|
||||
if let Some(drag) = &self.polygon_fill_drag {
|
||||
if drag.ts == ts && drag.target == target && drag.viewport == viewport && drag.quick_mask_before.is_some() == quick_mask {
|
||||
// A camera move (a wheel zoom mid-drag) keeps the drag, which then sees the mesh from the new camera
|
||||
if drag.camera != self.camera {
|
||||
let (points, depth) = self.box_space(viewport);
|
||||
if let Some(drag) = self.polygon_fill_drag.as_mut() {
|
||||
(drag.points, drag.depth, drag.camera, drag.last_box) = (points, depth, self.camera, None);
|
||||
}
|
||||
}
|
||||
|
||||
return Ok(());
|
||||
}
|
||||
|
||||
self.end_polygon_fill_box();
|
||||
}
|
||||
|
||||
let material = self.fill_material()?;
|
||||
let (points, depth) = self.box_space(viewport);
|
||||
let polygons = match self.tool.fill_mode {
|
||||
FillMode::Triangle | FillMode::Polygon => None,
|
||||
FillMode::UvIsland | FillMode::Mesh => Some(TrianglePartition::new(&self.mesh, material, polygon_edges)),
|
||||
};
|
||||
self.polygon_fill_drag = Some(PolygonFillDrag {
|
||||
ts,
|
||||
target,
|
||||
viewport,
|
||||
camera: self.camera,
|
||||
before: self.doc.clone(),
|
||||
quick_mask_before: quick_mask.then(|| self.quick_mask.masks.clone()),
|
||||
points,
|
||||
depth,
|
||||
fill_groups: self.fill_partition(material),
|
||||
polygons,
|
||||
filled: BTreeSet::new(),
|
||||
last_box: None,
|
||||
failed: false,
|
||||
});
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// Each vertex where a box sees it (viewport pixels for a 3D view of size `viewport`, else texture coordinates) and, for visible polygons only in 3D, what the camera sees
|
||||
fn box_space(&self, viewport: Option<Vec2>) -> (Vec<Option<Vec2>>, Option<EyeDepth>) {
|
||||
let Some(size) = viewport else { return (self.mesh.uvs.iter().copied().map(Some).collect(), None) };
|
||||
|
||||
let view_proj = self.camera.view_proj(size.x / size.y);
|
||||
let points = self.mesh.positions.iter().map(|position| screen_point(view_proj, *position, size)).collect();
|
||||
let depth = self.tool.fill_visible_only.then(|| EyeDepth::render_with_triangles(&self.shown_mesh(), &self.camera, size.x as u32, size.y as u32));
|
||||
(points, depth)
|
||||
}
|
||||
|
||||
/// The mesh material of the texture set being painted
|
||||
fn fill_material(&self) -> Result<usize> {
|
||||
Ok(self.doc.project.texture_set(self.ts())?.material)
|
||||
}
|
||||
|
||||
/// The triangles the current fill mode fills together, for `material`
|
||||
fn fill_partition(&self, material: usize) -> TrianglePartition {
|
||||
match self.tool.fill_mode {
|
||||
FillMode::Triangle => TrianglePartition::new(&self.mesh, material, |_, _| Vec::<u32>::new()),
|
||||
FillMode::Polygon => TrianglePartition::new(&self.mesh, material, polygon_edges),
|
||||
FillMode::UvIsland => TrianglePartition::new(&self.mesh, material, uv_edges),
|
||||
FillMode::Mesh => TrianglePartition::new(&self.mesh, material, position_edges),
|
||||
}
|
||||
}
|
||||
|
||||
/// Fill the fill-mode group holding `triangle` (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 (gbuf, mut canvas) = self.fill_canvas(ts)?;
|
||||
fill_triangles(&mut canvas, &gbuf, &triangles);
|
||||
self.commit_fill("Polygon fill", ts, &canvas)?;
|
||||
Ok(triangles.len())
|
||||
}
|
||||
|
||||
/// The mesh as the 3D view shows it: hidden texture sets' triangles collapse to a point, so nothing behind them counts as hidden
|
||||
fn shown_mesh(&self) -> Cow<'_, Mesh> {
|
||||
let sets = &self.doc.project.texture_sets;
|
||||
if sets.iter().all(|set| set.visible) {
|
||||
return Cow::Borrowed(&self.mesh);
|
||||
}
|
||||
|
||||
let mut mesh = (*self.mesh).clone();
|
||||
for set in sets.iter().filter(|set| !set.visible) {
|
||||
for triangle in self.mesh.triangles_of(set.material) {
|
||||
if let Some(corners) = mesh.indices.get_mut(triangle * 3..triangle * 3 + 3) {
|
||||
let first = corners[0];
|
||||
corners.fill(first);
|
||||
}
|
||||
}
|
||||
}
|
||||
Cow::Owned(mesh)
|
||||
}
|
||||
|
||||
/// Triangles the dragged box from `low` to `high` fills: each polygon the hit-test selects, grown by the fill mode
|
||||
fn box_selection(&self, low: Vec2, high: Vec2) -> BTreeSet<u32> {
|
||||
let Some(drag) = &self.polygon_fill_drag else { return BTreeSet::new() };
|
||||
|
||||
let visible = drag.depth.as_ref().zip(drag.viewport).map(|(depth, viewport)| visible_triangles(depth, viewport, low, high));
|
||||
let point = |vertex: usize| drag.points.get(vertex).copied().flatten();
|
||||
let corners = |triangle: u32| {
|
||||
let [first, second, third] = self.mesh.tri(triangle as usize)?;
|
||||
Some([point(first)?, point(second)?, point(third)?])
|
||||
};
|
||||
let hit_test = self.tool.fill_hit_test;
|
||||
let mut polygon_corners = Vec::new();
|
||||
let mut groups = BTreeSet::new();
|
||||
for polygon in &drag.polygons.as_ref().unwrap_or(&drag.fill_groups).groups {
|
||||
let seen = visible.as_ref().is_none_or(|visible| polygon.iter().any(|triangle| visible.contains(triangle)));
|
||||
if !seen {
|
||||
continue;
|
||||
}
|
||||
|
||||
polygon_corners.clear();
|
||||
polygon_corners.extend(polygon.iter().map_while(|triangle| corners(*triangle)));
|
||||
if polygon_corners.len() == polygon.len() && hit_test.selects(&polygon_corners, low, high) {
|
||||
groups.extend(polygon.iter().filter_map(|triangle| drag.fill_groups.index_of(*triangle)));
|
||||
}
|
||||
}
|
||||
|
||||
groups.iter().filter_map(|group| drag.fill_groups.groups.get(*group)).flatten().copied().collect()
|
||||
}
|
||||
|
||||
/// Show the box drag's fill of `selected`: the document before the drag, refilled when the selection changed
|
||||
fn show_box_fill(&mut self, selected: BTreeSet<u32>) -> Result<usize> {
|
||||
let Some(drag) = self.polygon_fill_drag.as_mut() else { return Ok(0) };
|
||||
if drag.filled == selected {
|
||||
return Ok(selected.len());
|
||||
}
|
||||
|
||||
let ts = drag.ts;
|
||||
let previous = std::mem::replace(&mut self.doc, drag.before.clone());
|
||||
if let Some(masks) = &drag.quick_mask_before {
|
||||
self.quick_mask.masks = masks.clone();
|
||||
self.quick_mask.revision = self.quick_mask.revision.wrapping_add(1);
|
||||
}
|
||||
|
||||
let painted = if selected.is_empty() {
|
||||
Ok(())
|
||||
} else {
|
||||
self.fill_canvas(ts).and_then(|(gbuf, mut canvas)| {
|
||||
fill_triangles(&mut canvas, &gbuf, &selected);
|
||||
self.paint_fill(ts, &canvas)
|
||||
})
|
||||
};
|
||||
self.invalidate_changed(&previous);
|
||||
|
||||
// A failed fill is reported once and leaves the document as before the drag; the rest of the drag fills nothing
|
||||
let selected_count = selected.len();
|
||||
if let Some(drag) = self.polygon_fill_drag.as_mut() {
|
||||
drag.failed = painted.is_err();
|
||||
drag.filled = if drag.failed { BTreeSet::new() } else { selected };
|
||||
}
|
||||
painted.map(|_| selected_count)
|
||||
}
|
||||
}
|
||||
|
||||
/// Triangles `depth` (rendered for a `viewport` pixel view) shows in the viewport pixels from `low` to `high`, both edges included
|
||||
fn visible_triangles(depth: &EyeDepth, viewport: Vec2, low: Vec2, high: Vec2) -> HashSet<u32> {
|
||||
let depth_pixels_per_viewport_pixel = Vec2::new(depth.width as f32, depth.height as f32) / viewport;
|
||||
let (low, high) = (low * depth_pixels_per_viewport_pixel, high * depth_pixels_per_viewport_pixel);
|
||||
let columns = pixel_span(low.x, high.x, depth.width);
|
||||
let rows = pixel_span(low.y, high.y, depth.height);
|
||||
|
||||
rows.flat_map(|row| depth.triangle.get(row * depth.width as usize..).into_iter().flat_map(|pixels| pixels.iter().take(columns.end).skip(columns.start)))
|
||||
.copied()
|
||||
.filter(|triangle| *triangle != NO_TRI)
|
||||
.collect()
|
||||
}
|
||||
|
||||
/// The pixels `0..count` a span from `low` to `high` covers, both edges included (empty when it lies outside)
|
||||
fn pixel_span(low: f32, high: f32, count: u32) -> std::ops::Range<usize> {
|
||||
let first = low.floor().clamp(0.0, count as f32) as usize;
|
||||
let end = (high.floor() + 1.0).clamp(0.0, count as f32) as usize;
|
||||
first..end.max(first)
|
||||
}
|
||||
|
||||
/// Texture coordinates of `triangle`'s corners
|
||||
fn uv_corners(mesh: &Mesh, triangle: usize) -> Option<[Vec2; 3]> {
|
||||
let [first, second, third] = mesh.tri(triangle)?;
|
||||
Some([*mesh.uvs.get(first)?, *mesh.uvs.get(second)?, *mesh.uvs.get(third)?])
|
||||
}
|
||||
|
||||
/// The polygon diagonals of `triangle`: edges the importer added to split a polygon
|
||||
fn polygon_edges(mesh: &Mesh, triangle: usize) -> Vec<(u32, u32)> {
|
||||
let hidden = mesh.diagonals.get(triangle).copied().unwrap_or(0);
|
||||
let Some(vertices) = mesh.indices.get(triangle * 3..triangle * 3 + 3) else { return Vec::new() };
|
||||
|
||||
(0..3)
|
||||
.filter(|edge| hidden >> edge & 1 == 1)
|
||||
.map(|edge| {
|
||||
let (from, to) = (vertices[edge], vertices[(edge + 1) % 3]);
|
||||
(from.min(to), from.max(to))
|
||||
})
|
||||
.collect()
|
||||
}
|
||||
|
||||
/// `triangle`'s edges in UV space: imports often split vertices along hard edges where the UVs run on, so vertex indices alone break islands apart
|
||||
fn uv_edges(mesh: &Mesh, triangle: usize) -> Vec<([i64; 2], [i64; 2])> {
|
||||
let corner = |uv: Vec2| (uv * CORNER_GRID_STEPS).round().to_array().map(|step| step as i64);
|
||||
let Some([first, second, third]) = uv_corners(mesh, triangle).map(|uvs| uvs.map(corner)) else { return Vec::new() };
|
||||
|
||||
[(first, second), (second, third), (third, first)].map(|(from, to)| (from.min(to), from.max(to))).to_vec()
|
||||
}
|
||||
|
||||
/// `triangle`'s edges by position: UV seams and hard edges split vertices but leave the geometry connected
|
||||
fn position_edges(mesh: &Mesh, triangle: usize) -> Vec<([i64; 3], [i64; 3])> {
|
||||
let corner = |vertex: usize| mesh.positions.get(vertex).map(|position| (*position * CORNER_GRID_STEPS).round().to_array().map(|step| step as i64));
|
||||
let Some([first, second, third]) = mesh.tri(triangle) else { return Vec::new() };
|
||||
let (Some(first), Some(second), Some(third)) = (corner(first), corner(second), corner(third)) else { return Vec::new() };
|
||||
|
||||
[(first, second), (second, third), (third, first)].map(|(from, to)| (from.min(to), from.max(to))).to_vec()
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use texturecraft_core::Channel;
|
||||
use texturecraft_geom::glam::{Vec2, Vec3};
|
||||
use texturecraft_geom::mesh::Mesh;
|
||||
use texturecraft_geom::primitives;
|
||||
|
||||
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;
|
||||
|
||||
/// A polygon fill session on `mesh` painting roughness [`FILL_ROUGHNESS`]
|
||||
fn fill_session(mesh: Mesh) -> Session {
|
||||
let mut session = Session::new_project("t", mesh, "test", None, 128).unwrap();
|
||||
session.viewport = Vec2::new(400.0, 400.0);
|
||||
session.tool.tool = Tool::PolygonFill;
|
||||
session.tool.values.insert(Channel::Roughness, [FILL_ROUGHNESS; 3]);
|
||||
session.update();
|
||||
session
|
||||
}
|
||||
|
||||
/// Whether the texel at texture coordinate `uv` shows the fill's roughness
|
||||
fn filled_at(session: &Session, uv: Vec2) -> bool {
|
||||
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
|
||||
}
|
||||
|
||||
/// Two copies of a plane apart in space and in UV space, each triangle with its own three vertices (as hard edges or per-face imports leave a mesh)
|
||||
fn split_planes() -> (Mesh, usize) {
|
||||
let plane = primitives::plane(2.0, 4);
|
||||
let (mut positions, mut uvs) = (Vec::<Vec3>::new(), Vec::<Vec2>::new());
|
||||
for shift in [0.0, 0.5] {
|
||||
for vertex in plane.indices.iter().map(|index| *index as usize) {
|
||||
positions.push(plane.positions[vertex] + Vec3::Y * shift);
|
||||
uvs.push(plane.uvs[vertex] * 0.5 + shift);
|
||||
}
|
||||
}
|
||||
let indices = (0..positions.len() as u32).collect();
|
||||
let mesh = Mesh::from_parts(positions, None, uvs, indices, "m").unwrap();
|
||||
assert_eq!(mesh.vertex_count(), 6 * plane.triangle_count(), "no vertex is shared");
|
||||
(mesh, plane.triangle_count())
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn uv_island_and_mesh_fills_follow_seams_split_vertices_leave_apart() {
|
||||
let (mesh, per_plane) = split_planes();
|
||||
let mut session = Session::new_project("t", mesh, "test", None, 128).unwrap();
|
||||
|
||||
for fill_mode in [FillMode::UvIsland, FillMode::Mesh] {
|
||||
session.tool.fill_mode = fill_mode;
|
||||
let groups = session.fill_partition(0);
|
||||
assert_eq!(groups.group(0).map(<[u32]>::len), Some(per_plane), "{fill_mode:?}: the whole first plane");
|
||||
assert_eq!(groups.group(per_plane as u32).map(<[u32]>::len), Some(per_plane), "{fill_mode:?}: only the second plane");
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn polygon_mode_groups_the_two_triangles_of_each_quad() {
|
||||
let mut session = fill_session(primitives::plane(2.0, 2));
|
||||
|
||||
session.tool.fill_mode = FillMode::Triangle;
|
||||
assert_eq!(session.fill_partition(0).group(0), Some(&[0][..]));
|
||||
|
||||
session.tool.fill_mode = FillMode::Polygon;
|
||||
let mut quad = session.fill_partition(0).group(0).unwrap().to_vec();
|
||||
quad.sort_unstable();
|
||||
assert_eq!(quad, [0, 1], "the quad's two triangles and no other quad");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_uv_box_over_half_a_plane_fills_that_half() {
|
||||
let mut session = fill_session(primitives::plane(2.0, 4));
|
||||
session.tool.fill_hit_test = FillHitTest::ContainedCenter;
|
||||
|
||||
let filled = session.polygon_fill_box_uv(Vec2::new(-0.01, -0.01), Vec2::new(0.5, 1.01)).unwrap();
|
||||
session.update();
|
||||
|
||||
assert_eq!(filled, 16, "the left two columns of quads");
|
||||
assert!(filled_at(&session, Vec2::new(0.1, 0.5)) && filled_at(&session, Vec2::new(0.45, 0.9)));
|
||||
assert!(!filled_at(&session, Vec2::new(0.55, 0.5)) && !filled_at(&session, Vec2::new(0.9, 0.1)));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn intersection_and_contained_center_differ_on_a_box_missing_a_quads_center() {
|
||||
let mut session = fill_session(primitives::plane(2.0, 2));
|
||||
session.tool.fill_mode = FillMode::Polygon;
|
||||
let (corner, opposite) = (Vec2::new(0.0, 0.0), Vec2::new(0.2, 0.2));
|
||||
|
||||
session.tool.fill_hit_test = FillHitTest::ContainedCenter;
|
||||
assert_eq!(session.polygon_fill_box_uv(corner, opposite).unwrap(), 0, "the quad's center (0.25, 0.25) is outside");
|
||||
assert_ne!(session.undo_label(), Some("Polygon fill"), "an empty box records no undo step");
|
||||
|
||||
session.tool.fill_hit_test = FillHitTest::Intersection;
|
||||
assert_eq!(session.polygon_fill_box_uv(corner, opposite).unwrap(), 2, "the quad the box cuts");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn visible_only_skips_the_back_of_a_cube() {
|
||||
let mut session = fill_session(primitives::cube(1.0));
|
||||
session.camera.yaw = 0.6;
|
||||
session.camera.pitch = 0.4;
|
||||
let (low, high) = (Vec2::ZERO, session.viewport);
|
||||
let every_triangle = session.mesh.triangle_count();
|
||||
|
||||
session.tool.fill_visible_only = true;
|
||||
assert_eq!(session.polygon_fill_box(low, high, session.viewport).unwrap(), every_triangle / 2, "the three sides the camera sees");
|
||||
|
||||
session.tool.fill_visible_only = false;
|
||||
assert_eq!(session.polygon_fill_box(low, high, session.viewport).unwrap(), every_triangle);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn visible_only_sees_through_a_hidden_texture_set() {
|
||||
let mut session = fill_session(primitives::material_ball());
|
||||
let base = session.doc.project.texture_sets.iter().position(|set| set.name == "Base").unwrap();
|
||||
session.active_set = base;
|
||||
let (low, high) = (Vec2::ZERO, session.viewport);
|
||||
|
||||
let behind_the_ball = session.polygon_fill_box(low, high, session.viewport).unwrap();
|
||||
session.doc.project.texture_sets[0].visible = false;
|
||||
let ball_hidden = session.polygon_fill_box(low, high, session.viewport).unwrap();
|
||||
|
||||
assert!(ball_hidden > behind_the_ball, "hiding the ball shows more of the base: {ball_hidden} vs {behind_the_ball}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_dragged_box_fills_live_and_records_one_step_when_it_ends() {
|
||||
let mut session = fill_session(primitives::plane(2.0, 4));
|
||||
let history = session.history_labels().len();
|
||||
|
||||
assert_eq!(session.drag_polygon_fill_box_uv(Vec2::ZERO, Vec2::ONE).unwrap(), 32);
|
||||
assert_eq!(session.drag_polygon_fill_box_uv(Vec2::ZERO, Vec2::new(0.45, 1.0)).unwrap(), 16, "shrinking the box unfills");
|
||||
session.update();
|
||||
assert!(filled_at(&session, Vec2::new(0.2, 0.5)) && !filled_at(&session, Vec2::new(0.8, 0.5)), "the fill shows while dragging");
|
||||
assert_eq!(session.history_labels().len(), history, "no undo step yet");
|
||||
|
||||
assert_eq!(session.end_polygon_fill_box(), 16);
|
||||
assert_eq!(session.history_labels().len(), history + 1);
|
||||
session.undo().unwrap();
|
||||
session.update();
|
||||
assert!(!filled_at(&session, Vec2::new(0.2, 0.5)), "one undo removes the whole drag");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_failed_box_fill_leaves_no_drag_behind() {
|
||||
let mut session = fill_session(primitives::plane(2.0, 4));
|
||||
let layer = session.selected.remove(&0).unwrap();
|
||||
assert!(session.polygon_fill_box_uv(Vec2::ZERO, Vec2::ONE).is_err(), "no layer to paint on");
|
||||
|
||||
session.selected.insert(0, layer);
|
||||
assert_eq!(session.polygon_fill_box_uv(Vec2::ZERO, Vec2::ONE).unwrap(), 32, "the next box fills again");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn undo_and_tool_changes_finish_a_box_drag_first() {
|
||||
let mut session = fill_session(primitives::plane(2.0, 4));
|
||||
let history = session.history_labels().len();
|
||||
|
||||
session.drag_polygon_fill_box_uv(Vec2::ZERO, Vec2::ONE).unwrap();
|
||||
assert_eq!(session.undo().unwrap(), "Polygon fill", "undo takes back the drag it finished");
|
||||
assert!(session.polygon_fill_drag.is_none());
|
||||
assert_eq!(session.history_labels().len(), history);
|
||||
|
||||
session.drag_polygon_fill_box_uv(Vec2::ZERO, Vec2::ONE).unwrap();
|
||||
crate::tool_cmds::set_tool(&mut session, Tool::Paint).unwrap();
|
||||
assert!(session.polygon_fill_drag.is_none());
|
||||
assert_eq!(session.history_labels().len(), history + 1, "a tool change keeps the fill as one step");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn an_unmoved_box_keeps_its_fill() {
|
||||
let mut session = fill_session(primitives::plane(2.0, 4));
|
||||
let narrow_box = Vec2::new(0.3, 1.0);
|
||||
assert_eq!(session.drag_polygon_fill_box_uv(Vec2::ZERO, narrow_box).unwrap(), 16, "intersection: the two columns the box touches");
|
||||
|
||||
// Contained center would select one column, so a second selection would show 8
|
||||
session.tool.fill_hit_test = FillHitTest::ContainedCenter;
|
||||
assert_eq!(session.drag_polygon_fill_box_uv(Vec2::ZERO, narrow_box).unwrap(), 16, "the same box selects nothing again");
|
||||
assert_eq!(session.drag_polygon_fill_box_uv(Vec2::ZERO, narrow_box + Vec2::new(0.01, 0.0)).unwrap(), 8, "a moved box selects again");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_uv_box_over_the_second_uv_tile_fills_that_tile_only() {
|
||||
let mut session = fill_session(primitives::udim_plane());
|
||||
assert_eq!(session.doc.project.texture_sets[0].uv_tiles, [1001, 1002]);
|
||||
session.tool.fill_hit_test = FillHitTest::ContainedCenter;
|
||||
|
||||
let every_triangle = session.mesh.triangle_count();
|
||||
assert_eq!(session.polygon_fill_box_uv(Vec2::new(0.5, 0.0), Vec2::ONE).unwrap(), every_triangle / 2, "the atlas's right half is tile 1002");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_2d_click_skips_a_triangle_with_collapsed_uvs() {
|
||||
// A face left unmapped (all corners at UV 0,0) comes first, as imports often leave them
|
||||
let plane = primitives::plane(2.0, 1);
|
||||
let mut positions = vec![Vec3::ZERO, Vec3::X, Vec3::Z];
|
||||
let mut uvs = vec![Vec2::ZERO; 3];
|
||||
positions.extend(&plane.positions);
|
||||
uvs.extend(&plane.uvs);
|
||||
let indices = [0, 1, 2].into_iter().chain(plane.indices.iter().map(|index| index + 3)).collect();
|
||||
let mut session = fill_session(Mesh::from_parts(positions, None, uvs, indices, "m").unwrap());
|
||||
|
||||
assert_eq!(session.polygon_fill_uv(Vec2::new(0.2, 0.7)).unwrap(), 1);
|
||||
session.update();
|
||||
assert!(filled_at(&session, Vec2::new(0.2, 0.7)), "the triangle under the cursor, not the collapsed one");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_failing_drag_reports_once_and_records_nothing() {
|
||||
let mut session = fill_session(primitives::plane(2.0, 4));
|
||||
let history = session.history_labels().len();
|
||||
session.selected.clear();
|
||||
|
||||
assert!(session.drag_polygon_fill_box_uv(Vec2::ZERO, Vec2::new(0.5, 1.0)).is_err());
|
||||
assert_eq!(session.drag_polygon_fill_box_uv(Vec2::ZERO, Vec2::ONE).unwrap(), 0, "the rest of the drag fills nothing");
|
||||
assert_eq!(session.end_polygon_fill_box(), 0);
|
||||
assert_eq!(session.history_labels().len(), history);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn an_edit_during_a_drag_records_the_fill_first() {
|
||||
let mut session = fill_session(primitives::plane(2.0, 4));
|
||||
session.drag_polygon_fill_box_uv(Vec2::ZERO, Vec2::ONE).unwrap();
|
||||
|
||||
let layers = session.doc.project.layers.len();
|
||||
crate::execute(&mut session, "layer.add.paint", &serde_json::Value::Null).unwrap();
|
||||
assert!(session.polygon_fill_drag.is_none());
|
||||
let labels = session.history_labels();
|
||||
assert_eq!(labels.get(labels.len().wrapping_sub(2)).map(String::as_str), Some("Polygon fill"), "{labels:?}");
|
||||
|
||||
session.drag_polygon_fill_box_uv(Vec2::ZERO, Vec2::new(0.45, 1.0)).unwrap();
|
||||
assert_eq!(session.doc.project.layers.len(), layers + 1, "a later drag move keeps the added layer");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_zero_size_box_on_whole_pixels_selects_what_is_under_it() {
|
||||
let mut session = fill_session(primitives::cube(1.0));
|
||||
let center = (session.viewport * 0.5).floor();
|
||||
|
||||
assert!(session.polygon_fill_box(center, center, session.viewport).unwrap() > 0);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_camera_move_mid_drag_keeps_one_drag() {
|
||||
let mut session = fill_session(primitives::cube(1.0));
|
||||
let viewport = session.viewport;
|
||||
let history = session.history_labels().len();
|
||||
|
||||
let (corner, opposite) = (viewport * 0.4, viewport * 0.6);
|
||||
|
||||
let before_zoom = session.drag_polygon_fill_box(corner, opposite, viewport).unwrap();
|
||||
session.camera.zoom(0.5);
|
||||
let after_zoom = session.drag_polygon_fill_box(corner, opposite, viewport).unwrap();
|
||||
session.end_polygon_fill_box();
|
||||
|
||||
assert_ne!(before_zoom, after_zoom, "the same box selects again from the new camera");
|
||||
assert_eq!(session.history_labels().len(), history + 1, "a wheel zoom during the drag doesn't split it");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn pixel_spans_include_both_edges_and_nothing_outside() {
|
||||
assert_eq!(super::pixel_span(2.0, 2.0, 100), 2..3, "a zero-size span on a whole pixel");
|
||||
assert_eq!(super::pixel_span(-50.0, -10.0, 100), 0..0, "before the first pixel");
|
||||
assert_eq!(super::pixel_span(120.0, 150.0, 100), 100..100, "past the last pixel");
|
||||
assert_eq!(super::pixel_span(-5.0, 500.0, 100), 0..100);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_2d_click_fills_the_triangle_under_it() {
|
||||
let mut session = fill_session(primitives::plane(2.0, 1));
|
||||
|
||||
assert_eq!(session.polygon_fill_uv(Vec2::new(0.2, 0.7)).unwrap(), 1);
|
||||
session.update();
|
||||
|
||||
assert!(filled_at(&session, Vec2::new(0.2, 0.7)));
|
||||
assert!(!filled_at(&session, Vec2::new(0.7, 0.2)), "the quad's other triangle stays");
|
||||
assert!(session.polygon_fill_uv(Vec2::new(1.5, 0.5)).is_err(), "nothing outside the UVs");
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,42 @@
|
||||
//! A polygon fill box being dragged: what it filled so far and what it needs to refill each move.
|
||||
|
||||
use std::collections::{BTreeMap, BTreeSet};
|
||||
|
||||
use texturecraft_core::LayerId;
|
||||
use texturecraft_geom::OrbitCamera;
|
||||
use texturecraft_geom::glam::Vec2;
|
||||
use texturecraft_paint::EyeDepth;
|
||||
use texturecraft_texel::TileImage;
|
||||
|
||||
use crate::session::{Document, StackTarget};
|
||||
use crate::triangle_partition::TrianglePartition;
|
||||
|
||||
/// A polygon fill box being dragged: the fill shows live and becomes one undo step when the drag ends
|
||||
pub(crate) struct PolygonFillDrag {
|
||||
/// The texture set it fills
|
||||
pub ts: usize,
|
||||
/// The selected layer and content, mask or effect being filled
|
||||
pub target: (Option<LayerId>, StackTarget),
|
||||
/// The 3D view's size in pixels, or None for a drag in the 2D view
|
||||
pub viewport: Option<Vec2>,
|
||||
/// The camera [`PolygonFillDrag::points`] and [`PolygonFillDrag::depth`] were made with
|
||||
pub camera: OrbitCamera,
|
||||
/// The document before the drag, refilled each time the selection changes
|
||||
pub before: Document,
|
||||
/// The quick mask's coverage before the drag, when the drag paints the quick mask
|
||||
pub quick_mask_before: Option<BTreeMap<usize, TileImage>>,
|
||||
/// Each vertex where the box sees it: viewport pixels in the 3D view (None behind the camera), texture coordinates in the 2D view
|
||||
pub points: Vec<Option<Vec2>>,
|
||||
/// What the camera sees (3D view, visible polygons only)
|
||||
pub depth: Option<EyeDepth>,
|
||||
/// What the fill mode fills together
|
||||
pub fill_groups: TrianglePartition,
|
||||
/// The polygons the box tests, when they differ from the fill groups
|
||||
pub polygons: Option<TrianglePartition>,
|
||||
/// The triangles filled so far
|
||||
pub filled: BTreeSet<u32>,
|
||||
/// The box last shown, lowest corner first: an unmoved box isn't selected again
|
||||
pub last_box: Option<(Vec2, Vec2)>,
|
||||
/// The fill failed (reported once): the rest of the drag fills nothing
|
||||
pub failed: bool,
|
||||
}
|
||||
@@ -1,14 +1,8 @@
|
||||
//! Shelf previews: built-in materials evaluated on a unit sphere seen from +Z, without a mesh or
|
||||
//! baked maps (generators that need mesh maps are approximated with world-space noise), and
|
||||
//! library filters. Cheap enough for lazily rendered thumbnails. Smart masks have their own baked
|
||||
//! preview ([`crate::mask_preview`]).
|
||||
//! Cheap shelf previews on a unit sphere: plain materials and library filters (smart ones use [`crate::orb_preview`])
|
||||
|
||||
use rayon::prelude::*;
|
||||
use texturecraft_compose::pattern::{Coords, procedural, world_noise};
|
||||
use texturecraft_core::{
|
||||
Channel, Effect, EffectKind, Fill, Filter, Generator, GeneratorKind, Layer, LayerKind, Mask, MaskBackground, Procedural, ProceduralKind, Project,
|
||||
Projection, Source, TextureSet, blend1,
|
||||
};
|
||||
use texturecraft_compose::pattern::{Coords, procedural};
|
||||
use texturecraft_core::{Channel, Effect, EffectKind, Fill, Filter, Layer, LayerKind, Procedural, ProceduralKind, Project, Projection, Source, TextureSet};
|
||||
use texturecraft_geom::glam::{Vec2, Vec3};
|
||||
|
||||
use crate::materials::{Builder, build};
|
||||
@@ -50,54 +44,13 @@ fn source(s: &Source, proj: &Projection, c: &Coords) -> Option<[f32; 3]> {
|
||||
}
|
||||
}
|
||||
|
||||
/// Approximate generator: mesh-map signals become world noise (a sphere has no edges or cavities).
|
||||
fn generator(g: &Generator, c: &Coords) -> f32 {
|
||||
let dir = Vec3::from(g.direction).try_normalize().unwrap_or(Vec3::Y);
|
||||
let wear = (world_noise(c.pos, 3.0, 91) - 0.5) * 2.2;
|
||||
let cavity = (world_noise(c.pos, 3.0, 57) - 0.3).clamp(0.0, 1.0) + (1.0 - c.nrm.y) * 0.1;
|
||||
let s = match g.kind {
|
||||
GeneratorKind::Position => c.pos.dot(dir) * 0.5 + 0.5,
|
||||
GeneratorKind::Direction => c.nrm.dot(dir) * 0.5 + 0.5,
|
||||
GeneratorKind::EdgeWear => wear,
|
||||
GeneratorKind::Curvature => 0.5 + wear * 0.5,
|
||||
GeneratorKind::AmbientOcclusion => 1.0 - cavity,
|
||||
_ => cavity,
|
||||
};
|
||||
// Same thresholding as the compositor.
|
||||
let s = if g.noise_amount > 0.0 { s + (world_noise(c.pos, g.noise_scale, g.seed) - 0.5) * g.noise_amount } else { s };
|
||||
let soft = g.softness.max(1e-3);
|
||||
let t = ((s - (1.0 - g.level.clamp(0.0, 1.0) - soft)) / (2.0 * soft)).clamp(0.0, 1.0);
|
||||
let v = t * t * (3.0 - 2.0 * t);
|
||||
if g.invert { 1.0 - v } else { v }
|
||||
}
|
||||
|
||||
fn mask(m: &Mask, c: &Coords) -> f32 {
|
||||
if !m.enabled {
|
||||
return 1.0;
|
||||
}
|
||||
let mut v = if m.background == MaskBackground::White { 1.0 } else { 0.0 };
|
||||
for e in m.effects.iter().filter(|e| e.visible) {
|
||||
let val = match &e.kind {
|
||||
EffectKind::Fill { source: s, projection } => source(s, projection, c).map(|x| x[0]),
|
||||
EffectKind::Generator(g) => Some(generator(g, c)),
|
||||
EffectKind::Levels(l) => Some(l.apply(v)),
|
||||
EffectKind::Filter(Filter::Invert) => Some(1.0 - v),
|
||||
_ => None,
|
||||
};
|
||||
if let Some(val) = val {
|
||||
let blended = if matches!(e.kind, EffectKind::Levels(_) | EffectKind::Filter(_)) { val } else { blend1(e.blend, v, val) };
|
||||
v += (blended - v) * e.opacity.clamp(0.0, 1.0);
|
||||
}
|
||||
}
|
||||
v.clamp(0.0, 1.0)
|
||||
}
|
||||
|
||||
const CHANNELS: [Channel; 4] = [Channel::BaseColor, Channel::Metallic, Channel::Roughness, Channel::Height];
|
||||
|
||||
/// Preview of built-in material `id` (None for an unknown id).
|
||||
/// Preview of plain material `id` (None for an unknown id or a smart material, whose masks need mesh maps)
|
||||
pub fn material(id: &str, size: usize) -> Option<Vec<Option<Sample>>> {
|
||||
let plain = crate::materials::find(id).filter(|found| !found.smart)?;
|
||||
let mut project = Project::new("preview", "");
|
||||
let layers = build(&mut Builder { p: &mut project, channels: CHANNELS.to_vec() }, id).ok()?;
|
||||
let layers = build(&mut Builder { p: &mut project, channels: CHANNELS.to_vec() }, plain.id).ok()?;
|
||||
|
||||
// Pixels evaluate independently and big previews take long on one core
|
||||
let normals: Vec<_> = sphere_normals(size).collect();
|
||||
@@ -106,23 +59,24 @@ pub fn material(id: &str, size: usize) -> Option<Vec<Option<Sample>>> {
|
||||
.map(|normal| {
|
||||
let at = coords(normal?);
|
||||
let mut values = CHANNELS.map(Channel::default_value);
|
||||
for layer in layers.iter().filter(|l| l.visible) {
|
||||
for layer in layers.iter().filter(|layer| layer.visible) {
|
||||
// Plain materials are unmasked fills
|
||||
let LayerKind::Fill(fill) = &layer.kind else { continue };
|
||||
|
||||
let coverage = layer.mask.as_ref().map_or(1.0, |m| mask(m, &at));
|
||||
for (value, channel) in values.iter_mut().zip(CHANNELS) {
|
||||
let layer_value = fill.sources.get(&channel).and_then(|s| source(s, &fill.projection, &at));
|
||||
let layer_value = fill.sources.get(&channel).and_then(|channel_source| source(channel_source, &fill.projection, &at));
|
||||
if let (Some(blend), Some(layer_value)) = (layer.blend(channel), layer_value) {
|
||||
let weight = coverage * blend.opacity.clamp(0.0, 1.0);
|
||||
*value = [0, 1, 2].map(|k| value[k] + (layer_value[k] - value[k]) * weight);
|
||||
let weight = blend.opacity.clamp(0.0, 1.0);
|
||||
*value = [0, 1, 2].map(|component| value[component] + (layer_value[component] - value[component]) * weight);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
let [base, metal, rough, height] = values;
|
||||
Some(Sample { base, metallic: metal[0], roughness: rough[0], height: height[0] })
|
||||
let [base, metallic, roughness, height] = values;
|
||||
Some(Sample { base, metallic: metallic[0], roughness: roughness[0], height: height[0] })
|
||||
})
|
||||
.collect();
|
||||
|
||||
Some(samples)
|
||||
}
|
||||
|
||||
@@ -196,21 +150,40 @@ pub fn filter(id: &str, size: usize) -> Option<Vec<Option<Sample>>> {
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
/// Whether every value of `sample` is finite
|
||||
fn finite(sample: &Sample) -> bool {
|
||||
sample.base.into_iter().chain([sample.metallic, sample.roughness, sample.height]).all(f32::is_finite)
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn previews_cover_the_sphere_with_finite_values() {
|
||||
for m in crate::materials::MATERIALS {
|
||||
let px = material(m.id, 16).unwrap_or_else(|| panic!("{}", m.id));
|
||||
let center = px[8 * 16 + 8].unwrap_or_else(|| panic!("{}", m.id));
|
||||
assert!(center.base.iter().chain([¢er.metallic, ¢er.roughness, ¢er.height]).all(|v| v.is_finite()), "{}", m.id);
|
||||
assert!(px[0].is_none(), "corners are outside the sphere");
|
||||
let size = 16;
|
||||
for built_in in crate::materials::MATERIALS {
|
||||
let id = built_in.id;
|
||||
if built_in.smart {
|
||||
assert!(material(id, size).is_none(), "{id}: smart materials preview on the orb");
|
||||
continue;
|
||||
}
|
||||
|
||||
let mut project = Project::new("preview", "");
|
||||
let layers = build(&mut Builder { p: &mut project, channels: CHANNELS.to_vec() }, id).unwrap();
|
||||
assert!(layers.iter().all(|layer| layer.mask.is_none()), "{id}: the sphere preview shows no masks");
|
||||
|
||||
let pixels = material(id, size).unwrap_or_else(|| panic!("{id}"));
|
||||
let center = pixels[size / 2 * size + size / 2].unwrap_or_else(|| panic!("{id}"));
|
||||
assert!(finite(¢er), "{id}");
|
||||
assert!(pixels[0].is_none(), "corners are outside the sphere");
|
||||
}
|
||||
assert!(material("nope", 8).is_none() && filter("nope", 8).is_none());
|
||||
for f in crate::filter_lib::FILTERS {
|
||||
let px = filter(f.id, 24).unwrap_or_else(|| panic!("{}", f.id));
|
||||
let center = px[12 * 24 + 12].unwrap_or_else(|| panic!("{}", f.id));
|
||||
assert!(center.base.iter().chain([¢er.roughness, ¢er.height]).all(|v| v.is_finite()), "{}", f.id);
|
||||
assert!(material("nope", size).is_none() && filter("nope", size).is_none());
|
||||
|
||||
let size = 24;
|
||||
for library_filter in crate::filter_lib::FILTERS {
|
||||
let id = library_filter.id;
|
||||
let pixels = filter(id, size).unwrap_or_else(|| panic!("{id}"));
|
||||
let center = pixels[size / 2 * size + size / 2].unwrap_or_else(|| panic!("{id}"));
|
||||
assert!(finite(¢er), "{id}");
|
||||
}
|
||||
let (plain, warped) = (filter("levels", 24).unwrap(), filter("warp", 24).unwrap());
|
||||
let (plain, warped) = (filter("levels", size).unwrap(), filter("warp", size).unwrap());
|
||||
assert!(plain != warped, "the warp shows in its preview");
|
||||
}
|
||||
}
|
||||
@@ -11,6 +11,7 @@ use texturecraft_geom::{Bvh, Mesh, OrbitCamera, UvGBuffer};
|
||||
use texturecraft_paint::{BrushSettings, EyeDepth, Stroke, StrokeCanvas};
|
||||
use texturecraft_texel::DilationMap;
|
||||
|
||||
use crate::fill_mode::FillMode;
|
||||
use crate::{EngineError, Result};
|
||||
|
||||
/// Padding (texels) applied to composites for display.
|
||||
@@ -160,15 +161,6 @@ impl ViewMode {
|
||||
}
|
||||
}
|
||||
|
||||
/// Polygon fill granularity.
|
||||
#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize, Default)]
|
||||
pub enum FillMode {
|
||||
#[default]
|
||||
Triangle,
|
||||
UvIsland,
|
||||
Mesh,
|
||||
}
|
||||
|
||||
/// A screen-pinned image for the Projection tool (a stencil).
|
||||
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
|
||||
pub struct StencilState {
|
||||
@@ -210,6 +202,12 @@ pub struct ToolState {
|
||||
/// Gray painted into masks.
|
||||
pub mask_value: f32,
|
||||
pub fill_mode: FillMode,
|
||||
/// How a polygon fill box decides which polygons it selects
|
||||
#[serde(default)]
|
||||
pub fill_hit_test: crate::fill_hit_test::FillHitTest,
|
||||
/// Polygon fill boxes in the 3D view select only the polygons the camera sees
|
||||
#[serde(default = "default_fill_visible_only")]
|
||||
pub fill_visible_only: bool,
|
||||
/// Stencil used by the Projection tool.
|
||||
#[serde(default)]
|
||||
pub stencil: Option<StencilState>,
|
||||
@@ -231,6 +229,10 @@ fn default_smudge_strength() -> f32 {
|
||||
0.5
|
||||
}
|
||||
|
||||
fn default_fill_visible_only() -> bool {
|
||||
true
|
||||
}
|
||||
|
||||
/// What the Clone tool copies (the clone source modes).
|
||||
#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize, Default)]
|
||||
pub enum CloneFrom {
|
||||
@@ -260,6 +262,8 @@ impl Default for ToolState {
|
||||
enabled: [Channel::BaseColor, Channel::Metallic, Channel::Roughness, Channel::Height, Channel::Normal].into_iter().collect(),
|
||||
mask_value: 1.0,
|
||||
fill_mode: FillMode::Triangle,
|
||||
fill_hit_test: Default::default(),
|
||||
fill_visible_only: default_fill_visible_only(),
|
||||
stencil: None,
|
||||
smudge_strength: default_smudge_strength(),
|
||||
clone_source: None,
|
||||
@@ -291,8 +295,8 @@ pub(crate) struct ActiveStroke {
|
||||
pub canvas: StrokeCanvas,
|
||||
/// Camera visibility for 3D strokes (None for strokes in the 2D view).
|
||||
pub depth: Option<Arc<EyeDepth>>,
|
||||
/// 2D view strokes: last UV point and the distance carried to the next stamp.
|
||||
pub uv: Option<(Option<Vec2>, f32)>,
|
||||
/// 2D view strokes: where the stroke is between samples.
|
||||
pub uv: Option<crate::uv_stroke_state::UvStrokeState>,
|
||||
pub camera: OrbitCamera,
|
||||
pub viewport: Vec2,
|
||||
pub values: BTreeMap<Channel, [f32; 3]>,
|
||||
@@ -356,6 +360,8 @@ pub struct Session {
|
||||
/// The last stroke's camera visibility buffer: reused while the camera, view size and mesh
|
||||
/// are unchanged, so back-to-back dabs start instantly.
|
||||
pub(crate) depth_cache: Option<DepthCache>,
|
||||
/// The polygon fill box being dragged
|
||||
pub(crate) polygon_fill_drag: Option<crate::polygon_fill_drag::PolygonFillDrag>,
|
||||
/// The user's export presets (kept when another project opens).
|
||||
pub export_presets: crate::preset_cmds::UserPresets,
|
||||
/// The user's project templates (kept when another project opens).
|
||||
@@ -405,6 +411,7 @@ impl Session {
|
||||
revision: 1,
|
||||
log: Vec::new(),
|
||||
depth_cache: None,
|
||||
polygon_fill_drag: None,
|
||||
export_presets: Default::default(),
|
||||
templates: Default::default(),
|
||||
})
|
||||
@@ -489,22 +496,24 @@ impl Session {
|
||||
self.edit_merging(label, self.merge_edits, f)
|
||||
}
|
||||
|
||||
/// [`Session::edit`] that, with `merge`, continues the previous undo step when it has the
|
||||
/// same label (a drag in the viewport is one step however many updates it makes).
|
||||
pub fn edit_merging<T>(&mut self, label: &str, merge: bool, f: impl FnOnce(&mut Session) -> Result<T>) -> Result<T> {
|
||||
/// [`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> {
|
||||
// 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 = f(self).and_then(|v| match self.doc.project.instance_cycle() {
|
||||
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(v),
|
||||
None => Ok(value),
|
||||
});
|
||||
match result {
|
||||
Ok(v) => {
|
||||
Ok(value) => {
|
||||
self.record(label, before, merge);
|
||||
Ok(v)
|
||||
Ok(value)
|
||||
}
|
||||
Err(e) => {
|
||||
Err(error) => {
|
||||
self.doc = before;
|
||||
Err(e)
|
||||
Err(error)
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -530,7 +539,7 @@ impl Session {
|
||||
|
||||
/// Mark dirty every texture set whose composite differs between `other` and the current
|
||||
/// document (after an edit, undo or redo).
|
||||
fn invalidate_changed(&mut self, other: &Document) {
|
||||
pub(crate) fn invalidate_changed(&mut self, other: &Document) {
|
||||
self.follow_uv_layouts(&other.project);
|
||||
self.sync_caches();
|
||||
let resources = |d: &Document| d.resources.iter().map(|(n, b)| (n.clone(), Arc::as_ptr(b))).collect::<Vec<_>>();
|
||||
@@ -625,25 +634,29 @@ impl Session {
|
||||
}
|
||||
|
||||
pub fn undo(&mut self) -> Result<String> {
|
||||
// A stroke, a box fill or an edited path under way would otherwise write over the restored document
|
||||
self.cancel_stroke();
|
||||
// An edited path would otherwise repaint over the restored document.
|
||||
self.end_polygon_fill_box();
|
||||
self.stop_path_edit();
|
||||
let (label, doc) = self.undo.pop().ok_or_else(|| EngineError::Other("nothing to undo".into()))?;
|
||||
let now = std::mem::replace(&mut self.doc, doc);
|
||||
self.after_history(&now);
|
||||
self.redo.push((label.clone(), now));
|
||||
|
||||
let (label, restored) = self.undo.pop().ok_or_else(|| EngineError::Other("nothing to undo".into()))?;
|
||||
let current = std::mem::replace(&mut self.doc, restored);
|
||||
self.after_history(¤t);
|
||||
self.redo.push((label.clone(), current));
|
||||
self.sync_images();
|
||||
Ok(label)
|
||||
}
|
||||
|
||||
pub fn redo(&mut self) -> Result<String> {
|
||||
// A stroke, a box fill or an edited path under way would otherwise write over the restored document
|
||||
self.cancel_stroke();
|
||||
// An edited path would otherwise repaint over the restored document.
|
||||
self.end_polygon_fill_box();
|
||||
self.stop_path_edit();
|
||||
let (label, doc) = self.redo.pop().ok_or_else(|| EngineError::Other("nothing to redo".into()))?;
|
||||
let now = std::mem::replace(&mut self.doc, doc);
|
||||
self.after_history(&now);
|
||||
self.undo.push((label.clone(), now));
|
||||
|
||||
let (label, restored) = self.redo.pop().ok_or_else(|| EngineError::Other("nothing to redo".into()))?;
|
||||
let current = std::mem::replace(&mut self.doc, restored);
|
||||
self.after_history(¤t);
|
||||
self.undo.push((label.clone(), current));
|
||||
self.sync_images();
|
||||
Ok(label)
|
||||
}
|
||||
|
||||
@@ -62,14 +62,14 @@ pub fn find(name: &str) -> Option<&'static SmartMask> {
|
||||
|
||||
const UP: [f32; 3] = [0.0, 1.0, 0.0];
|
||||
|
||||
/// A mesh-map generator with explicit threshold, softness and noise breakup.
|
||||
/// A mesh-map generator with explicit threshold, softness and noise breakup (curvature as baked, without detail sizes).
|
||||
pub(crate) fn generator(kind: GeneratorKind, level: f32, softness: f32, noise: f32) -> EffectKind {
|
||||
EffectKind::Generator(Generator { level, softness, noise_amount: noise, ..Generator::new(kind) })
|
||||
EffectKind::Generator(Generator { level, softness, noise_amount: noise, detail: None, ..Generator::new(kind) })
|
||||
}
|
||||
|
||||
/// A direction or position generator (`invert` flips the result).
|
||||
pub(crate) fn directional(kind: GeneratorKind, direction: [f32; 3], level: f32, softness: f32, noise: f32, invert: bool) -> EffectKind {
|
||||
EffectKind::Generator(Generator { level, softness, noise_amount: noise, direction, invert, ..Generator::new(kind) })
|
||||
EffectKind::Generator(Generator { level, softness, noise_amount: noise, direction, invert, detail: None, ..Generator::new(kind) })
|
||||
}
|
||||
|
||||
/// A triplanar grayscale pattern fill.
|
||||
|
||||
@@ -7,7 +7,9 @@ use texturecraft_geom::glam::Vec2;
|
||||
use texturecraft_paint::{Alignment, BrushAlpha, alphas};
|
||||
|
||||
use crate::commands::{CommandSpec, always, bad, boolp, channel_param, color_param, f32p, strp};
|
||||
use crate::session::{CloneFrom, CloneSource, FillMode, Tool};
|
||||
use crate::fill_hit_test::FillHitTest;
|
||||
use crate::fill_mode::FillMode;
|
||||
use crate::session::{CloneFrom, CloneSource, Tool};
|
||||
use crate::{Result, Session, cmd};
|
||||
|
||||
pub fn specs() -> Vec<CommandSpec> {
|
||||
@@ -69,7 +71,16 @@ pub fn specs() -> Vec<CommandSpec> {
|
||||
always,
|
||||
clone_source
|
||||
),
|
||||
cmd!("tool.fillMode", "Polygon fill mode", [], None, "{mode: triangle|uvIsland|mesh}", always, fill_mode),
|
||||
cmd!("tool.fillMode", "Polygon fill mode", [], None, "{mode: triangle|polygon|uvIsland|mesh}", always, fill_mode),
|
||||
cmd!(
|
||||
"tool.fillSelection",
|
||||
"Polygon fill selection",
|
||||
[],
|
||||
None,
|
||||
"{hitTest?: intersection|containedCenter (a box selects polygons it touches, or whose center it holds), visibleOnly?: bool (3D view boxes select only what the camera sees)}",
|
||||
always,
|
||||
fill_selection
|
||||
),
|
||||
cmd!("tool.stroke", "Paint stroke", [], None, "{points: [[x,y],...] viewport pixels, viewport?: [w,h]} — paints with the current tool", always, stroke),
|
||||
cmd!(
|
||||
"tool.strokeUv",
|
||||
@@ -80,16 +91,26 @@ pub fn specs() -> Vec<CommandSpec> {
|
||||
always,
|
||||
stroke_uv
|
||||
),
|
||||
cmd!("tool.click", "Tool click", [], None, "{x, y, viewport?: [w,h]} — polygon fill / color picker / single dab", always, click),
|
||||
cmd!(
|
||||
"tool.click",
|
||||
"Tool click",
|
||||
[],
|
||||
None,
|
||||
"{x, y, viewport?: [w,h]} — polygon fill / color picker / single dab; polygon fill also takes a box {x0, y0, x1, y1, viewport?}, a 2D view point {uv: [u,v]} or a 2D view box {uv0: [u,v], uv1: [u,v]}",
|
||||
always,
|
||||
click
|
||||
),
|
||||
cmd!("tool.state", "Tool state", [], None, "{}", always, |s, _| Ok(serde_json::to_value(&s.tool).unwrap_or(Value::Null))),
|
||||
]
|
||||
}
|
||||
|
||||
pub(crate) fn set_tool(s: &mut Session, t: Tool) -> Result<Value> {
|
||||
s.cancel_stroke();
|
||||
s.tool.tool = t;
|
||||
s.revision = s.revision.wrapping_add(1);
|
||||
Ok(json!({ "tool": t.id() }))
|
||||
pub(crate) fn set_tool(session: &mut Session, tool: Tool) -> Result<Value> {
|
||||
session.cancel_stroke();
|
||||
// A box fill under way keeps what it filled as one undo step
|
||||
session.end_polygon_fill_box();
|
||||
session.tool.tool = tool;
|
||||
session.revision = session.revision.wrapping_add(1);
|
||||
Ok(json!({ "tool": tool.id() }))
|
||||
}
|
||||
|
||||
fn select(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
@@ -319,13 +340,29 @@ fn clone_source(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
Ok(serde_json::to_value(s.tool.clone_source).unwrap_or(Value::Null))
|
||||
}
|
||||
|
||||
fn fill_mode(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
s.tool.fill_mode = match strp(p, "mode").unwrap_or("triangle") {
|
||||
fn fill_mode(session: &mut Session, params: &Value) -> Result<Value> {
|
||||
session.tool.fill_mode = match strp(params, "mode").unwrap_or("triangle") {
|
||||
"triangle" => FillMode::Triangle,
|
||||
"polygon" => FillMode::Polygon,
|
||||
"uvIsland" | "island" => FillMode::UvIsland,
|
||||
"mesh" => FillMode::Mesh,
|
||||
other => return Err(bad("tool.fillMode", format!("unknown fill mode `{other}`"))),
|
||||
};
|
||||
|
||||
Ok(Value::Null)
|
||||
}
|
||||
|
||||
fn fill_selection(session: &mut Session, params: &Value) -> Result<Value> {
|
||||
match strp(params, "hitTest") {
|
||||
None => {}
|
||||
Some("intersection") => session.tool.fill_hit_test = FillHitTest::Intersection,
|
||||
Some("containedCenter") => session.tool.fill_hit_test = FillHitTest::ContainedCenter,
|
||||
Some(other) => return Err(bad("tool.fillSelection", format!("unknown hit-test `{other}` (intersection or containedCenter)"))),
|
||||
}
|
||||
if let Some(visible_only) = boolp(params, "visibleOnly") {
|
||||
session.tool.fill_visible_only = visible_only;
|
||||
}
|
||||
|
||||
Ok(Value::Null)
|
||||
}
|
||||
|
||||
@@ -369,22 +406,48 @@ fn stroke(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
Ok(json!({ "stamps": stamps }))
|
||||
}
|
||||
|
||||
fn click(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
let (Some(x), Some(y)) = (f32p(p, "x"), f32p(p, "y")) else { return Err(bad("tool.click", "`x` and `y` are required")) };
|
||||
let vp = viewport_of(s, p);
|
||||
let out = match s.tool.tool {
|
||||
Tool::PolygonFill => json!({ "triangles": s.polygon_fill(Vec2::new(x, y), vp)? }),
|
||||
fn click(session: &mut Session, params: &Value) -> Result<Value> {
|
||||
if session.tool.tool == Tool::PolygonFill
|
||||
&& let Some(triangles) = polygon_fill_click(session, params)?
|
||||
{
|
||||
session.update();
|
||||
return Ok(json!({ "triangles": triangles }));
|
||||
}
|
||||
|
||||
let (Some(x), Some(y)) = (f32p(params, "x"), f32p(params, "y")) else { return Err(bad("tool.click", "`x` and `y` are required")) };
|
||||
|
||||
let point = Vec2::new(x, y);
|
||||
let viewport = viewport_of(session, params);
|
||||
let out = match session.tool.tool {
|
||||
Tool::PolygonFill => json!({ "triangles": session.polygon_fill(point, viewport)? }),
|
||||
Tool::ColorPicker => {
|
||||
let v = s.color_pick(Vec2::new(x, y), vp)?;
|
||||
json!(v.iter().map(|(c, v)| (c.id().to_string(), json!(v))).collect::<serde_json::Map<_, _>>())
|
||||
let picked = session.color_pick(point, viewport)?;
|
||||
json!(picked.iter().map(|(channel, value)| (channel.id().to_string(), json!(value))).collect::<serde_json::Map<_, _>>())
|
||||
}
|
||||
Tool::GeometryMask => crate::instance_cmds::toggle_part_at(s, Vec2::new(x, y), vp)?,
|
||||
_ => json!({ "stamps": s.stroke_points(&[Vec2::new(x, y)], vp)? }),
|
||||
Tool::GeometryMask => crate::instance_cmds::toggle_part_at(session, point, viewport)?,
|
||||
_ => json!({ "stamps": session.stroke_points(&[point], viewport)? }),
|
||||
};
|
||||
s.update();
|
||||
session.update();
|
||||
Ok(out)
|
||||
}
|
||||
|
||||
/// The polygon fill forms of `tool.click` besides a plain `{x, y}` point: None for that point
|
||||
fn polygon_fill_click(session: &mut Session, params: &Value) -> Result<Option<usize>> {
|
||||
let screen_box = (f32p(params, "x0"), f32p(params, "y0"), f32p(params, "x1"), f32p(params, "y1"));
|
||||
let given = |keys: &[&str]| keys.iter().any(|key| params.get(*key).is_some());
|
||||
let filled = match (pair(params, "uv0"), pair(params, "uv1"), pair(params, "uv"), screen_box) {
|
||||
(Some(corner), Some(opposite), ..) => session.polygon_fill_box_uv(corner.into(), opposite.into())?,
|
||||
_ if given(&["uv0", "uv1"]) => return Err(bad("tool.click", "a UV box needs `uv0` and `uv1` as [u, v]")),
|
||||
(_, _, Some(uv), _) => session.polygon_fill_uv(uv.into())?,
|
||||
_ if given(&["uv"]) => return Err(bad("tool.click", "a 2D view point needs `uv` as [u, v]")),
|
||||
(.., (Some(x0), Some(y0), Some(x1), Some(y1))) => session.polygon_fill_box(Vec2::new(x0, y0), Vec2::new(x1, y1), viewport_of(session, params))?,
|
||||
_ if given(&["x0", "y0", "x1", "y1"]) => return Err(bad("tool.click", "a screen box needs numbers `x0`, `y0`, `x1` and `y1`")),
|
||||
_ => return Ok(None),
|
||||
};
|
||||
|
||||
Ok(Some(filled))
|
||||
}
|
||||
|
||||
fn stroke_uv(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
let points = points_param("tool.strokeUv", p, "points")?.ok_or_else(|| bad("tool.strokeUv", "`points` must be an array of [u, v]"))?;
|
||||
let tiles = s.stroke_uv_points(&points)?;
|
||||
|
||||
@@ -0,0 +1,123 @@
|
||||
//! Triangles of one material grouped into the pieces polygon fill selects and fills.
|
||||
|
||||
use std::collections::HashMap;
|
||||
use std::hash::Hash;
|
||||
|
||||
use texturecraft_geom::Mesh;
|
||||
|
||||
/// A material's triangles split into groups joined across shared edges
|
||||
pub struct TrianglePartition {
|
||||
/// The triangles of each group
|
||||
pub groups: Vec<Vec<u32>>,
|
||||
/// The index of each triangle's group
|
||||
group_of: HashMap<u32, usize>,
|
||||
}
|
||||
|
||||
impl TrianglePartition {
|
||||
/// Group `material`'s triangles of `mesh`: two triangles join when `edges` names a key for both
|
||||
pub fn new<K: Eq + Hash + Clone>(mesh: &Mesh, material: usize, edges: impl Fn(&Mesh, usize) -> Vec<K>) -> TrianglePartition {
|
||||
// Each triangle's edges once, in mesh order so the groups come out the same every time
|
||||
let triangles: Vec<u32> = mesh.triangles_of(material).map(|triangle| triangle as u32).collect();
|
||||
let position_of: HashMap<u32, usize> = triangles.iter().enumerate().map(|(position, triangle)| (*triangle, position)).collect();
|
||||
let mut edge_lists: Vec<Vec<K>> = triangles.iter().map(|triangle| edges(mesh, *triangle as usize)).collect();
|
||||
let mut by_edge: HashMap<K, Vec<u32>> = HashMap::new();
|
||||
for (triangle, triangle_edges) in triangles.iter().zip(&edge_lists) {
|
||||
for edge in triangle_edges {
|
||||
by_edge.entry(edge.clone()).or_default().push(*triangle);
|
||||
}
|
||||
}
|
||||
|
||||
let mut groups = Vec::new();
|
||||
let mut group_of = HashMap::with_capacity(triangles.len());
|
||||
for &start in &triangles {
|
||||
if group_of.contains_key(&start) {
|
||||
continue;
|
||||
}
|
||||
|
||||
let mut members = Vec::new();
|
||||
let mut stack = vec![start];
|
||||
group_of.insert(start, groups.len());
|
||||
while let Some(triangle) = stack.pop() {
|
||||
members.push(triangle);
|
||||
let triangle_edges = position_of.get(&triangle).and_then(|position| edge_lists.get_mut(*position)).map(std::mem::take).unwrap_or_default();
|
||||
// Visit a shared edge once, including when many collapsed faces share the same key
|
||||
for neighbour in triangle_edges.iter().flat_map(|edge| by_edge.remove(edge).into_iter().flatten()) {
|
||||
if let std::collections::hash_map::Entry::Vacant(entry) = group_of.entry(neighbour) {
|
||||
entry.insert(groups.len());
|
||||
stack.push(neighbour);
|
||||
}
|
||||
}
|
||||
}
|
||||
groups.push(members);
|
||||
}
|
||||
TrianglePartition { groups, group_of }
|
||||
}
|
||||
|
||||
/// The index in [`TrianglePartition::groups`] of the group holding `triangle` (None for a triangle of another material)
|
||||
pub fn index_of(&self, triangle: u32) -> Option<usize> {
|
||||
self.group_of.get(&triangle).copied()
|
||||
}
|
||||
|
||||
/// The group holding `triangle` (None for a triangle of another material)
|
||||
pub fn group(&self, triangle: u32) -> Option<&[u32]> {
|
||||
self.index_of(triangle).and_then(|group| self.groups.get(group)).map(Vec::as_slice)
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use texturecraft_geom::primitives;
|
||||
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn triangles_sharing_a_key_join_one_group() {
|
||||
let mesh = primitives::plane(2.0, 2);
|
||||
let singles = TrianglePartition::new(&mesh, 0, |_, _| Vec::<u32>::new());
|
||||
let pairs = TrianglePartition::new(&mesh, 0, |_, triangle| vec![triangle / 2]);
|
||||
|
||||
assert_eq!(singles.groups.len(), mesh.triangle_count());
|
||||
assert_eq!(pairs.groups.len(), mesh.triangle_count() / 2);
|
||||
assert_eq!(pairs.group(3).map(<[u32]>::len), Some(2));
|
||||
assert_eq!(pairs.group(99), None);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn shared_edges_keep_transitive_neighbors() {
|
||||
let mesh = primitives::plane(2.0, 4);
|
||||
let groups = TrianglePartition::new(&mesh, 0, |_, triangle| vec![triangle / 4, (triangle + 1) / 4]);
|
||||
|
||||
assert_eq!(groups.groups.len(), 1);
|
||||
assert_eq!(groups.group(0).unwrap().len(), mesh.triangle_count());
|
||||
}
|
||||
|
||||
#[test]
|
||||
#[ignore = "release performance measurement"]
|
||||
fn benchmark_shared_edges() {
|
||||
use std::hint::black_box;
|
||||
use std::time::Instant;
|
||||
|
||||
for subdivisions in [32, 64] {
|
||||
let mesh = primitives::plane(2.0, subdivisions);
|
||||
for collapsed in [false, true] {
|
||||
let mut times = Vec::new();
|
||||
for _ in 0..5 {
|
||||
let start = Instant::now();
|
||||
let groups = TrianglePartition::new(&mesh, 0, |mesh, triangle| {
|
||||
if collapsed {
|
||||
vec![(0, 0); 3]
|
||||
} else {
|
||||
let [first, second, third] = mesh.tri(triangle).unwrap();
|
||||
[(first, second), (second, third), (third, first)].map(|(from, to)| (from.min(to), from.max(to))).to_vec()
|
||||
}
|
||||
});
|
||||
assert_eq!(groups.groups.len(), 1);
|
||||
black_box(groups);
|
||||
times.push(start.elapsed().as_secs_f64() * 1000.0);
|
||||
}
|
||||
times.sort_by(f64::total_cmp);
|
||||
eprintln!("{} triangles, collapsed={collapsed}, median={:.3} ms, range={:.3}..{:.3} ms", mesh.triangle_count(), times[2], times[0], times[4]);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,14 @@
|
||||
//! Where a stroke in the 2D view is between pointer samples.
|
||||
|
||||
use texturecraft_geom::glam::Vec2;
|
||||
|
||||
/// A 2D view stroke's progress: its last point, the distance carried to the next stamp and the stamps so far.
|
||||
#[derive(Clone, Copy, Debug, Default)]
|
||||
pub(crate) struct UvStrokeState {
|
||||
/// The last sample's texture coordinates (None before the first sample).
|
||||
pub last: Option<Vec2>,
|
||||
/// Distance from the last stamp to the last sample, at most one stamp step.
|
||||
pub carry: f32,
|
||||
/// Stamps so far: the next stamp's seed, so noise alphas don't repeat from sample to sample.
|
||||
pub stamps: u32,
|
||||
}
|
||||
File renamed without changes.
File renamed without changes.
File renamed without changes.
File renamed without changes.
File renamed without changes.
File renamed without changes.
@@ -0,0 +1,172 @@
|
||||
//! Swapping a filter effect's type in place through `effect.set {filter}`
|
||||
|
||||
use serde_json::{Value, json};
|
||||
use texturecraft_engine::core::{BlendMode, Effect, EffectKind, Filter, LayerId};
|
||||
use texturecraft_engine::geom::primitives;
|
||||
use texturecraft_engine::{Session, StackTarget, execute};
|
||||
|
||||
/// A sphere project with its default layer selected
|
||||
fn session() -> Session {
|
||||
Session::new_project("t", primitives::sphere(1.0, 16, 8), "builtin:sphere", None, 256).unwrap()
|
||||
}
|
||||
|
||||
/// Runs effect-adding `command` and returns the new effect, which it selects
|
||||
fn add(s: &mut Session, command: &str, params: Value) -> LayerId {
|
||||
execute(s, command, ¶ms).unwrap();
|
||||
let StackTarget::Effect(added) = s.target else { panic!("adding an effect selects it: {:?}", s.target) };
|
||||
|
||||
added
|
||||
}
|
||||
|
||||
/// A copy of effect `id`
|
||||
fn effect(s: &Session, id: LayerId) -> Effect {
|
||||
s.doc.project.effect(id).unwrap().1.clone()
|
||||
}
|
||||
|
||||
/// Ids of the selected layer's content effects, bottom first
|
||||
fn content_order(s: &Session) -> Vec<LayerId> {
|
||||
let layer = s.selected_layer().unwrap();
|
||||
s.doc.project.layer(layer).unwrap().content_effects.iter().map(|effect| effect.id).collect()
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn swapping_a_filter_keeps_its_place_blend_opacity_and_visibility() {
|
||||
let mut s = session();
|
||||
let below = add(&mut s, "effect.add.filter", json!({"filter": "invert", "target": "content"}));
|
||||
let swapped = add(&mut s, "effect.add.filter", json!({"filter": "invert", "target": "content"}));
|
||||
let above = add(&mut s, "effect.add.filter", json!({"filter": "grayscale", "target": "content"}));
|
||||
execute(&mut s, "effect.set", &json!({"effect": swapped.0, "blend": "Multiply", "opacity": 0.4, "visible": false})).unwrap();
|
||||
|
||||
execute(&mut s, "effect.set", &json!({"effect": swapped.0, "filter": "blur", "radius": 5.0})).unwrap();
|
||||
|
||||
let blur = effect(&s, swapped);
|
||||
assert!(matches!(blur.kind, EffectKind::Filter(Filter::Blur { radius }) if radius == 5.0), "{:?}", blur.kind);
|
||||
assert_eq!(blur.name, "Blur", "a default name follows the new filter");
|
||||
assert_eq!((blur.blend, blur.opacity, blur.visible), (BlendMode::Multiply, 0.4, false));
|
||||
assert_eq!(content_order(&s), vec![below, swapped, above]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn swapping_a_filter_keeps_a_name_the_user_chose() {
|
||||
let mut s = session();
|
||||
let id = add(&mut s, "effect.add.filter", json!({"filter": "invert", "target": "content", "name": "Flip"}));
|
||||
|
||||
execute(&mut s, "effect.set", &json!({"effect": id.0, "filter": "threshold"})).unwrap();
|
||||
|
||||
assert_eq!(effect(&s, id).name, "Flip");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn one_undo_restores_the_old_filter() {
|
||||
let mut s = session();
|
||||
let id = add(&mut s, "effect.add.filter", json!({"filter": "threshold", "target": "content", "level": 0.3}));
|
||||
|
||||
execute(&mut s, "effect.set", &json!({"effect": id.0, "filter": "sharpen"})).unwrap();
|
||||
execute(&mut s, "edit.undo", &Value::Null).unwrap();
|
||||
|
||||
let restored = effect(&s, id);
|
||||
assert!(matches!(restored.kind, EffectKind::Filter(Filter::Threshold { level }) if level == 0.3), "{:?}", restored.kind);
|
||||
assert_eq!(restored.name, "Threshold");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_mask_refuses_a_content_only_filter() {
|
||||
let mut s = session();
|
||||
let id = add(&mut s, "effect.add.filter", json!({"filter": "invert", "target": "mask"}));
|
||||
|
||||
let err = execute(&mut s, "effect.set", &json!({"effect": id.0, "filter": "grayscale"})).unwrap_err();
|
||||
|
||||
assert!(err.to_string().contains("not on masks"), "{err}");
|
||||
assert!(matches!(effect(&s, id).kind, EffectKind::Filter(Filter::Invert)));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_mask_filter_swaps_in_place_on_the_mask() {
|
||||
let mut s = session();
|
||||
let below = add(&mut s, "effect.add.filter", json!({"filter": "invert", "target": "mask"}));
|
||||
let swapped = add(&mut s, "effect.add.filter", json!({"filter": "invert", "target": "mask"}));
|
||||
let above = add(&mut s, "effect.add.filter", json!({"filter": "invert", "target": "mask"}));
|
||||
execute(&mut s, "effect.set", &json!({"effect": swapped.0, "blend": "Multiply", "opacity": 0.4})).unwrap();
|
||||
|
||||
execute(&mut s, "effect.set", &json!({"effect": swapped.0, "filter": "blur"})).unwrap();
|
||||
|
||||
let blur = effect(&s, swapped);
|
||||
assert!(matches!(blur.kind, EffectKind::Filter(Filter::Blur { .. })), "{:?}", blur.kind);
|
||||
assert_eq!((blur.name.as_str(), blur.blend, blur.opacity), ("Blur", BlendMode::Multiply, 0.4));
|
||||
let layer = s.selected_layer().unwrap();
|
||||
let mask_order: Vec<LayerId> = s.doc.project.layer(layer).unwrap().mask.as_ref().unwrap().effects.iter().map(|effect| effect.id).collect();
|
||||
assert_eq!(mask_order, vec![below, swapped, above]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn naming_the_current_filter_edits_it_in_place() {
|
||||
let mut s = session();
|
||||
let id = add(&mut s, "effect.add.filter", json!({"filter": "blur", "target": "content", "radius": 5.0}));
|
||||
|
||||
execute(&mut s, "effect.set", &json!({"effect": id.0, "filter": "blur", "radius": 9.0})).unwrap();
|
||||
execute(&mut s, "effect.set", &json!({"effect": id.0, "filter": "blur"})).unwrap();
|
||||
|
||||
let blur = effect(&s, id);
|
||||
assert!(matches!(blur.kind, EffectKind::Filter(Filter::Blur { radius }) if radius == 9.0), "the radius is kept, not reset: {:?}", blur.kind);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_name_given_with_the_swap_wins() {
|
||||
let mut s = session();
|
||||
let id = add(&mut s, "effect.add.filter", json!({"filter": "invert", "target": "content"}));
|
||||
|
||||
execute(&mut s, "effect.set", &json!({"effect": id.0, "filter": "threshold", "name": "Edges"})).unwrap();
|
||||
|
||||
let swapped = effect(&s, id);
|
||||
assert!(matches!(swapped.kind, EffectKind::Filter(Filter::Threshold { .. })), "{:?}", swapped.kind);
|
||||
assert_eq!(swapped.name, "Edges");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_refused_swap_changes_nothing_and_adds_no_undo_step() {
|
||||
let mut s = session();
|
||||
let id = add(&mut s, "effect.add.filter", json!({"filter": "invert", "target": "mask"}));
|
||||
execute(&mut s, "effect.set", &json!({"effect": id.0, "blend": "Multiply", "opacity": 0.4, "name": "Flip"})).unwrap();
|
||||
let before = effect(&s, id);
|
||||
|
||||
for refused in [
|
||||
json!({"effect": id.0, "filter": "grayscale"}),
|
||||
json!({"effect": id.0, "filter": "nope"}),
|
||||
json!({"effect": id.0, "filter": "levels"}),
|
||||
json!({"effect": id.0, "filter": "colorBalance", "shadows": "not a color"}),
|
||||
] {
|
||||
assert!(execute(&mut s, "effect.set", &refused).is_err(), "{refused}");
|
||||
}
|
||||
|
||||
assert_eq!(effect(&s, id), before);
|
||||
// The last step is still the blend, opacity and name edit
|
||||
execute(&mut s, "edit.undo", &Value::Null).unwrap();
|
||||
assert_eq!(effect(&s, id).name, "Invert");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn only_filter_effects_swap_and_only_to_filters() {
|
||||
let mut s = session();
|
||||
let levels = add(&mut s, "effect.add.levels", json!({"target": "content"}));
|
||||
let filter = add(&mut s, "effect.add.filter", json!({"filter": "invert", "target": "content"}));
|
||||
|
||||
assert!(execute(&mut s, "effect.set", &json!({"effect": levels.0, "filter": "blur"})).is_err(), "levels is not a filter effect");
|
||||
assert!(execute(&mut s, "effect.set", &json!({"effect": levels.0, "filter": "nope"})).is_err(), "an unknown filter on levels");
|
||||
assert!(execute(&mut s, "effect.set", &json!({"effect": filter.0, "filter": "matFinishGrind"})).is_err(), "a material finish is a fill");
|
||||
assert!(execute(&mut s, "effect.set", &json!({"effect": filter.0, "filter": "nope"})).is_err());
|
||||
assert!(matches!(effect(&s, filter).kind, EffectKind::Filter(Filter::Invert)));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn invalid_swap_parameters_report_effect_set_and_preserve_history() {
|
||||
let mut s = session();
|
||||
let id = add(&mut s, "effect.add.filter", json!({"filter": "invert", "target": "content"}));
|
||||
let before = effect(&s, id);
|
||||
let history = s.history_labels();
|
||||
|
||||
let error = execute(&mut s, "effect.set", &json!({"effect": id.0, "filter": "colorBalance", "shadows": "invalid", "name": "Changed"})).unwrap_err();
|
||||
|
||||
assert!(matches!(error, texturecraft_engine::EngineError::BadParams { ref cmd, .. } if cmd == "effect.set"), "{error}");
|
||||
assert_eq!(effect(&s, id), before);
|
||||
assert_eq!(s.history_labels(), history);
|
||||
}
|
||||
File renamed without changes.
File renamed without changes.
@@ -0,0 +1,24 @@
|
||||
//! One integration-test executable avoids linking the same dependencies for every feature.
|
||||
//! Keep feature tests in their own modules; the standalone session.rs target remains available.
|
||||
|
||||
mod bake;
|
||||
mod bake_resolution;
|
||||
mod bake_settings;
|
||||
mod bake_tiles;
|
||||
mod content_effects;
|
||||
mod export_colour_space;
|
||||
mod filter_swap;
|
||||
mod filters;
|
||||
mod instances;
|
||||
mod materialcraft_link;
|
||||
mod materialx;
|
||||
mod materialx_import;
|
||||
mod painter_gaps;
|
||||
mod path_tool;
|
||||
mod perf;
|
||||
mod polygon_fill;
|
||||
mod project_recovery;
|
||||
mod sample;
|
||||
mod tools;
|
||||
mod udim;
|
||||
mod uv_strokes;
|
||||
File renamed without changes.
File renamed without changes.
File renamed without changes.
File renamed without changes.
File renamed without changes.
File renamed without changes.
@@ -0,0 +1,88 @@
|
||||
//! Polygon fill drag transitions preserve already painted targets
|
||||
|
||||
use serde_json::json;
|
||||
use texturecraft_engine::core::Channel;
|
||||
use texturecraft_engine::geom::{glam::Vec2, primitives};
|
||||
use texturecraft_engine::{Session, execute};
|
||||
|
||||
#[test]
|
||||
fn changing_layers_during_a_box_drag_preserves_the_first_fill() {
|
||||
let mut session = Session::new_project("t", primitives::plane(2.0, 4), "test", None, 128).unwrap();
|
||||
let first = session.selected_layer().unwrap();
|
||||
execute(&mut session, "layer.add.paint", &json!({})).unwrap();
|
||||
let second = session.selected_layer().unwrap();
|
||||
execute(&mut session, "layer.select", &json!({"layer": first.0})).unwrap();
|
||||
let history = session.history_labels().len();
|
||||
|
||||
session.drag_polygon_fill_box_uv(Vec2::ZERO, Vec2::ONE).unwrap();
|
||||
execute(&mut session, "layer.select", &json!({"layer": second.0})).unwrap();
|
||||
session.drag_polygon_fill_box_uv(Vec2::ZERO, Vec2::new(0.4, 1.0)).unwrap();
|
||||
session.end_polygon_fill_box();
|
||||
|
||||
assert!(session.doc.pixels.layer(first, Channel::BaseColor).is_some(), "the first layer keeps its fill");
|
||||
assert!(session.doc.pixels.layer(second, Channel::BaseColor).is_some(), "the new target receives the next fill");
|
||||
assert_eq!(session.history_labels().len(), history + 2, "each target has its own undo step");
|
||||
session.undo().unwrap();
|
||||
assert!(session.doc.pixels.layer(first, Channel::BaseColor).is_some());
|
||||
assert!(session.doc.pixels.layer(second, Channel::BaseColor).is_none());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn changing_from_content_to_mask_during_a_box_drag_preserves_content() {
|
||||
let mut session = Session::new_project("t", primitives::plane(2.0, 4), "test", None, 128).unwrap();
|
||||
let layer = session.selected_layer().unwrap();
|
||||
execute(&mut session, "mask.add.black", &json!({})).unwrap();
|
||||
execute(&mut session, "layer.select", &json!({"layer": layer.0, "target": "content"})).unwrap();
|
||||
let history = session.history_labels().len();
|
||||
|
||||
session.drag_polygon_fill_box_uv(Vec2::ZERO, Vec2::ONE).unwrap();
|
||||
execute(&mut session, "layer.select", &json!({"layer": layer.0, "target": "mask"})).unwrap();
|
||||
session.drag_polygon_fill_box_uv(Vec2::ZERO, Vec2::new(0.4, 1.0)).unwrap();
|
||||
session.end_polygon_fill_box();
|
||||
|
||||
assert!(session.doc.pixels.layer(layer, Channel::BaseColor).is_some(), "switching to the mask keeps the content fill");
|
||||
assert_eq!(session.history_labels().len(), history + 2);
|
||||
session.undo().unwrap();
|
||||
assert!(session.doc.pixels.layer(layer, Channel::BaseColor).is_some());
|
||||
assert!(session.doc.project.layer(layer).unwrap().mask.as_ref().unwrap().effects.is_empty());
|
||||
}
|
||||
|
||||
#[test]
|
||||
#[ignore = "release performance measurement"]
|
||||
fn benchmark_live_box_fill() {
|
||||
use std::hint::black_box;
|
||||
use std::time::Instant;
|
||||
|
||||
for (name, mesh) in [("ball", primitives::material_ball()), ("sphere", primitives::sphere(1.0, 512, 256))] {
|
||||
let triangles = mesh.triangle_count();
|
||||
let mut session = Session::new_project("benchmark", mesh, "test", None, 1024).unwrap();
|
||||
let viewport = Vec2::new(1920.0, 1080.0);
|
||||
let start = Instant::now();
|
||||
session.drag_polygon_fill_box(viewport * 0.4, viewport * 0.6, viewport).unwrap();
|
||||
let first_ms = start.elapsed().as_secs_f64() * 1000.0;
|
||||
let mut times = Vec::new();
|
||||
for step in 1..=12 {
|
||||
let radius = 0.1 + step as f32 * 0.02;
|
||||
let start = Instant::now();
|
||||
black_box(session.drag_polygon_fill_box(viewport * (0.5 - radius), viewport * (0.5 + radius), viewport).unwrap());
|
||||
times.push(start.elapsed().as_secs_f64() * 1000.0);
|
||||
}
|
||||
let (corner, opposite) = (viewport * 0.16, viewport * 0.84);
|
||||
session.drag_polygon_fill_box(corner, opposite, viewport).unwrap();
|
||||
let start = Instant::now();
|
||||
for _ in 0..1000 {
|
||||
black_box(session.drag_polygon_fill_box(corner, opposite, viewport).unwrap());
|
||||
}
|
||||
let unchanged_us = start.elapsed().as_secs_f64() * 1000.0;
|
||||
session.end_polygon_fill_box();
|
||||
let start = Instant::now();
|
||||
session.update();
|
||||
let composite_ms = start.elapsed().as_secs_f64() * 1000.0;
|
||||
times.sort_by(f64::total_cmp);
|
||||
let memory = session.memory();
|
||||
eprintln!(
|
||||
"{name}: {triangles} triangles, first={first_ms:.3} ms, growing median={:.3} ms max={:.3} ms, unchanged mean={unchanged_us:.3} us, composite={composite_ms:.3} ms, pixels={} bytes composites={} bytes cache={} bytes",
|
||||
times[6], times[11], memory.pixels, memory.composites, memory.cache
|
||||
);
|
||||
}
|
||||
}
|
||||
File renamed without changes.
File renamed without changes.
File renamed without changes.
File renamed without changes.
@@ -0,0 +1,105 @@
|
||||
//! Stamping along 2D view strokes: long segments, the carry between samples and per-stamp seeds
|
||||
|
||||
use serde_json::json;
|
||||
use texturecraft_engine::core::Channel;
|
||||
use texturecraft_engine::geom::primitives;
|
||||
use texturecraft_engine::{Session, execute};
|
||||
|
||||
/// Texture size: 1e-4 UV is 0.0256 texels
|
||||
const RESOLUTION: u32 = 256;
|
||||
|
||||
/// A sphere project painting red with `brush` settings (the UI's 0–100 scales)
|
||||
fn red_brush_session(brush: serde_json::Value) -> Session {
|
||||
let mut session = Session::new_project("UV strokes", primitives::sphere(1.0, 48, 24), "builtin:sphere", None, RESOLUTION).unwrap();
|
||||
execute(&mut session, "tool.paint", &serde_json::Value::Null).unwrap();
|
||||
execute(&mut session, "tool.material", &json!({"channel": "baseColor", "color": [1.0, 0.0, 0.0]})).unwrap();
|
||||
execute(&mut session, "tool.brush", &brush).unwrap();
|
||||
session
|
||||
}
|
||||
|
||||
/// The composite base color at texel (`x`, `y`)
|
||||
fn color_at(session: &Session, x: u32, y: u32) -> [f32; 3] {
|
||||
session.caches[0].composite.value(Channel::BaseColor, x, y)
|
||||
}
|
||||
|
||||
/// Whether the composite base color at (`u`, `v`) is the painted red
|
||||
fn red_at(session: &Session, u: f32, v: f32) -> bool {
|
||||
let color = color_at(session, (u * RESOLUTION as f32) as u32, (v * RESOLUTION as f32) as u32);
|
||||
color[0] > 0.85 && color[1] < 0.15
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_segment_longer_than_one_stamp_batch_paints_to_its_end() {
|
||||
// 1e-4 UV between stamps: 0.9 UV is 9000 stamps, past the 4096 of one batch
|
||||
let mut session = red_brush_session(json!({"size": 1.0, "spacing": 1.0, "hardness": 90}));
|
||||
|
||||
execute(&mut session, "tool.strokeUv", &json!({"points": [[0.05, 0.5], [0.95, 0.5]]})).unwrap();
|
||||
|
||||
for u in [0.1, 0.5, 0.9] {
|
||||
assert!(red_at(&session, u, 0.5), "painted at u = {u}");
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_segment_cut_at_the_stamp_limit_does_not_stamp_the_next_one_backwards() {
|
||||
// 1e-4 UV between stamps: the 20.5 UV first segment needs 205k stamps and is cut off before reaching the texture
|
||||
let mut session = red_brush_session(json!({"size": 1.0, "spacing": 1.0, "hardness": 90}));
|
||||
|
||||
execute(&mut session, "tool.strokeUv", &json!({"points": [[-20.0, 0.5], [0.5, 0.5], [0.6, 0.5]]})).unwrap();
|
||||
|
||||
assert!(red_at(&session, 0.55, 0.5), "the last segment is painted");
|
||||
assert!(!red_at(&session, 0.3, 0.5), "nothing is stamped behind the last segment's start");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn each_sample_of_a_stroke_stamps_new_noise() {
|
||||
// A 32 texel radius at full spacing: one stamp per sample, each centred on a texel at u = 0.25 and 0.5
|
||||
let mut session = red_brush_session(json!({"size": 25.0, "spacing": 100.0, "alpha": "cloud"}));
|
||||
|
||||
execute(&mut session, "tool.strokeUv", &json!({"points": [[0.25, 0.5], [0.5, 0.5]]})).unwrap();
|
||||
|
||||
let patch = |centre_x: u32| -> Vec<[f32; 3]> {
|
||||
(centre_x - 16..centre_x + 16).flat_map(|x| (112..144).map(move |y| (x, y))).map(|(x, y)| color_at(&session, x, y)).collect()
|
||||
};
|
||||
let first_stamp = patch(64);
|
||||
assert!(first_stamp.iter().any(|color| color[0] > 0.5 && color[1] < 0.5), "the first stamp painted");
|
||||
assert_ne!(first_stamp, patch(128), "the second sample's stamp has its own noise");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_hostile_segment_stays_bounded() {
|
||||
// The finest brush the settings allow: 2e-5 UV between stamps
|
||||
let mut session = red_brush_session(json!({"size": 0.2, "spacing": 1.0}));
|
||||
|
||||
let result = execute(&mut session, "tool.strokeUv", &json!({"points": [[0.0, 0.0], [1e9, 1e9]]}));
|
||||
|
||||
assert!(result.is_ok(), "{result:?}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_light_pressure_diagonal_reaches_the_far_corner() {
|
||||
let mut session = red_brush_session(json!({"size": 0.2, "minSize": 0.0, "spacing": 1.0, "hardness": 90}));
|
||||
|
||||
// Half pressure reaches the minimum stamp step: a diagonal needs about 142k stamps
|
||||
session.begin_stroke_uv([0.0, 0.0].into(), 0.5).unwrap();
|
||||
session.continue_stroke_uv([1.0, 1.0].into(), 0.5);
|
||||
session.end_stroke().unwrap();
|
||||
session.update();
|
||||
|
||||
assert!(red_at(&session, 0.5, 0.5), "the diagonal paints through its midpoint");
|
||||
assert!(red_at(&session, 0.97, 0.97), "the diagonal reaches the far corner");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn decreasing_pressure_does_not_stamp_behind_a_turn() {
|
||||
let mut session = red_brush_session(json!({"size": 10.0, "minSize": 0.0, "spacing": 100.0, "hardness": 90}));
|
||||
|
||||
session.begin_stroke_uv([0.25, 0.5].into(), 1.0).unwrap();
|
||||
session.continue_stroke_uv([0.33, 0.5].into(), 1.0);
|
||||
session.continue_stroke_uv([0.33, 0.6].into(), 0.1);
|
||||
session.end_stroke().unwrap();
|
||||
session.update();
|
||||
|
||||
assert!(red_at(&session, 0.33, 0.55), "the new segment is painted");
|
||||
assert!(!red_at(&session, 0.33, 0.45), "a smaller step must not stamp behind the turn");
|
||||
}
|
||||
@@ -105,6 +105,42 @@ fn polygon_fill_and_color_picker() {
|
||||
assert!((r["roughness"][0].as_f64().unwrap() - 0.9).abs() < 0.01, "{r}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn polygon_fill_boxes_survive_hostile_params() {
|
||||
let hostile = [
|
||||
json!({"x0": 1e30, "y0": -1e30, "x1": f64::MAX, "y1": 0, "viewport": [1e9, 1e9]}),
|
||||
json!({"x0": 0, "y0": 0, "x1": 0, "y1": 0, "viewport": [16, 16]}),
|
||||
json!({"uv0": [1e30, -1e30], "uv1": [0, 0]}),
|
||||
json!({"uv0": [0.5], "uv1": "x", "uv": [f64::MIN, 2]}),
|
||||
json!({"hitTest": "nope", "visibleOnly": "yes", "mode": 7}),
|
||||
];
|
||||
for visible_only in [true, false] {
|
||||
for hit_test in ["intersection", "containedCenter"] {
|
||||
let mut session = session();
|
||||
execute(&mut session, "tool.polygonFill", &Value::Null).unwrap();
|
||||
execute(&mut session, "tool.fillSelection", &json!({"hitTest": hit_test, "visibleOnly": visible_only})).unwrap();
|
||||
for params in &hostile {
|
||||
let _ = execute(&mut session, "tool.click", params);
|
||||
let _ = execute(&mut session, "tool.fillSelection", params);
|
||||
session.update();
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// A small project still gets the production bake defaults; only panic_hunt overrides them.
|
||||
#[test]
|
||||
fn new_project_keeps_full_resolution_bake_defaults() {
|
||||
let s = session();
|
||||
assert!(!s.doc.project.texture_sets.is_empty());
|
||||
for texture_set in &s.doc.project.texture_sets {
|
||||
assert_eq!(texture_set.resolution, 256);
|
||||
assert_eq!(texture_set.bake, texturecraft_engine::core::BakeSettings::default());
|
||||
assert_eq!(texture_set.bake.common.output_size(), (2048, 2048));
|
||||
assert_eq!(texture_set.bake.maps.ao.parameters.rays.rays, 64);
|
||||
}
|
||||
}
|
||||
|
||||
/// Every command must return Ok or Err — never panic — for hostile params.
|
||||
#[test]
|
||||
fn panic_hunt() {
|
||||
@@ -122,6 +158,11 @@ fn panic_hunt() {
|
||||
}
|
||||
for p in &hostile {
|
||||
let mut s = session();
|
||||
// Match the 256px fixture: otherwise empty/irrelevant bake.run params perform
|
||||
// repeated 2048px default bakes. Keep every input, ray count and fresh session.
|
||||
for texture_set in &mut s.doc.project.texture_sets {
|
||||
texture_set.bake.common.resolution = texturecraft_engine::core::BakeResolution::R256;
|
||||
}
|
||||
let _ = execute(&mut s, spec.id, p);
|
||||
s.update();
|
||||
}
|
||||
@@ -380,3 +421,28 @@ fn background_resizes_match_the_command_and_keep_later_edits() {
|
||||
b.update();
|
||||
assert_eq!(b.caches[0].size, (512, 512));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn curvature_generators_take_a_mode_and_detail_sizes() {
|
||||
let mut state = session();
|
||||
execute(&mut state, "layer.add.fill", &json!({})).unwrap();
|
||||
execute(&mut state, "mask.add.black", &Value::Null).unwrap();
|
||||
let added = execute(&mut state, "effect.add.generator", &json!({"generator": "curvature", "mode": "cavities"})).unwrap();
|
||||
let effect = added["effect"].clone();
|
||||
|
||||
execute(&mut state, "effect.set", &json!({"effect": effect, "sizes": [0.0, 0.0, 0.0, 1.0, 0.0, 0.0, 0.5]})).unwrap();
|
||||
let inspect = execute(&mut state, "project.inspect", &Value::Null).unwrap().to_string();
|
||||
assert!(inspect.contains(r#""mode":"Cavities""#) && inspect.contains(r#""sizes":[0.0,0.0,0.0,1.0,0.0,0.0,0.5]"#), "{inspect}");
|
||||
|
||||
let too_few = execute(&mut state, "effect.set", &json!({"effect": effect, "sizes": [1.0, 0.5]}));
|
||||
assert!(too_few.is_err(), "sizes takes one weight per detail size");
|
||||
let not_numbers = execute(&mut state, "effect.set", &json!({"effect": effect, "sizes": [1.0, "a", 0.0, 0.0, 0.0, 0.0, 0.0, 0.0]}));
|
||||
assert!(not_numbers.is_err(), "a size that isn't a number is rejected, not skipped");
|
||||
let unknown = execute(&mut state, "effect.set", &json!({"effect": effect, "mode": "ridges"}));
|
||||
assert!(unknown.is_err(), "unknown modes are rejected");
|
||||
let wrong_type = execute(&mut state, "effect.set", &json!({"effect": effect, "mode": 1, "level": 0.1}));
|
||||
assert!(wrong_type.is_err(), "a mode must be a string and an invalid edit must be rejected");
|
||||
let dirt = execute(&mut state, "effect.add.generator", &json!({"generator": "dirt", "mode": "edges"}));
|
||||
assert!(dirt.is_err(), "only curvature generators have a mode");
|
||||
assert_eq!(execute(&mut state, "project.inspect", &Value::Null).unwrap().to_string(), inspect, "failed commands leave the project unchanged");
|
||||
}
|
||||
@@ -201,7 +201,7 @@ const ORB_CUT: f32 = 0.8;
|
||||
/// [`preview_orb`] domed panels: where the valley sits, as a fraction of the face rim radius.
|
||||
const ORB_PANEL_VALLEY: f32 = 0.88;
|
||||
|
||||
/// The smart mask preview shape: a sphere cut flat by a cube on six sides, on a thin round base.
|
||||
/// The preview orb of the smart mask and smart material previews: a sphere cut flat by a cube on six sides, on a thin round base
|
||||
/// Each feature gives one kind of mask something to show: sharp face rims (edges), a softly
|
||||
/// blended left face (soft edges), domed panels inside the front, left and top faces whose valleys
|
||||
/// hold dirt (cavities), a slot around the middle (cavity), the base (thin part, the seam where it
|
||||
|
||||
@@ -29,4 +29,4 @@ pub use path::{Lasso, spline};
|
||||
pub use pickup::{Pickup, PickupMode};
|
||||
pub use raster::{RasterCtx, StrokeCanvas, UvStamp, fill_coverage, fill_triangles, rasterize, rasterize_uv};
|
||||
pub use stroke::{PickCtx, Stamp, Stroke, SurfaceHit, pick};
|
||||
pub use visibility::EyeDepth;
|
||||
pub use visibility::{EyeDepth, screen_point};
|
||||
+123
-48
@@ -2,11 +2,26 @@
|
||||
//! rendered once at the start of a stroke.
|
||||
|
||||
use rayon::prelude::*;
|
||||
use texturecraft_geom::glam::{Mat4, Vec3, Vec4};
|
||||
use texturecraft_geom::{Mesh, OrbitCamera};
|
||||
use texturecraft_geom::glam::{Mat4, Vec2, Vec3, Vec4};
|
||||
use texturecraft_geom::{Mesh, NO_TRI, OrbitCamera};
|
||||
|
||||
const BAND: usize = 16;
|
||||
|
||||
/// Largest buffer side in pixels.
|
||||
const MAX_SIZE: u32 = 4096;
|
||||
|
||||
/// Clip-space w below which a vertex counts as behind the camera.
|
||||
pub const MIN_CLIP_W: f32 = 1e-5;
|
||||
|
||||
/// Screen area (pixels squared) below which a triangle is skipped as degenerate.
|
||||
const MIN_SCREEN_AREA: f32 = 1e-9;
|
||||
|
||||
/// How far outside a triangle (in barycentric weight) a pixel center may lie and still count, closing seams between neighbours.
|
||||
const EDGE_TOLERANCE: f32 = 1e-4;
|
||||
|
||||
/// [`EyeDepth::bias`] as a fraction of the scene radius.
|
||||
const BIAS_PER_RADIUS: f32 = 0.004;
|
||||
|
||||
/// Distance from the eye to the nearest surface per screen pixel (f32::MAX where empty).
|
||||
#[derive(Clone, Debug)]
|
||||
pub struct EyeDepth {
|
||||
@@ -15,73 +30,133 @@ pub struct EyeDepth {
|
||||
pub view_proj: Mat4,
|
||||
pub eye: Vec3,
|
||||
pub dist: Vec<f32>,
|
||||
/// The nearest triangle per screen pixel ([`NO_TRI`] where empty); empty unless rendered with [`EyeDepth::render_with_triangles`].
|
||||
pub triangle: Vec<u32>,
|
||||
/// Tolerance in world units (≈ 0.4% of the scene radius).
|
||||
pub bias: f32,
|
||||
}
|
||||
|
||||
/// Where `position` lands in a `size` pixel view through `view_proj` (origin top-left), or None behind the camera.
|
||||
pub fn screen_point(view_proj: Mat4, position: Vec3, size: Vec2) -> Option<Vec2> {
|
||||
let clip = view_proj * position.extend(1.0);
|
||||
(clip.w > MIN_CLIP_W).then(|| Vec2::new(clip.x / clip.w * 0.5 + 0.5, 0.5 - clip.y / clip.w * 0.5) * size)
|
||||
}
|
||||
|
||||
impl EyeDepth {
|
||||
/// Rasterize `mesh` seen by `camera` into a `width × height` buffer (sizes capped at 4096).
|
||||
/// Rasterize `mesh` seen by `camera` into a `width × height` buffer (sizes capped at [`MAX_SIZE`]), without [`EyeDepth::triangle`].
|
||||
pub fn render(mesh: &Mesh, camera: &OrbitCamera, width: u32, height: u32) -> EyeDepth {
|
||||
let (w, h) = (width.clamp(1, 4096), height.clamp(1, 4096));
|
||||
let aspect = w as f32 / h as f32;
|
||||
let vp = camera.view_proj(aspect);
|
||||
Self::rasterize(mesh, camera, width, height, false)
|
||||
}
|
||||
|
||||
/// [`EyeDepth::render`] that also records the nearest triangle per pixel in [`EyeDepth::triangle`].
|
||||
pub fn render_with_triangles(mesh: &Mesh, camera: &OrbitCamera, width: u32, height: u32) -> EyeDepth {
|
||||
Self::rasterize(mesh, camera, width, height, true)
|
||||
}
|
||||
|
||||
/// The eye-distance buffer, plus the nearest triangle per pixel when `record_triangles` is set.
|
||||
fn rasterize(mesh: &Mesh, camera: &OrbitCamera, width: u32, height: u32, record_triangles: bool) -> EyeDepth {
|
||||
// Capping storage dimensions must not change the camera's projection
|
||||
let projection = camera.proj(width.max(1) as f32 / height.max(1) as f32);
|
||||
let view = camera.view();
|
||||
let view_proj = projection * view;
|
||||
let depth_key = |view_depth: f32| if camera.ortho { view_depth } else { -view_depth.recip() };
|
||||
let inverse_projection = projection.inverse();
|
||||
let clip_depth = |z: f32| {
|
||||
let point = inverse_projection * Vec4::new(0.0, 0.0, z, 1.0);
|
||||
depth_key(-point.z / point.w)
|
||||
};
|
||||
let depth_range = clip_depth(0.0)..=clip_depth(1.0);
|
||||
let (width, height) = (width.clamp(1, MAX_SIZE), height.clamp(1, MAX_SIZE));
|
||||
let size = Vec2::new(width as f32, height as f32);
|
||||
let eye = camera.eye();
|
||||
// Project every vertex once.
|
||||
let clip: Vec<Vec4> = mesh.positions.iter().map(|p| vp * p.extend(1.0)).collect();
|
||||
let screen: Vec<Option<(f32, f32)>> =
|
||||
clip.iter().map(|c| (c.w > 1e-5).then(|| ((c.x / c.w * 0.5 + 0.5) * w as f32, (0.5 - c.y / c.w * 0.5) * h as f32))).collect();
|
||||
let dist_v: Vec<f32> = mesh.positions.iter().map(|p| p.distance(eye)).collect();
|
||||
let bands = (h as usize).div_ceil(BAND);
|
||||
let mut bins: Vec<Vec<u32>> = vec![Vec::new(); bands];
|
||||
for t in 0..mesh.triangle_count() {
|
||||
let Some([a, b, c]) = mesh.tri(t) else { continue };
|
||||
let (Some(Some(pa)), Some(Some(pb)), Some(Some(pc))) = (screen.get(a), screen.get(b), screen.get(c)) else { continue };
|
||||
let y0 = pa.1.min(pb.1).min(pc.1).floor().max(0.0);
|
||||
let y1 = pa.1.max(pb.1).max(pc.1).ceil().min(h as f32);
|
||||
if y1 <= y0 || !y0.is_finite() || !y1.is_finite() {
|
||||
// Brush depth closes seams, but expanding triangle IDs can expose hidden faces at silhouettes
|
||||
let edge_tolerance = if record_triangles { 0.0 } else { EDGE_TOLERANCE };
|
||||
|
||||
let screen: Vec<Option<Vec2>> = mesh.positions.iter().map(|position| screen_point(view_proj, *position, size)).collect();
|
||||
// Inverse view depth is affine in perspective and avoids the precision loss of normalized clip depth
|
||||
let vertex_depth: Vec<f32> = mesh.positions.iter().map(|position| depth_key(-(view * position.extend(1.0)).z)).collect();
|
||||
|
||||
// Bin each triangle into the bands of rows it covers
|
||||
let mut bands: Vec<Vec<u32>> = vec![Vec::new(); (height as usize).div_ceil(BAND)];
|
||||
for triangle in 0..mesh.triangle_count() {
|
||||
let Some([first, second, third]) = mesh.tri(triangle) else { continue };
|
||||
let (Some(Some(first)), Some(Some(second)), Some(Some(third))) = (screen.get(first), screen.get(second), screen.get(third)) else { continue };
|
||||
|
||||
let top = first.y.min(second.y).min(third.y).floor().max(0.0);
|
||||
let bottom = first.y.max(second.y).max(third.y).ceil().min(size.y);
|
||||
if bottom <= top || !top.is_finite() || !bottom.is_finite() {
|
||||
continue;
|
||||
}
|
||||
let (b0, b1) = (y0 as usize / BAND, ((y1 as usize).saturating_sub(1)) / BAND);
|
||||
for bin in bins.iter_mut().take(b1 + 1).skip(b0) {
|
||||
bin.push(t as u32);
|
||||
|
||||
let (first_band, last_band) = (top as usize / BAND, (bottom as usize).saturating_sub(1) / BAND);
|
||||
for band in bands.iter_mut().take(last_band + 1).skip(first_band) {
|
||||
band.push(triangle as u32);
|
||||
}
|
||||
}
|
||||
let mut dist = vec![f32::MAX; (w * h) as usize];
|
||||
dist.par_chunks_mut(BAND * w as usize).enumerate().for_each(|(bi, rows)| {
|
||||
let row0 = bi * BAND;
|
||||
let nrows = rows.len() / w as usize;
|
||||
for &t in bins.get(bi).map(Vec::as_slice).unwrap_or(&[]) {
|
||||
let Some([a, b, c]) = mesh.tri(t as usize) else { continue };
|
||||
let (Some(Some(pa)), Some(Some(pb)), Some(Some(pc))) = (screen.get(a), screen.get(b), screen.get(c)) else { continue };
|
||||
let (da, db, dc) = (dist_v[a], dist_v[b], dist_v[c]);
|
||||
let area = (pb.0 - pa.0) * (pc.1 - pa.1) - (pb.1 - pa.1) * (pc.0 - pa.0);
|
||||
if area.abs() < 1e-9 {
|
||||
|
||||
let mut dist = vec![f32::MAX; (width * height) as usize];
|
||||
let mut triangle = if record_triangles { vec![NO_TRI; (width * height) as usize] } else { Vec::new() };
|
||||
let band_len = BAND * width as usize;
|
||||
let mut triangle_bands: Vec<Option<&mut [u32]>> = triangle.chunks_mut(band_len).map(Some).collect();
|
||||
triangle_bands.resize_with(dist.len().div_ceil(band_len), || None);
|
||||
dist.par_chunks_mut(band_len).zip(triangle_bands.into_par_iter()).enumerate().for_each(|(band, (band_dist, mut band_triangles))| {
|
||||
let first_row = band * BAND;
|
||||
let row_count = band_dist.len() / width as usize;
|
||||
for &candidate in bands.get(band).map(Vec::as_slice).unwrap_or(&[]) {
|
||||
let Some(corners) = mesh.tri(candidate as usize) else { continue };
|
||||
let [first, second, third] = corners;
|
||||
let (Some(Some(first_point)), Some(Some(second_point)), Some(Some(third_point))) = (screen.get(first), screen.get(second), screen.get(third))
|
||||
else {
|
||||
continue;
|
||||
};
|
||||
|
||||
let corner_depth = corners.map(|vertex| vertex_depth.get(vertex).copied().unwrap_or(f32::MAX));
|
||||
let area = (*second_point - *first_point).perp_dot(*third_point - *first_point);
|
||||
if area.abs() < MIN_SCREEN_AREA {
|
||||
continue;
|
||||
}
|
||||
let x0 = pa.0.min(pb.0).min(pc.0).floor().max(0.0) as usize;
|
||||
let x1 = (pa.0.max(pb.0).max(pc.0).ceil().min(w as f32)) as usize;
|
||||
let y0 = (pa.1.min(pb.1).min(pc.1).floor().max(row0 as f32)) as usize;
|
||||
let y1 = (pa.1.max(pb.1).max(pc.1).ceil().min((row0 + nrows) as f32)) as usize;
|
||||
for y in y0.max(row0)..y1 {
|
||||
for x in x0..x1.min(w as usize) {
|
||||
let (px, py) = (x as f32 + 0.5, y as f32 + 0.5);
|
||||
let w0 = ((pb.0 - px) * (pc.1 - py) - (pb.1 - py) * (pc.0 - px)) / area;
|
||||
let w1 = ((pc.0 - px) * (pa.1 - py) - (pc.1 - py) * (pa.0 - px)) / area;
|
||||
let w2 = 1.0 - w0 - w1;
|
||||
if w0 < -1e-4 || w1 < -1e-4 || w2 < -1e-4 {
|
||||
|
||||
let low = first_point.min(*second_point).min(*third_point).floor();
|
||||
let high = first_point.max(*second_point).max(*third_point).ceil();
|
||||
let (left, right) = (low.x.max(0.0) as usize, (high.x.min(size.x) as usize).min(width as usize));
|
||||
let (top, bottom) = (low.y.max(first_row as f32) as usize, high.y.min((first_row + row_count) as f32) as usize);
|
||||
for row in top.max(first_row)..bottom {
|
||||
for column in left..right {
|
||||
let sample = Vec2::new(column as f32 + 0.5, row as f32 + 0.5);
|
||||
let first_weight = (*third_point - *second_point).perp_dot(sample - *second_point) / area;
|
||||
let second_weight = (*first_point - *third_point).perp_dot(sample - *third_point) / area;
|
||||
let third_weight = 1.0 - first_weight - second_weight;
|
||||
if first_weight < -edge_tolerance || second_weight < -edge_tolerance || third_weight < -edge_tolerance {
|
||||
continue;
|
||||
}
|
||||
let d = w0 * da + w1 * db + w2 * dc;
|
||||
if let Some(slot) = rows.get_mut((y - row0) * w as usize + x)
|
||||
&& d < *slot
|
||||
|
||||
let depth = first_weight * corner_depth[0] + second_weight * corner_depth[1] + third_weight * corner_depth[2];
|
||||
let at = (row - first_row) * width as usize + column;
|
||||
if let Some(slot) = band_dist.get_mut(at)
|
||||
&& depth_range.contains(&depth)
|
||||
&& depth < *slot
|
||||
{
|
||||
*slot = d;
|
||||
*slot = depth;
|
||||
if let Some(nearest) = band_triangles.as_deref_mut().and_then(|triangles| triangles.get_mut(at)) {
|
||||
*nearest = candidate;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// Convert only the winning depths to eye distances for brush visibility queries
|
||||
for (row, distances) in band_dist.chunks_mut(width as usize).enumerate() {
|
||||
let view_y = (1.0 - (first_row as f32 + row as f32 + 0.5) / size.y * 2.0) / projection.y_axis.y;
|
||||
for (column, distance) in distances.iter_mut().enumerate().filter(|(_, distance)| **distance != f32::MAX) {
|
||||
let view_x = ((column as f32 + 0.5) / size.x * 2.0 - 1.0) / projection.x_axis.x;
|
||||
let radial_squared = view_x * view_x + view_y * view_y;
|
||||
*distance = if camera.ortho { (radial_squared + *distance * *distance).sqrt() } else { (radial_squared + 1.0).sqrt() / -*distance };
|
||||
}
|
||||
}
|
||||
});
|
||||
EyeDepth { width: w, height: h, view_proj: vp, eye, dist, bias: mesh.radius() * 0.004 }
|
||||
|
||||
EyeDepth { width, height, view_proj, eye, dist, triangle, bias: mesh.radius() * BIAS_PER_RADIUS }
|
||||
}
|
||||
|
||||
/// Whether world point `p` is visible (not hidden behind other geometry, inside the view).
|
||||
|
||||
@@ -0,0 +1,99 @@
|
||||
//! Visibility agrees with the surface under each pixel
|
||||
|
||||
use texturecraft_geom::glam::{Vec2, Vec3};
|
||||
use texturecraft_geom::{Mesh, OrbitCamera};
|
||||
use texturecraft_paint::EyeDepth;
|
||||
|
||||
#[test]
|
||||
fn a_large_front_triangle_occludes_a_small_rear_triangle() {
|
||||
let positions = vec![
|
||||
Vec3::new(-4.0, -4.0, 0.0),
|
||||
Vec3::new(4.0, -4.0, 0.0),
|
||||
Vec3::new(0.0, 4.0, 0.0),
|
||||
Vec3::new(-0.5, -0.5, -1.0),
|
||||
Vec3::new(0.5, -0.5, -1.0),
|
||||
Vec3::new(0.0, 0.5, -1.0),
|
||||
];
|
||||
let mesh = Mesh::from_parts(positions, None, vec![Vec2::ZERO; 6], (0..6).collect(), "m").unwrap();
|
||||
|
||||
for ortho in [false, true] {
|
||||
let camera = OrbitCamera { pitch: 0.0, ortho, ..Default::default() };
|
||||
let depth = EyeDepth::render_with_triangles(&mesh, &camera, 128, 128);
|
||||
assert_eq!(depth.triangle[64 * 128 + 64], 0, "orthographic: {ortho}");
|
||||
assert!(!depth.visible(Vec3::new(0.0, 0.0, -1.0)), "the rear face is hidden");
|
||||
assert!(depth.visible(Vec3::ZERO), "the front face is visible");
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
#[ignore = "release performance measurement"]
|
||||
fn benchmark_eye_depth() {
|
||||
use std::hint::black_box;
|
||||
use std::time::Instant;
|
||||
use texturecraft_geom::primitives;
|
||||
|
||||
for (name, mesh) in [("ball", primitives::material_ball()), ("sphere", primitives::sphere(1.0, 512, 256))] {
|
||||
let mut camera = OrbitCamera::default();
|
||||
let (low, high) = mesh.bounds();
|
||||
camera.frame(low, high);
|
||||
for triangles in [false, true] {
|
||||
let mut times = Vec::new();
|
||||
for iteration in 0..12 {
|
||||
let start = Instant::now();
|
||||
black_box(if triangles { EyeDepth::render_with_triangles(&mesh, &camera, 960, 540) } else { EyeDepth::render(&mesh, &camera, 960, 540) });
|
||||
if iteration >= 2 {
|
||||
times.push(start.elapsed().as_secs_f64() * 1000.0);
|
||||
}
|
||||
}
|
||||
times.sort_by(f64::total_cmp);
|
||||
eprintln!("{name}: {} triangles, record={triangles}, median={:.3} ms, range={:.3}..{:.3} ms", mesh.triangle_count(), times[5], times[0], times[9]);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn perspective_depth_matches_ray_intersections() {
|
||||
use texturecraft_geom::Bvh;
|
||||
|
||||
let positions = vec![Vec3::new(-3.0, -2.0, 2.0), Vec3::new(3.0, -2.0, -2.0), Vec3::new(0.0, 3.0, 0.0)];
|
||||
let mesh = Mesh::from_parts(positions, None, vec![Vec2::ZERO; 3], vec![0, 1, 2], "m").unwrap();
|
||||
let camera = OrbitCamera { pitch: 0.0, ..Default::default() };
|
||||
let bvh = Bvh::new(&mesh);
|
||||
let depth = EyeDepth::render_with_triangles(&mesh, &camera, 128, 128);
|
||||
|
||||
for (x, y) in [(40, 60), (64, 64), (88, 60)] {
|
||||
let ndc = Vec2::new((x as f32 + 0.5) / 64.0 - 1.0, 1.0 - (y as f32 + 0.5) / 64.0);
|
||||
let ray = camera.ray(ndc, 1.0);
|
||||
let hit = bvh.closest(ray.origin, ray.dir, f32::MAX).unwrap();
|
||||
let expected = (ray.origin + ray.dir * hit.t).distance(camera.eye());
|
||||
assert!((depth.dist[y * 128 + x] - expected).abs() < 0.001, "pixel {x},{y}: {} vs {expected}", depth.dist[y * 128 + x]);
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn capped_buffers_keep_the_requested_viewport_aspect() {
|
||||
let positions = vec![Vec3::new(4.0, -1.0, 0.0), Vec3::new(7.0, -1.0, 0.0), Vec3::new(5.5, 1.0, 0.0)];
|
||||
let mesh = Mesh::from_parts(positions, None, vec![Vec2::ZERO; 3], vec![0, 1, 2], "m").unwrap();
|
||||
let camera = OrbitCamera { pitch: 0.0, ..Default::default() };
|
||||
let depth = EyeDepth::render_with_triangles(&mesh, &camera, 8192, 1024);
|
||||
let point = camera.project(Vec3::new(5.5, 0.0, 0.0), 8.0).unwrap();
|
||||
let x = ((point.x * 0.5 + 0.5) * depth.width as f32) as usize;
|
||||
let y = ((0.5 - point.y * 0.5) * depth.height as f32) as usize;
|
||||
|
||||
assert_eq!(depth.triangle[y * depth.width as usize + x], 0, "the triangle stays under its viewport position after the buffer is capped");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn triangle_ids_do_not_expand_hidden_cube_faces_past_the_silhouette() {
|
||||
use std::collections::HashSet;
|
||||
use texturecraft_geom::{NO_TRI, primitives};
|
||||
|
||||
let mesh = primitives::cube(1.0);
|
||||
let mut camera = OrbitCamera { yaw: 0.6, pitch: 0.4, ..Default::default() };
|
||||
let (low, high) = mesh.bounds();
|
||||
camera.frame(low, high);
|
||||
let depth = EyeDepth::render_with_triangles(&mesh, &camera, 400, 400);
|
||||
let visible: HashSet<_> = depth.triangle.iter().copied().filter(|triangle| *triangle != NO_TRI).collect();
|
||||
|
||||
assert_eq!(visible.len(), mesh.triangle_count() / 2, "only the three front faces own screen pixels");
|
||||
}
|
||||
+334
-167
@@ -5,10 +5,10 @@ use egui::{Color32, Rect, RichText, Sense, Stroke, Ui, pos2, vec2};
|
||||
use egui_phosphor::regular as ic;
|
||||
use serde_json::{Value, json};
|
||||
use texturecraft_engine::core::{
|
||||
BakedMap, BlendMode, Channel, Decal, Effect, EffectKind, Fill, Filter, GeneratorKind, Layer, LayerId, LayerKind, LinkParam, MaterialLink, ProceduralKind,
|
||||
Projection, Source,
|
||||
BakedMap, BlendMode, Channel, CurvatureDetail, CurvatureMode, Decal, Effect, EffectKind, Fill, Filter, Generator, GeneratorKind, Layer, LayerId, LayerKind,
|
||||
LinkParam, MaterialLink, ProceduralKind, Projection, Source,
|
||||
};
|
||||
use texturecraft_engine::filter_lib::{FILTERS, scalar_params};
|
||||
use texturecraft_engine::filter_lib::scalar_params;
|
||||
use texturecraft_engine::paint::{BrushAlpha, alphas};
|
||||
use texturecraft_engine::{CloneFrom, StackTarget, Tool};
|
||||
|
||||
@@ -19,6 +19,13 @@ use crate::state::PropsTab;
|
||||
use crate::theme::{Tokens, caption};
|
||||
use crate::widgets::{chip, color_swatch, combo, dnd_release, elided, histogram, icon_button, section, slider, slider_edit};
|
||||
|
||||
/// The filter Add filter adds: at its defaults it changes nothing, and its slot opens the picker to swap it
|
||||
const NEW_FILTER: &str = "hsl";
|
||||
const FILTER_SWATCH_WIDTH: f32 = 36.0;
|
||||
const FILTER_HINT_SIZE: f32 = 10.5;
|
||||
/// The most colors `effect.set {colors}` takes for a gradient map
|
||||
const MAX_GRADIENT_STOPS: usize = 16;
|
||||
|
||||
const TAG_COLORS: [Color32; 8] = [
|
||||
Color32::from_rgb(0xc0, 0x40, 0x40),
|
||||
Color32::from_rgb(0xd0, 0x80, 0x30),
|
||||
@@ -208,48 +215,43 @@ pub(crate) fn targets_content(app: &TextureCraftApp) -> bool {
|
||||
}
|
||||
}
|
||||
|
||||
/// "Add effect" items for `layer` (toolbar and context menu). Effects that fit both stacks go
|
||||
/// to the content when it is the selected target; generators and compare always go to the
|
||||
/// mask, anchor points to the content.
|
||||
/// "Add effect" items for `layer`: content when it is the selected target, else the mask
|
||||
fn effect_menu(app: &mut TextureCraftApp, ui: &mut Ui, layer: &Layer) {
|
||||
let content = !layer.is_group() && app.session.selected_layer() == Some(layer.id) && targets_content(app);
|
||||
let t = if content { "content" } else { "mask" };
|
||||
let target = if content { "content" } else { "mask" };
|
||||
ui.label(caption(if content { tr("Add to the layer content") } else { tr("Add to the mask") }));
|
||||
|
||||
// Generators and compare masks always go to the mask, anchor points to the content
|
||||
let items = [
|
||||
(tr("Add generator"), "effect.add.generator", json!({})),
|
||||
(tr("Add paint"), "effect.add.paint", json!({"target": t})),
|
||||
(tr("Add fill"), "effect.add.fill", json!({"target": t})),
|
||||
(tr("Add levels"), "effect.add.levels", json!({"target": t})),
|
||||
(tr("Add paint"), "effect.add.paint", json!({"target": target})),
|
||||
(tr("Add fill"), "effect.add.fill", json!({"target": target})),
|
||||
(tr("Add levels"), "effect.add.levels", json!({"target": target})),
|
||||
(tr("Add compare mask"), "effect.add.compare", json!({})),
|
||||
(tr("Add filter"), "effect.add.filter", json!({"target": target, "filter": NEW_FILTER})),
|
||||
(tr("Add anchor point"), "effect.add.anchor", json!({})),
|
||||
];
|
||||
let run = |app: &mut TextureCraftApp, id: &str, p: &Value| {
|
||||
for (label, command, params) in items {
|
||||
let enabled = command != "effect.add.anchor" || !layer.is_group();
|
||||
if !ui.add_enabled(enabled, egui::Button::new(label)).clicked() {
|
||||
continue;
|
||||
}
|
||||
|
||||
if app.session.selected_layer() != Some(layer.id) {
|
||||
app.run("layer.select", json!({"layer": layer.id.0}));
|
||||
}
|
||||
app.run(id, with(p, json!({"layer": layer.id.0})));
|
||||
};
|
||||
for (label, id, p) in items {
|
||||
let enabled = id != "effect.add.anchor" || !layer.is_group();
|
||||
if ui.add_enabled(enabled, egui::Button::new(label)).clicked() {
|
||||
run(app, id, &p);
|
||||
ui.close();
|
||||
|
||||
let added = app.run(command, with(¶ms, json!({"layer": layer.id.0})));
|
||||
// The neutral filter is a placeholder: its slot opens the picker to choose the real one
|
||||
if command == "effect.add.filter"
|
||||
&& let Some(effect) = added.as_ref().and_then(|result| result["effect"].as_u64())
|
||||
{
|
||||
app.ui.dock.focus(crate::docking::Panel::Properties);
|
||||
crate::filter_slot::open_picker_when_shown(ui.ctx(), effect);
|
||||
}
|
||||
|
||||
ui.close();
|
||||
}
|
||||
// The filter library (material finishes only fill content).
|
||||
ui.menu_button(tr("Add filter"), |ui| {
|
||||
let mut group = "";
|
||||
for f in FILTERS.iter().filter(|f| content || f.mask) {
|
||||
if f.group != group {
|
||||
ui.label(caption(tr(f.group)));
|
||||
group = f.group;
|
||||
}
|
||||
if ui.button(tr(f.label)).clicked() {
|
||||
run(app, "effect.add.filter", &json!({"target": t, "filter": f.id}));
|
||||
ui.close();
|
||||
}
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
fn layer_tree(app: &mut TextureCraftApp, ui: &mut Ui, id: LayerId, depth: usize) {
|
||||
@@ -912,12 +914,14 @@ fn mesh_map_color(map: BakedMap) -> Color32 {
|
||||
|
||||
/// The Properties tab title: what the panel edits.
|
||||
pub(crate) fn properties_title(app: &TextureCraftApp) -> String {
|
||||
let p = &app.session.doc.project;
|
||||
let what = match (app.session.selected_layer().and_then(|id| p.layers.get(&id)), app.session.target) {
|
||||
(Some(_), StackTarget::Effect(e)) => p.effect(e).map(|(_, x)| x.name.clone()).unwrap_or_default(),
|
||||
(Some(l), StackTarget::Content) if matches!(l.kind, LayerKind::Fill(_)) => tr("Fill").to_string(),
|
||||
(Some(l), StackTarget::Content) if l.is_group() => tr("Folder").to_string(),
|
||||
(Some(l), StackTarget::Content) if l.instance_source().is_some() => tr("Instance").to_string(),
|
||||
let project = &app.session.doc.project;
|
||||
let what = match (app.session.selected_layer().and_then(|id| project.layers.get(&id)), app.session.target) {
|
||||
// Polygon fill keeps its own properties whatever is selected
|
||||
_ if app.session.tool.tool == Tool::PolygonFill => tr(app.session.tool.tool.label()).to_string(),
|
||||
(Some(_), StackTarget::Effect(effect)) => project.effect(effect).map(|(_, found)| found.name.clone()).unwrap_or_default(),
|
||||
(Some(layer), StackTarget::Content) if matches!(layer.kind, LayerKind::Fill(_)) => tr("Fill").to_string(),
|
||||
(Some(layer), StackTarget::Content) if layer.is_group() => tr("Folder").to_string(),
|
||||
(Some(layer), StackTarget::Content) if layer.instance_source().is_some() => tr("Instance").to_string(),
|
||||
_ => tr(app.session.tool.tool.label()).to_string(),
|
||||
};
|
||||
format!("{} - {what}", tr("Properties"))
|
||||
@@ -927,12 +931,14 @@ pub(crate) fn properties(app: &mut TextureCraftApp, ui: &mut Ui) {
|
||||
egui::ScrollArea::vertical().id_salt("props").auto_shrink([false, false]).show(ui, |ui| properties_contents(app, ui));
|
||||
}
|
||||
|
||||
/// What the Properties panel edits: the selected effect, fill, folder or instance, else the tool
|
||||
/// What the Properties panel edits: polygon fill's own settings, the selected effect, fill, folder or instance, else the tool
|
||||
pub(crate) fn properties_contents(app: &mut TextureCraftApp, ui: &mut Ui) {
|
||||
let tokens = Tokens::get(ui.ctx());
|
||||
let selected = app.session.selected_layer().and_then(|id| app.session.doc.project.layers.get(&id).cloned());
|
||||
|
||||
match (&selected, app.session.target) {
|
||||
// Polygon fill shows its own settings and says what it fills into, whatever is selected
|
||||
_ if app.session.tool.tool == Tool::PolygonFill => polygon_fill_properties(app, ui),
|
||||
(Some(layer), StackTarget::Effect(effect)) => effect_properties(app, ui, layer, effect),
|
||||
(Some(layer), StackTarget::Content) if matches!(layer.kind, LayerKind::Fill(_)) => fill_properties(app, ui, layer),
|
||||
(Some(layer), StackTarget::Content) if layer.is_group() => {
|
||||
@@ -1144,6 +1150,104 @@ fn path_section(app: &mut TextureCraftApp, ui: &mut Ui) {
|
||||
ui.label(RichText::new(hint).size(10.5).color(tk.text_dim));
|
||||
}
|
||||
|
||||
/// Width of the label column in polygon fill's properties
|
||||
const POLYGON_FILL_LABEL_WIDTH: f32 = 108.0;
|
||||
|
||||
/// Polygon fill's properties: how it selects and fills, its blending, then what it fills with (material, mask gray, or why it can't fill)
|
||||
fn polygon_fill_properties(app: &mut TextureCraftApp, ui: &mut Ui) {
|
||||
use texturecraft_engine::FillHitTest;
|
||||
|
||||
let button_size = ui.spacing().interact_size.y;
|
||||
ui.label(caption(&tr("Polygon fill").to_uppercase()));
|
||||
property_row(ui, tr("Selection mode"), tr("A click fills what is under it; a dragged rectangle fills what it selects as it grows"), |ui| {
|
||||
icon_button(ui, ic::SELECTION, tr("Rectangle fill"), true, button_size);
|
||||
});
|
||||
property_row(
|
||||
ui,
|
||||
tr("Fill mode"),
|
||||
tr("Triangle fills single triangles, Polygon whole quads and n-gons, Mesh the connected geometry, UV island the UV islands"),
|
||||
|ui| crate::toolbar::fill_mode_buttons(app, ui),
|
||||
);
|
||||
property_row(ui, tr("Hit-test"), tr("How a rectangle selects polygons"), |ui| {
|
||||
for (hit_test, icon, tooltip) in [
|
||||
(FillHitTest::Intersection, ic::INTERSECT_SQUARE, tr("Intersection: fill polygons the rectangle touches")),
|
||||
(FillHitTest::ContainedCenter, ic::SELECTION_FOREGROUND, tr("Contained center: fill polygons whose center is in the rectangle")),
|
||||
] {
|
||||
if icon_button(ui, icon, tooltip, app.session.tool.fill_hit_test == hit_test, button_size).clicked() {
|
||||
app.session.tool.fill_hit_test = hit_test;
|
||||
}
|
||||
}
|
||||
});
|
||||
ui.horizontal(|ui| {
|
||||
ui.checkbox(&mut app.session.tool.fill_visible_only, tr("Visible polygons only"));
|
||||
ui.with_layout(egui::Layout::right_to_left(egui::Align::Center), |ui| info_icon(ui, tr("Fill only polygons the camera sees (3D view)")));
|
||||
});
|
||||
section(ui, "sec_polygon_fill_blending", tr("Blending"), false, |ui| {
|
||||
let mut opacity = app.session.tool.brush.opacity * 100.0;
|
||||
if slider(ui, tr("Opacity"), &mut opacity, 0.0..=100.0, 0).changed() {
|
||||
app.session.tool.brush.opacity = (opacity / 100.0).clamp(0.0, 1.0);
|
||||
}
|
||||
});
|
||||
ui.separator();
|
||||
|
||||
match polygon_fill_paints_mask(app) {
|
||||
Ok(false) => {
|
||||
ui.label(caption(&tr("Material").to_uppercase()));
|
||||
material_controls(app, ui);
|
||||
}
|
||||
Ok(true) => {
|
||||
ui.label(caption(&tr("Grayscale").to_uppercase()));
|
||||
let mut gray = app.session.tool.mask_value;
|
||||
if slider(ui, tr("Value"), &mut gray, 0.0..=1.0, 2).changed() {
|
||||
app.session.tool.mask_value = gray;
|
||||
}
|
||||
}
|
||||
Err(note) => {
|
||||
ui.label(RichText::new(note).color(Tokens::get(ui.ctx()).text_dim));
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// One polygon fill setting: its label in a fixed column, its `controls`, and an info icon with `info` at the right edge
|
||||
fn property_row(ui: &mut Ui, label: &str, info: &str, controls: impl FnOnce(&mut Ui)) {
|
||||
ui.horizontal(|ui| {
|
||||
let label_width = ui.label(label).rect.width();
|
||||
ui.add_space((POLYGON_FILL_LABEL_WIDTH - label_width - ui.spacing().item_spacing.x).max(0.0));
|
||||
controls(ui);
|
||||
ui.with_layout(egui::Layout::right_to_left(egui::Align::Center), |ui| info_icon(ui, info));
|
||||
});
|
||||
}
|
||||
|
||||
/// A dim info icon explaining a setting on hover
|
||||
fn info_icon(ui: &mut Ui, text: &str) {
|
||||
ui.label(RichText::new(ic::INFO).color(Tokens::get(ui.ctx()).text_dim)).on_hover_text(text);
|
||||
}
|
||||
|
||||
/// What a polygon fill paints into now: Ok(true) a mask (gray), Ok(false) layer content (material), or a note on why it can't fill
|
||||
fn polygon_fill_paints_mask(app: &TextureCraftApp) -> Result<bool, String> {
|
||||
if app.session.quick_mask.editing {
|
||||
return Err(tr("Editing the quick mask: fills paint where painting is allowed. Press U to finish.").to_string());
|
||||
}
|
||||
|
||||
let project = &app.session.doc.project;
|
||||
let Some(layer) = app.session.selected_layer().and_then(|id| project.layers.get(&id)) else {
|
||||
return Err(tr("Select a paint layer or a layer's mask to fill").to_string());
|
||||
};
|
||||
|
||||
match app.session.target {
|
||||
StackTarget::Mask => Ok(true),
|
||||
StackTarget::Effect(_) => Ok(!targets_content(app)),
|
||||
StackTarget::Content => {
|
||||
let content = project.content_layer(layer.id).unwrap_or(layer);
|
||||
if matches!(content.kind, LayerKind::Paint) {
|
||||
Ok(false)
|
||||
} else {
|
||||
Err(trf("\"{layer}\" can't be filled: select a paint layer or a layer's mask", &[("layer", &layer.name)]))
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fn brush_section(app: &mut TextureCraftApp, ui: &mut Ui) {
|
||||
let b = &mut app.session.tool.brush;
|
||||
ui.label(caption(tr("Brush")));
|
||||
@@ -1365,59 +1469,68 @@ fn text_section(app: &mut TextureCraftApp, ui: &mut Ui) {
|
||||
/// Tooltip of the material channel chips.
|
||||
pub(crate) const SOLO_HINT: &str = "Click: turn this channel on or off. Alt+click: this channel only";
|
||||
|
||||
/// The tool's material under a "Material" heading
|
||||
fn material_section(app: &mut TextureCraftApp, ui: &mut Ui) {
|
||||
let tk = Tokens::get(ui.ctx());
|
||||
ui.label(caption(tr("Material")));
|
||||
let chans = app.session.doc.project.texture_set(app.session.ts()).map(|t| t.channel_list()).unwrap_or_default();
|
||||
material_controls(app, ui);
|
||||
}
|
||||
|
||||
/// The tool's material: channel chips, then each enabled channel's value (or the mask gray while painting a mask)
|
||||
fn material_controls(app: &mut TextureCraftApp, ui: &mut Ui) {
|
||||
use texturecraft_engine::core::ChannelKind;
|
||||
|
||||
let tokens = Tokens::get(ui.ctx());
|
||||
let channels = app.session.doc.project.texture_set(app.session.ts()).map(|set| set.channel_list()).unwrap_or_default();
|
||||
ui.horizontal_wrapped(|ui| {
|
||||
for c in &chans {
|
||||
let on = app.session.tool.enabled.contains(c);
|
||||
if chip(ui, tr(c.short()), on).on_hover_text(tr(SOLO_HINT)).clicked() {
|
||||
let solo = ui.input(|i| i.modifiers.alt);
|
||||
app.run("tool.material", json!({"channel": c.id(), "enabled": solo || !on, "solo": solo}));
|
||||
for channel in &channels {
|
||||
let on = app.session.tool.enabled.contains(channel);
|
||||
if chip(ui, tr(channel.short()), on).on_hover_text(tr(SOLO_HINT)).clicked() {
|
||||
let solo = ui.input(|input| input.modifiers.alt);
|
||||
app.run("tool.material", json!({"channel": channel.id(), "enabled": solo || !on, "solo": solo}));
|
||||
}
|
||||
}
|
||||
});
|
||||
ui.add_space(4.0);
|
||||
let mask_mode = !targets_content(app);
|
||||
if mask_mode {
|
||||
let mut v = app.session.tool.mask_value;
|
||||
if slider(ui, tr("Mask value (gray)"), &mut v, 0.0..=1.0, 2).changed() {
|
||||
app.session.tool.mask_value = v;
|
||||
|
||||
if !targets_content(app) {
|
||||
let mut gray = app.session.tool.mask_value;
|
||||
if slider(ui, tr("Mask value (gray)"), &mut gray, 0.0..=1.0, 2).changed() {
|
||||
app.session.tool.mask_value = gray;
|
||||
}
|
||||
return;
|
||||
}
|
||||
for c in chans {
|
||||
if !app.session.tool.enabled.contains(&c) {
|
||||
|
||||
for channel in channels {
|
||||
if !app.session.tool.enabled.contains(&channel) {
|
||||
continue;
|
||||
}
|
||||
let mut v = app.session.tool.values.get(&c).copied().unwrap_or(c.default_value());
|
||||
match c.kind() {
|
||||
texturecraft_engine::core::ChannelKind::Color => {
|
||||
let mut value = app.session.tool.values.get(&channel).copied().unwrap_or(channel.default_value());
|
||||
match channel.kind() {
|
||||
ChannelKind::Color => {
|
||||
ui.horizontal(|ui| {
|
||||
ui.label(tr(c.label()));
|
||||
if color_swatch(ui, &format!("tool_{}", c.id()), &mut v, ui.available_width() - 4.0) {
|
||||
app.session.tool.values.insert(c, v);
|
||||
ui.label(tr(channel.label()));
|
||||
if color_swatch(ui, &format!("tool_{}", channel.id()), &mut value, ui.available_width() - 4.0) {
|
||||
app.session.tool.values.insert(channel, value);
|
||||
}
|
||||
});
|
||||
}
|
||||
texturecraft_engine::core::ChannelKind::NormalMap => {
|
||||
ui.label(RichText::new(tr("Normal: painting uses the flat normal")).color(tk.text_dim));
|
||||
ChannelKind::NormalMap => {
|
||||
ui.label(RichText::new(tr("Normal: painting uses the flat normal")).color(tokens.text_dim));
|
||||
}
|
||||
texturecraft_engine::core::ChannelKind::Signed => {
|
||||
if slider(ui, tr(c.label()), &mut v[0], -1.0..=1.0, 2).changed() {
|
||||
app.session.tool.values.insert(c, [v[0]; 3]);
|
||||
ChannelKind::Signed => {
|
||||
if slider(ui, tr(channel.label()), &mut value[0], -1.0..=1.0, 2).changed() {
|
||||
app.session.tool.values.insert(channel, [value[0]; 3]);
|
||||
}
|
||||
}
|
||||
texturecraft_engine::core::ChannelKind::Scalar => {
|
||||
if slider(ui, tr(c.label()), &mut v[0], 0.0..=1.0, 2).changed() {
|
||||
app.session.tool.values.insert(c, [v[0]; 3]);
|
||||
ChannelKind::Scalar => {
|
||||
if slider(ui, tr(channel.label()), &mut value[0], 0.0..=1.0, 2).changed() {
|
||||
app.session.tool.values.insert(channel, [value[0]; 3]);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
if app.session.tool.tool == Tool::Eraser {
|
||||
ui.label(RichText::new(tr("The eraser removes paint from the enabled channels.")).color(tk.text_dim));
|
||||
ui.label(RichText::new(tr("The eraser removes paint from the enabled channels.")).color(tokens.text_dim));
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1873,63 +1986,42 @@ fn fill_channel(app: &mut TextureCraftApp, ui: &mut Ui, fill: &Fill, base: &Valu
|
||||
|
||||
fn effect_properties(app: &mut TextureCraftApp, ui: &mut Ui, layer: &Layer, eid: LayerId) {
|
||||
let tk = Tokens::get(ui.ctx());
|
||||
let Some((_, e)) = app.session.doc.project.effect(eid).map(|(l, e)| (l, e.clone())) else { return };
|
||||
let Some((_, effect)) = app.session.doc.project.effect(eid).map(|(owner, effect)| (owner, effect.clone())) else { return };
|
||||
|
||||
let id = eid.0;
|
||||
ui.horizontal(|ui| {
|
||||
ui.label(tr("Blending"));
|
||||
egui::ComboBox::from_id_salt("eff_blend").selected_text(tr(e.blend.label())).show_ui(ui, |ui| {
|
||||
for m in BlendMode::all() {
|
||||
if ui.selectable_label(m == e.blend, tr(m.label())).clicked() {
|
||||
app.run("effect.set", json!({"effect": id, "blend": format!("{m:?}")}));
|
||||
egui::ComboBox::from_id_salt("eff_blend").selected_text(tr(effect.blend.label())).show_ui(ui, |ui| {
|
||||
for mode in BlendMode::all() {
|
||||
if ui.selectable_label(mode == effect.blend, tr(mode.label())).clicked() {
|
||||
app.run("effect.set", json!({"effect": id, "blend": format!("{mode:?}")}));
|
||||
}
|
||||
}
|
||||
});
|
||||
});
|
||||
let mut op = e.opacity;
|
||||
if let Some(merge) = slider_edit(ui, tr("Opacity"), &mut op, 0.0..=1.0, 2) {
|
||||
app.run("effect.set", json!({"effect": id, "opacity": op, "merge": merge}));
|
||||
let mut opacity = effect.opacity;
|
||||
if let Some(merge) = slider_edit(ui, tr("Opacity"), &mut opacity, 0.0..=1.0, 2) {
|
||||
app.run("effect.set", json!({"effect": id, "opacity": opacity, "merge": merge}));
|
||||
}
|
||||
ui.separator();
|
||||
match &e.kind {
|
||||
EffectKind::Generator(g) => {
|
||||
ui.label(caption(tr("Generator")));
|
||||
egui::ComboBox::from_id_salt("gen_kind").selected_text(tr(g.kind.label())).show_ui(ui, |ui| {
|
||||
for k in GeneratorKind::ALL {
|
||||
if ui.selectable_label(k == g.kind, tr(k.label())).clicked() {
|
||||
// Replace the generator kind: remove and add keeps ordering simple.
|
||||
app.run("effect.remove", json!({"effect": id}));
|
||||
app.run("effect.add.generator", json!({"generator": format!("{k:?}")}));
|
||||
}
|
||||
}
|
||||
});
|
||||
let (mut level, mut soft, mut noise, mut ns) = (g.level, g.softness, g.noise_amount, g.noise_scale);
|
||||
let r1 = slider_edit(ui, tr("Level"), &mut level, 0.0..=1.0, 2);
|
||||
let r2 = slider_edit(ui, tr("Softness"), &mut soft, 0.0..=1.0, 2);
|
||||
let r3 = slider_edit(ui, tr("Noise amount"), &mut noise, 0.0..=2.0, 2);
|
||||
let r4 = slider_edit(ui, tr("Noise scale"), &mut ns, 0.1..=64.0, 1);
|
||||
let mut inv = g.invert;
|
||||
let r5 = ui.checkbox(&mut inv, tr("Invert"));
|
||||
if let Some(merge) = r1.or(r2).or(r3).or(r4).or(r5.changed().then_some(false)) {
|
||||
app.run("effect.set", json!({"effect": id, "level": level, "softness": soft, "noise": noise, "noiseScale": ns, "invert": inv, "merge": merge}));
|
||||
}
|
||||
if !app.session.doc.baked.contains_key(&app.session.ts()) {
|
||||
ui.label(
|
||||
RichText::new(format!("{} {}", ic::WARNING, tr("Bake mesh maps (F8) for curvature, AO and thickness based generators."))).color(tk.warning),
|
||||
);
|
||||
}
|
||||
}
|
||||
EffectKind::Levels(l) => {
|
||||
|
||||
match &effect.kind {
|
||||
EffectKind::Generator(generator) => generator_properties(app, ui, id, generator),
|
||||
EffectKind::Levels(levels) => {
|
||||
ui.label(caption(tr("Levels")));
|
||||
levels_histogram(app, ui, layer, eid, (l.in_low, l.in_high));
|
||||
let mut v = [l.in_low, l.in_high, l.gamma, l.out_low, l.out_high];
|
||||
levels_histogram(app, ui, layer, eid, (levels.in_low, levels.in_high));
|
||||
let mut values = [levels.in_low, levels.in_high, levels.gamma, levels.out_low, levels.out_high];
|
||||
let labels = [tr("Input low"), tr("Input high"), tr("Gamma"), tr("Output low"), tr("Output high")];
|
||||
let mut edit = None;
|
||||
for (i, label) in labels.iter().enumerate() {
|
||||
let range = if i == 2 { 0.1..=5.0 } else { 0.0..=1.0 };
|
||||
edit = edit.or(slider_edit(ui, label, &mut v[i], range, 2));
|
||||
for (index, label) in labels.iter().enumerate() {
|
||||
let range = if index == 2 { 0.1..=5.0 } else { 0.0..=1.0 };
|
||||
edit = edit.or(slider_edit(ui, label, &mut values[index], range, 2));
|
||||
}
|
||||
if let Some(merge) = edit {
|
||||
app.run("effect.set", json!({"effect": id, "inLow": v[0], "inHigh": v[1], "gamma": v[2], "outLow": v[3], "outHigh": v[4], "merge": merge}));
|
||||
app.run(
|
||||
"effect.set",
|
||||
json!({"effect": id, "inLow": values[0], "inHigh": values[1], "gamma": values[2], "outLow": values[3], "outHigh": values[4], "merge": merge}),
|
||||
);
|
||||
}
|
||||
}
|
||||
EffectKind::Fill { source, .. } => {
|
||||
@@ -1945,25 +2037,25 @@ fn effect_properties(app: &mut TextureCraftApp, ui: &mut Ui, layer: &Layer, eid:
|
||||
if ui.selectable_label(matches!(source, Source::Uniform(_)), tr("Uniform value")).clicked() {
|
||||
app.run("effect.set", json!({"effect": id, "value": 1.0}));
|
||||
}
|
||||
for (a, label) in &anchors {
|
||||
if ui.selectable_label(source.anchor() == Some(*a), trf("Anchor: {name}", &[("name", label)])).clicked() {
|
||||
app.run("effect.set", json!({"effect": id, "anchor": a.0}));
|
||||
for (anchor, label) in &anchors {
|
||||
if ui.selectable_label(source.anchor() == Some(*anchor), trf("Anchor: {name}", &[("name", label)])).clicked() {
|
||||
app.run("effect.set", json!({"effect": id, "anchor": anchor.0}));
|
||||
}
|
||||
}
|
||||
});
|
||||
match source {
|
||||
Source::Uniform(v) => {
|
||||
let mut x = v[0];
|
||||
if let Some(merge) = slider_edit(ui, tr("Value"), &mut x, 0.0..=1.0, 2) {
|
||||
app.run("effect.set", json!({"effect": id, "value": x, "merge": merge}));
|
||||
Source::Uniform(color) => {
|
||||
let mut value = color[0];
|
||||
if let Some(merge) = slider_edit(ui, tr("Value"), &mut value, 0.0..=1.0, 2) {
|
||||
app.run("effect.set", json!({"effect": id, "value": value, "merge": merge}));
|
||||
}
|
||||
}
|
||||
Source::Anchor { channel, .. } => {
|
||||
let chans = app.session.doc.project.texture_set(app.session.ts()).map(|t| t.channel_list()).unwrap_or_default();
|
||||
let channels = app.session.doc.project.texture_set(app.session.ts()).map(|set| set.channel_list()).unwrap_or_default();
|
||||
combo(ui, tr("Channel"), tr(channel.label()), |ui| {
|
||||
for c in chans {
|
||||
if ui.selectable_label(c == *channel, tr(c.label())).clicked() {
|
||||
app.run("effect.set", json!({"effect": id, "anchorChannel": c.id()}));
|
||||
for option in channels {
|
||||
if ui.selectable_label(option == *channel, tr(option.label())).clicked() {
|
||||
app.run("effect.set", json!({"effect": id, "anchorChannel": option.id()}));
|
||||
}
|
||||
}
|
||||
});
|
||||
@@ -1975,10 +2067,10 @@ fn effect_properties(app: &mut TextureCraftApp, ui: &mut Ui, layer: &Layer, eid:
|
||||
ui.label(RichText::new(tr("Add an anchor point to a layer below to use its stack as a mask.")).color(tk.text_dim));
|
||||
}
|
||||
}
|
||||
EffectKind::Material(f) => {
|
||||
EffectKind::Material(fill) => {
|
||||
ui.label(caption(tr("Fill")));
|
||||
let on: Vec<Channel> = f.sources.keys().copied().collect();
|
||||
fill_editor(app, ui, f, &json!({"effect": id}), &on, layer.id);
|
||||
let enabled: Vec<Channel> = fill.sources.keys().copied().collect();
|
||||
fill_editor(app, ui, fill, &json!({"effect": id}), &enabled, layer.id);
|
||||
}
|
||||
EffectKind::Anchor => {
|
||||
ui.label(caption(tr("Anchor point")));
|
||||
@@ -1988,7 +2080,7 @@ fn effect_properties(app: &mut TextureCraftApp, ui: &mut Ui, layer: &Layer, eid:
|
||||
);
|
||||
}
|
||||
EffectKind::Paint => {
|
||||
let hint = if layer.content_effects.iter().any(|x| x.id == eid) {
|
||||
let hint = if layer.content_effects.iter().any(|content| content.id == eid) {
|
||||
tr("Paint on the mesh to edit the layer content.")
|
||||
} else {
|
||||
tr("Paint on the mesh to edit this mask. Use the Material tab's mask value for gray.")
|
||||
@@ -2002,30 +2094,102 @@ fn effect_properties(app: &mut TextureCraftApp, ui: &mut Ui, layer: &Layer, eid:
|
||||
.color(tk.text_dim),
|
||||
);
|
||||
let editing = app.session.tool.path.editing;
|
||||
for i in 0..paths.len() {
|
||||
for index in 0..paths.len() {
|
||||
ui.horizontal(|ui| {
|
||||
let on = editing == Some((eid, i));
|
||||
if ui.selectable_label(on, format!("{} {}", tr("Path"), i + 1)).on_hover_text(tr("Edit")).clicked() {
|
||||
if on {
|
||||
let selected = editing == Some((eid, index));
|
||||
if ui.selectable_label(selected, format!("{} {}", tr("Path"), index + 1)).on_hover_text(tr("Edit")).clicked() {
|
||||
if selected {
|
||||
app.run("tool.path", json!({"clear": true}));
|
||||
} else {
|
||||
app.run("path.edit", json!({"effect": id, "index": i}));
|
||||
app.run("path.edit", json!({"effect": id, "index": index}));
|
||||
}
|
||||
}
|
||||
if icon_button(ui, ic::TRASH, tr("Remove"), false, 22.0).clicked() {
|
||||
app.run("path.remove", json!({"effect": id, "index": i}));
|
||||
app.run("path.remove", json!({"effect": id, "index": index}));
|
||||
}
|
||||
});
|
||||
}
|
||||
tool_properties(app, ui);
|
||||
}
|
||||
EffectKind::Filter(f) => filter_properties(app, ui, id, f),
|
||||
EffectKind::Filter(filter) => filter_properties(app, ui, id, filter),
|
||||
other => {
|
||||
ui.label(RichText::new(tr(other.name())).color(tk.text_dim));
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// The settings of generator effect `id`.
|
||||
fn generator_properties(app: &mut TextureCraftApp, ui: &mut Ui, id: u64, generator: &Generator) {
|
||||
let tk = Tokens::get(ui.ctx());
|
||||
ui.label(caption(tr("Generator")));
|
||||
egui::ComboBox::from_id_salt("gen_kind").selected_text(tr(generator.kind.label())).show_ui(ui, |ui| {
|
||||
for kind in GeneratorKind::ALL {
|
||||
if ui.selectable_label(kind == generator.kind, tr(kind.label())).clicked() {
|
||||
// Replace the generator kind: remove and add keeps ordering simple
|
||||
app.run("effect.remove", json!({"effect": id}));
|
||||
app.run("effect.add.generator", json!({"generator": format!("{kind:?}")}));
|
||||
}
|
||||
}
|
||||
});
|
||||
|
||||
let (mut level, mut softness, mut noise, mut noise_scale, mut invert) =
|
||||
(generator.level, generator.softness, generator.noise_amount, generator.noise_scale, generator.invert);
|
||||
let level_edit = slider_edit(ui, tr("Level"), &mut level, 0.0..=1.0, 2);
|
||||
let softness_edit = slider_edit(ui, tr("Softness"), &mut softness, 0.0..=1.0, 2);
|
||||
let noise_edit = slider_edit(ui, tr("Noise amount"), &mut noise, 0.0..=2.0, 2);
|
||||
let noise_scale_edit = slider_edit(ui, tr("Noise scale"), &mut noise_scale, 0.1..=64.0, 1);
|
||||
let invert_edit = ui.checkbox(&mut invert, tr("Invert")).changed().then_some(false);
|
||||
if let Some(merge) = level_edit.or(softness_edit).or(noise_edit).or(noise_scale_edit).or(invert_edit) {
|
||||
app.run(
|
||||
"effect.set",
|
||||
json!({"effect": id, "level": level, "softness": softness, "noise": noise, "noiseScale": noise_scale, "invert": invert, "merge": merge}),
|
||||
);
|
||||
}
|
||||
|
||||
if matches!(generator.kind, GeneratorKind::Curvature | GeneratorKind::EdgeWear) {
|
||||
curvature_detail_properties(app, ui, id, generator.detail.as_ref());
|
||||
}
|
||||
if !app.session.doc.baked.contains_key(&app.session.ts()) {
|
||||
ui.label(RichText::new(format!("{} {}", ic::WARNING, tr("Bake mesh maps (F8) for curvature, AO and thickness based generators."))).color(tk.warning));
|
||||
}
|
||||
}
|
||||
|
||||
/// The curvature mode and detail size weights of generator effect `id` (`detail` None: saved before detail sizes).
|
||||
fn curvature_detail_properties(app: &mut TextureCraftApp, ui: &mut Ui, id: u64, detail: Option<&CurvatureDetail>) {
|
||||
let tk = Tokens::get(ui.ctx());
|
||||
let shown = detail.cloned().unwrap_or_default();
|
||||
combo(ui, tr("Mode"), curvature_mode_label(shown.mode), |ui| {
|
||||
for mode in CurvatureMode::ALL {
|
||||
if ui.selectable_label(mode == shown.mode, curvature_mode_label(mode)).clicked() {
|
||||
app.run("effect.set", json!({"effect": id, "mode": format!("{mode:?}")}));
|
||||
}
|
||||
}
|
||||
});
|
||||
|
||||
ui.label(caption(tr("Detail sizes")));
|
||||
let mut weights = shown.weights;
|
||||
let mut edit = None;
|
||||
for (weight, size) in weights.iter_mut().zip(CurvatureDetail::SIZES) {
|
||||
edit = edit.or(slider_edit(ui, &format!("{size} px"), weight, 0.0..=1.0, 2));
|
||||
}
|
||||
if let Some(merge) = edit {
|
||||
app.run("effect.set", json!({"effect": id, "sizes": weights, "merge": merge}));
|
||||
}
|
||||
if detail.is_none() {
|
||||
ui.label(RichText::new(tr("Reads the curvature map as baked: changing the mode or a size turns detail sizes on.")).color(tk.text_dim));
|
||||
}
|
||||
}
|
||||
|
||||
/// The translated name of curvature mode `mode`.
|
||||
fn curvature_mode_label(mode: CurvatureMode) -> &'static str {
|
||||
match mode {
|
||||
CurvatureMode::Edges => tr("Edges"),
|
||||
CurvatureMode::Cavities => tr("Cavities"),
|
||||
CurvatureMode::Both => tr("Edges and cavities"),
|
||||
CurvatureMode::Raw => tr("Raw curvature"),
|
||||
}
|
||||
}
|
||||
|
||||
/// The histogram of what levels effect `eid` of `layer` remaps (its mask, or a content channel
|
||||
/// picked here), with the input range marked. Recomputed after a document change once no
|
||||
/// pointer button is held, so dragging a slider keeps the last one.
|
||||
@@ -2058,82 +2222,85 @@ fn levels_histogram(app: &TextureCraftApp, ui: &mut Ui, layer: &Layer, eid: Laye
|
||||
}
|
||||
}
|
||||
|
||||
/// The parameters of filter effect `id`.
|
||||
fn filter_properties(app: &mut TextureCraftApp, ui: &mut Ui, id: u64, f: &Filter) {
|
||||
/// The filter slot and the parameters of filter effect `id`
|
||||
fn filter_properties(app: &mut TextureCraftApp, ui: &mut Ui, id: u64, filter: &Filter) {
|
||||
let tk = Tokens::get(ui.ctx());
|
||||
let set = |app: &mut TextureCraftApp, key: &str, v: Value, merge: bool| {
|
||||
let mut p = json!({ "effect": id, "merge": merge });
|
||||
p[key] = v;
|
||||
app.run("effect.set", p);
|
||||
let set = |app: &mut TextureCraftApp, key: &str, value: Value, merge: bool| {
|
||||
let mut params = json!({ "effect": id, "merge": merge });
|
||||
params[key] = value;
|
||||
app.run("effect.set", params);
|
||||
};
|
||||
ui.label(caption(tr(f.label())));
|
||||
if let Filter::Hsl { hue, .. } = f {
|
||||
let mut h = hue * 360.0;
|
||||
if let Some(merge) = slider_edit(ui, tr("Hue shift (degrees)"), &mut h, -180.0..=180.0, 0) {
|
||||
set(app, "hue", json!(h / 360.0), merge);
|
||||
crate::filter_slot::show(app, ui, id, filter);
|
||||
|
||||
if let Filter::Hsl { hue, .. } = filter {
|
||||
let mut degrees = hue * 360.0;
|
||||
if let Some(merge) = slider_edit(ui, tr("Hue shift (degrees)"), &mut degrees, -180.0..=180.0, 0) {
|
||||
set(app, "hue", json!(degrees / 360.0), merge);
|
||||
}
|
||||
}
|
||||
for (key, label, mut v, lo, hi) in scalar_params(f) {
|
||||
|
||||
for (key, label, mut value, min, max) in scalar_params(filter) {
|
||||
let decimals = if matches!(key, "seed" | "levels") {
|
||||
0
|
||||
} else if hi - lo > 10.0 {
|
||||
} else if max - min > 10.0 {
|
||||
1
|
||||
} else {
|
||||
2
|
||||
};
|
||||
if let Some(merge) = slider_edit(ui, tr(label), &mut v, lo..=hi, decimals) {
|
||||
set(app, key, json!(v), merge);
|
||||
if let Some(merge) = slider_edit(ui, tr(label), &mut value, min..=max, decimals) {
|
||||
set(app, key, json!(value), merge);
|
||||
}
|
||||
}
|
||||
match f {
|
||||
|
||||
match filter {
|
||||
Filter::ColorBalance { shadows, midtones, highlights } => {
|
||||
for (key, label, rgb) in [("shadows", tr("Shadows"), shadows), ("midtones", tr("Midtones"), midtones), ("highlights", tr("Highlights"), highlights)]
|
||||
{
|
||||
ui.label(RichText::new(label).strong());
|
||||
let mut v = *rgb;
|
||||
let mut balance = *rgb;
|
||||
let mut edit = None;
|
||||
for (x, name) in v.iter_mut().zip([tr("Cyan / red"), tr("Magenta / green"), tr("Yellow / blue")]) {
|
||||
edit = edit.or(slider_edit(ui, name, x, -1.0..=1.0, 2));
|
||||
for (component, name) in balance.iter_mut().zip([tr("Cyan / red"), tr("Magenta / green"), tr("Yellow / blue")]) {
|
||||
edit = edit.or(slider_edit(ui, name, component, -1.0..=1.0, 2));
|
||||
}
|
||||
if let Some(merge) = edit {
|
||||
set(app, key, json!(v), merge);
|
||||
set(app, key, json!(balance), merge);
|
||||
}
|
||||
}
|
||||
}
|
||||
Filter::ReplaceColor { from, to, .. } => {
|
||||
for (key, label, rgb) in [("from", tr("Color to replace"), from), ("to", tr("Replacement color"), to)] {
|
||||
let mut v = *rgb;
|
||||
let mut color = *rgb;
|
||||
ui.horizontal(|ui| {
|
||||
if color_swatch(ui, &format!("replace_{key}_{id}"), &mut v, 36.0) {
|
||||
set(app, key, json!(v), false);
|
||||
if color_swatch(ui, &format!("replace_{key}_{id}"), &mut color, FILTER_SWATCH_WIDTH) {
|
||||
set(app, key, json!(color), false);
|
||||
}
|
||||
ui.label(label);
|
||||
});
|
||||
}
|
||||
ui.label(RichText::new(tr("Colors near the first shift towards the second, keeping their shading.")).size(10.5).color(tk.text_dim));
|
||||
ui.label(RichText::new(tr("Colors near the first shift towards the second, keeping their shading.")).size(FILTER_HINT_SIZE).color(tk.text_dim));
|
||||
}
|
||||
Filter::GradientMap { colors } => {
|
||||
let mut c = colors.clone();
|
||||
let mut stops = colors.clone();
|
||||
let mut changed = false;
|
||||
ui.horizontal_wrapped(|ui| {
|
||||
for (i, col) in c.iter_mut().enumerate() {
|
||||
changed |= color_swatch(ui, &format!("gradient_{id}_{i}"), col, 36.0);
|
||||
for (i, stop) in stops.iter_mut().enumerate() {
|
||||
changed |= color_swatch(ui, &format!("gradient_{id}_{i}"), stop, FILTER_SWATCH_WIDTH);
|
||||
}
|
||||
});
|
||||
ui.horizontal(|ui| {
|
||||
if ui.add_enabled(c.len() < 16, egui::Button::new(format!("{} {}", ic::PLUS, tr("Add color")))).clicked() {
|
||||
c.push(c.last().copied().unwrap_or([1.0; 3]));
|
||||
if ui.add_enabled(stops.len() < MAX_GRADIENT_STOPS, egui::Button::new(format!("{} {}", ic::PLUS, tr("Add color")))).clicked() {
|
||||
stops.push(stops.last().copied().unwrap_or([1.0; 3]));
|
||||
changed = true;
|
||||
}
|
||||
if ui.add_enabled(c.len() > 1, egui::Button::new(format!("{} {}", ic::MINUS, tr("Remove last")))).clicked() {
|
||||
c.pop();
|
||||
if ui.add_enabled(stops.len() > 1, egui::Button::new(format!("{} {}", ic::MINUS, tr("Remove last")))).clicked() {
|
||||
stops.pop();
|
||||
changed = true;
|
||||
}
|
||||
});
|
||||
if changed {
|
||||
set(app, "colors", json!(c), false);
|
||||
set(app, "colors", json!(stops), false);
|
||||
}
|
||||
ui.label(RichText::new(tr("Dark to light: the content's luminance picks a color along these stops.")).size(10.5).color(tk.text_dim));
|
||||
ui.label(RichText::new(tr("Dark to light: the content's luminance picks a color along these stops.")).size(FILTER_HINT_SIZE).color(tk.text_dim));
|
||||
}
|
||||
Filter::Warp { .. }
|
||||
| Filter::DirectionalBlur { .. }
|
||||
@@ -2144,7 +2311,7 @@ fn filter_properties(app: &mut TextureCraftApp, ui: &mut Ui, id: u64, f: &Filter
|
||||
| Filter::Bevel { .. }
|
||||
| Filter::Mosaic { .. }
|
||||
| Filter::Glow { .. } => {
|
||||
ui.label(RichText::new(tr("Works in texture space, like the blur: it does not cross UV seams.")).size(10.5).color(tk.text_dim));
|
||||
ui.label(RichText::new(tr("Works in texture space, like the blur: it does not cross UV seams.")).size(FILTER_HINT_SIZE).color(tk.text_dim));
|
||||
}
|
||||
_ => {}
|
||||
}
|
||||
|
||||
@@ -0,0 +1,120 @@
|
||||
//! The filter slot atop a filter's properties: thumbnail and name, opening a picker that swaps it
|
||||
|
||||
use egui::{Align2, FontId, Rect, Sense, Stroke, Ui, pos2, vec2};
|
||||
use egui_phosphor::regular as ic;
|
||||
use serde_json::json;
|
||||
use texturecraft_engine::core::{Filter, LayerId};
|
||||
use texturecraft_engine::filter_lib::{filter_effects, find};
|
||||
|
||||
use crate::TextureCraftApp;
|
||||
use crate::i18n::tr;
|
||||
use crate::resource_picker;
|
||||
use crate::resource_picker_item::ResourcePickerItem;
|
||||
use crate::shelf_preview::ShelfPreview;
|
||||
use crate::theme::Tokens;
|
||||
use crate::thumbs::Thumbs;
|
||||
use crate::widgets::elided;
|
||||
|
||||
const SLOT_HEIGHT: f32 = 52.0;
|
||||
const SLOT_ROUNDING: f32 = 3.0;
|
||||
const BORDER_WIDTH: f32 = 1.0;
|
||||
const THUMBNAIL_SIZE: f32 = 40.0;
|
||||
const THUMBNAIL_INSET: f32 = 6.0;
|
||||
const CAPTION_FONT_SIZE: f32 = 11.0;
|
||||
const NAME_FONT_SIZE: f32 = 13.0;
|
||||
/// Gap between the caption's and the name's centers
|
||||
const LINE_GAP: f32 = 15.0;
|
||||
const CARET_INSET: f32 = 14.0;
|
||||
const CARET_FONT_SIZE: f32 = 14.0;
|
||||
/// Gap between the slot and its keyboard focus outline
|
||||
const FOCUS_MARGIN: f32 = 2.0;
|
||||
|
||||
/// The slot of filter effect `effect`: a pick runs `effect.set {filter}`, masks offer only mask filters
|
||||
pub(crate) fn show(app: &mut TextureCraftApp, ui: &mut Ui, effect: u64, filter: &Filter) {
|
||||
let ctx = ui.ctx().clone();
|
||||
let on_mask = is_on_mask(app, effect);
|
||||
let current = find(filter.label()).map(|def| def.id);
|
||||
let thumbnail = current.and_then(|id| app.thumbs.filter(&ctx, id));
|
||||
let name = tr(filter.label());
|
||||
|
||||
let (rect, response) = ui.allocate_exact_size(vec2(ui.available_width(), SLOT_HEIGHT), Sense::click());
|
||||
response.widget_info(|| egui::WidgetInfo::labeled(egui::Role::ComboBox, true, name));
|
||||
|
||||
let popup = ui.make_persistent_id(("filter_picker", effect));
|
||||
let open_requested = take_open_request(&ctx, effect);
|
||||
|
||||
if response.clicked() || (open_requested && !egui::Popup::is_id_open(&ctx, popup)) {
|
||||
resource_picker::toggle(&ctx, popup);
|
||||
}
|
||||
|
||||
let highlighted = response.hovered() || egui::Popup::is_id_open(&ctx, popup);
|
||||
paint(ui, rect, highlighted, response.has_focus(), thumbnail.as_ref(), name);
|
||||
|
||||
let items = |thumbs: &mut Thumbs| {
|
||||
filter_effects()
|
||||
.iter()
|
||||
.filter(|def| def.mask || !on_mask)
|
||||
.map(|def| ResourcePickerItem { id: def.id, label: tr(def.label), group: tr(def.group), thumbnail: thumbs.filter(&ctx, def.id) })
|
||||
.collect()
|
||||
};
|
||||
let picked = resource_picker::show(&response, popup, &mut app.thumbs, current, items, ShelfPreview::Filter);
|
||||
if let Some(id) = picked.filter(|id| Some(*id) != current) {
|
||||
app.run("effect.set", json!({"effect": effect, "filter": id}));
|
||||
}
|
||||
}
|
||||
|
||||
/// Has the slot of filter effect `effect` open its picker if it shows this frame or the next, as Add filter does for the filter it adds
|
||||
pub(crate) fn open_picker_when_shown(ctx: &egui::Context, effect: u64) {
|
||||
let frame = ctx.cumulative_frame_nr();
|
||||
ctx.data_mut(|data| data.insert_temp(open_request_id(), (effect, frame)));
|
||||
}
|
||||
|
||||
/// Whether an open request for `effect`'s slot is waiting, removing it; a request older than a frame lapses
|
||||
fn take_open_request(ctx: &egui::Context, effect: u64) -> bool {
|
||||
let frame = ctx.cumulative_frame_nr();
|
||||
let request = ctx.data_mut(|data| data.remove_temp::<(u64, u64)>(open_request_id()));
|
||||
|
||||
// Properties can draw before or after the menu that asked, so a request lives for this frame and the next
|
||||
request.is_some_and(|(requested_effect, requested_frame)| requested_effect == effect && frame <= requested_frame + 1)
|
||||
}
|
||||
|
||||
/// Where the effect whose slot should open its picker waits
|
||||
fn open_request_id() -> egui::Id {
|
||||
egui::Id::unique("filter_slot_open_request")
|
||||
}
|
||||
|
||||
/// Whether filter effect `effect` sits in a mask rather than the layer content
|
||||
fn is_on_mask(app: &TextureCraftApp, effect: u64) -> bool {
|
||||
let project = &app.session.doc.project;
|
||||
let owner = project.effect(LayerId(effect)).and_then(|(owner, _)| project.layers.get(&owner));
|
||||
owner.and_then(|layer| layer.mask.as_ref()).is_some_and(|mask| mask.effects.iter().any(|masked| masked.id.0 == effect))
|
||||
}
|
||||
|
||||
/// The slot's box, highlighted while hovered or its picker is open and outlined while focused: thumbnail, "Filter" over the name, caret
|
||||
fn paint(ui: &Ui, rect: Rect, highlighted: bool, focused: bool, thumbnail: Option<&egui::TextureHandle>, name: &str) {
|
||||
let tk = Tokens::get(ui.ctx());
|
||||
let painter = ui.painter();
|
||||
let (fill, border) = if highlighted { (tk.row_hover, tk.button_border) } else { (tk.field, tk.field_border) };
|
||||
painter.rect(rect, SLOT_ROUNDING, fill, Stroke::new(BORDER_WIDTH, border), egui::StrokeKind::Inside);
|
||||
if focused {
|
||||
painter.rect_stroke(rect.expand(FOCUS_MARGIN), SLOT_ROUNDING, ui.visuals().selection.stroke, egui::StrokeKind::Outside);
|
||||
}
|
||||
|
||||
if let Some(texture) = thumbnail {
|
||||
let image = Rect::from_min_size(pos2(rect.left() + THUMBNAIL_INSET, rect.center().y - THUMBNAIL_SIZE * 0.5), vec2(THUMBNAIL_SIZE, THUMBNAIL_SIZE));
|
||||
painter.image(texture.id(), image, Rect::from_min_max(pos2(0.0, 0.0), pos2(1.0, 1.0)), egui::Color32::WHITE);
|
||||
}
|
||||
|
||||
// Long names are cut short rather than run under the thumbnail or the caret
|
||||
let text_left = rect.left() + THUMBNAIL_INSET * 2.0 + THUMBNAIL_SIZE;
|
||||
let text_right = rect.right() - CARET_INSET * 2.0;
|
||||
let text_center_x = (text_left + text_right) * 0.5;
|
||||
let lines = [(tr("Filter"), CAPTION_FONT_SIZE, tk.text_dim, -LINE_GAP * 0.5), (name, NAME_FONT_SIZE, tk.text_strong, LINE_GAP * 0.5)];
|
||||
for (text, size, color, offset) in lines {
|
||||
let galley = elided(painter, text, size, color, text_right - text_left);
|
||||
painter.galley(pos2(text_center_x, rect.center().y + offset) - galley.size() * 0.5, galley, color);
|
||||
}
|
||||
|
||||
let caret_color = if highlighted { tk.text } else { tk.text_dim };
|
||||
painter.text(pos2(rect.right() - CARET_INSET, rect.center().y), Align2::CENTER_CENTER, ic::CARET_DOWN, FontId::proportional(CARET_FONT_SIZE), caret_color);
|
||||
}
|
||||
@@ -304,6 +304,7 @@ pub const TABLE: &[(&str, &str)] = &[
|
||||
("Fill", "تعبئة"),
|
||||
("Fill the closed path (lasso)", "تعبئة المسار المغلق (حبل التحديد)"),
|
||||
("Fill the path (close it first)", "تعبئة المسار (أغلقه أولاً)"),
|
||||
("Filter", "مرشح"),
|
||||
("Filter the remaining noise while keeping edges and texture detail", "تصفية الضوضاء المتبقية مع الحفاظ على الحواف وتفاصيل الخامة"),
|
||||
("Filters", "مرشحات"),
|
||||
("Fine noise", "ضوضاء دقيقة"),
|
||||
@@ -677,6 +678,7 @@ pub const TABLE: &[(&str, &str)] = &[
|
||||
("Scratches", "خدوش"),
|
||||
("Screen", "شاشة (Screen)"),
|
||||
("Screenshot of the viewport", "لقطة شاشة لمنفذ العرض"),
|
||||
("Search", "بحث"),
|
||||
("Search all assets", "البحث في جميع الأصول"),
|
||||
("Search commands or keys", "البحث في الأوامر أو المفاتيح"),
|
||||
("Seed", "البذرة العشوائية (Seed)"),
|
||||
@@ -1040,4 +1042,33 @@ pub const TABLE: &[(&str, &str)] = &[
|
||||
("High Definition Mesh (HP)", "المجسم عالي الدقة (HP)"),
|
||||
("UV Seams", "فواصل UV"),
|
||||
("Project Mesh (LP)", "مجسم الإسقاط (LP)"),
|
||||
("Edges", "الحواف"),
|
||||
("Cavities", "التجاويف"),
|
||||
("Edges and cavities", "الحواف والتجاويف"),
|
||||
("Raw curvature", "الانحناء الخام"),
|
||||
("Detail sizes", "أحجام التفاصيل"),
|
||||
(
|
||||
"Reads the curvature map as baked: changing the mode or a size turns detail sizes on.",
|
||||
"يقرأ خريطة الانحناء كما خُبزت: تغيير الوضع أو أحد الأحجام يفعّل أحجام التفاصيل.",
|
||||
),
|
||||
(
|
||||
"A click fills what is under it; a dragged rectangle fills what it selects as it grows",
|
||||
"النقرة تملأ ما تحتها، والمستطيل المسحوب يملأ ما يحدده أثناء اتساعه",
|
||||
),
|
||||
("Contained center: fill polygons whose center is in the rectangle", "المركز المحتوى: تعبئة المضلعات التي يقع مركزها داخل المستطيل"),
|
||||
("Editing the quick mask: fills paint where painting is allowed. Press U to finish.", "تحرير القناع السريع: ترسم التعبئات حيث يُسمح بالرسم. اضغط U للإنهاء."),
|
||||
("Fill mode", "وضع التعبئة"),
|
||||
("Fill only polygons the camera sees (3D view)", "تعبئة المضلعات التي تراها الكاميرا فقط (العرض ثلاثي الأبعاد)"),
|
||||
("Hit-test", "اختبار الإصابة"),
|
||||
("How a rectangle selects polygons", "كيف يحدد المستطيل المضلعات"),
|
||||
("Intersection: fill polygons the rectangle touches", "التقاطع: تعبئة المضلعات التي يلمسها المستطيل"),
|
||||
("Rectangle fill", "تعبئة مستطيلة"),
|
||||
("Select a paint layer or a layer's mask to fill", "حدد طبقة رسم أو قناع طبقة للتعبئة"),
|
||||
("Selection mode", "وضع التحديد"),
|
||||
(
|
||||
"Triangle fills single triangles, Polygon whole quads and n-gons, Mesh the connected geometry, UV island the UV islands",
|
||||
"المثلث يملأ مثلثات منفردة، والمضلع رباعيات ومضلعات كاملة، والمجسم الهندسة المتصلة، وجزيرة UV جزر UV",
|
||||
),
|
||||
("Visible polygons only", "المضلعات المرئية فقط"),
|
||||
("\"{layer}\" can't be filled: select a paint layer or a layer's mask", "\"{layer}\" لا يمكن تعبئتها: حدد طبقة رسم أو قناع طبقة"),
|
||||
];
|
||||
@@ -328,6 +328,7 @@ pub const TABLE: &[(&str, &str)] = &[
|
||||
("Fill", "Füllung"),
|
||||
("Fill the closed path (lasso)", "Geschlossenen Pfad füllen (Lasso)"),
|
||||
("Fill the path (close it first)", "Pfad füllen (zuerst schließen)"),
|
||||
("Filter", "Filter"),
|
||||
("Filter the remaining noise while keeping edges and texture detail", "Restrauschen filtern und dabei Kanten und Texturdetails erhalten"),
|
||||
("Filters", "Filter"),
|
||||
("Fine noise", "Feines Rauschen"),
|
||||
@@ -716,6 +717,7 @@ pub const TABLE: &[(&str, &str)] = &[
|
||||
("Scratches", "Kratzer"),
|
||||
("Screen", "Negativ multiplizieren"),
|
||||
("Screenshot of the viewport", "Screenshot des Ansichtsfensters"),
|
||||
("Search", "Suchen"),
|
||||
("Search all assets", "Alle Assets durchsuchen"),
|
||||
("Search commands or keys", "Befehle oder Tasten suchen"),
|
||||
("Seed", "Startwert"),
|
||||
@@ -1083,4 +1085,36 @@ pub const TABLE: &[(&str, &str)] = &[
|
||||
("High Definition Mesh (HP)", "High-Poly-Mesh (HP)"),
|
||||
("UV Seams", "UV-Nähte"),
|
||||
("Project Mesh (LP)", "Projektions-Mesh (LP)"),
|
||||
("Edges", "Kanten"),
|
||||
("Cavities", "Vertiefungen"),
|
||||
("Edges and cavities", "Kanten und Vertiefungen"),
|
||||
("Raw curvature", "Rohe Krümmung"),
|
||||
("Detail sizes", "Detailgrößen"),
|
||||
(
|
||||
"Reads the curvature map as baked: changing the mode or a size turns detail sizes on.",
|
||||
"Liest die Krümmungskarte wie gebacken: Eine Änderung des Modus oder einer Größe schaltet die Detailgrößen ein.",
|
||||
),
|
||||
(
|
||||
"A click fills what is under it; a dragged rectangle fills what it selects as it grows",
|
||||
"Ein Klick füllt, was darunter liegt; ein aufgezogenes Rechteck füllt, was es beim Aufziehen erfasst",
|
||||
),
|
||||
("Contained center: fill polygons whose center is in the rectangle", "Enthaltener Mittelpunkt: Polygone füllen, deren Mittelpunkt im Rechteck liegt"),
|
||||
(
|
||||
"Editing the quick mask: fills paint where painting is allowed. Press U to finish.",
|
||||
"Schnellmaske wird bearbeitet: Füllungen markieren, wo Malen erlaubt ist. Zum Beenden U drücken.",
|
||||
),
|
||||
("Fill mode", "Füllmodus"),
|
||||
("Fill only polygons the camera sees (3D view)", "Nur Polygone füllen, die die Kamera sieht (3D-Ansicht)"),
|
||||
("Hit-test", "Treffertest"),
|
||||
("How a rectangle selects polygons", "Wie ein Rechteck Polygone auswählt"),
|
||||
("Intersection: fill polygons the rectangle touches", "Schnittmenge: Polygone füllen, die das Rechteck berührt"),
|
||||
("Rectangle fill", "Rechteckfüllung"),
|
||||
("Select a paint layer or a layer's mask to fill", "Wähle zum Füllen eine Malebene oder eine Ebenenmaske"),
|
||||
("Selection mode", "Auswahlmodus"),
|
||||
(
|
||||
"Triangle fills single triangles, Polygon whole quads and n-gons, Mesh the connected geometry, UV island the UV islands",
|
||||
"Dreieck füllt einzelne Dreiecke, Polygon ganze Vierecke und N-Ecke, Mesh die zusammenhängende Geometrie, UV-Insel die UV-Inseln",
|
||||
),
|
||||
("Visible polygons only", "Nur sichtbare Polygone"),
|
||||
("\"{layer}\" can't be filled: select a paint layer or a layer's mask", "\"{layer}\" kann nicht gefüllt werden: Wähle eine Malebene oder eine Ebenenmaske"),
|
||||
];
|
||||
@@ -319,6 +319,7 @@ pub const TABLE: &[(&str, &str)] = &[
|
||||
("Fill", "Relleno"),
|
||||
("Fill the closed path (lasso)", "Rellenar el trazado cerrado (lazo)"),
|
||||
("Fill the path (close it first)", "Rellenar el trazado (ciérralo antes)"),
|
||||
("Filter", "Filtro"),
|
||||
("Filter the remaining noise while keeping edges and texture detail", "Filtrar el ruido restante conservando los bordes y el detalle de la textura"),
|
||||
("Filters", "Filtros"),
|
||||
("Fine noise", "Ruido fino"),
|
||||
@@ -704,6 +705,7 @@ pub const TABLE: &[(&str, &str)] = &[
|
||||
("Scratches", "Arañazos"),
|
||||
("Screen", "Trama"),
|
||||
("Screenshot of the viewport", "Captura de la ventana gráfica"),
|
||||
("Search", "Buscar"),
|
||||
("Search all assets", "Buscar en todos los recursos"),
|
||||
("Search commands or keys", "Buscar comandos o teclas"),
|
||||
("Seed", "Semilla"),
|
||||
@@ -1068,4 +1070,39 @@ pub const TABLE: &[(&str, &str)] = &[
|
||||
("High Definition Mesh (HP)", "Malla de alta resolución (HP)"),
|
||||
("UV Seams", "Costuras UV"),
|
||||
("Project Mesh (LP)", "Malla de proyección (LP)"),
|
||||
("Edges", "Bordes"),
|
||||
("Cavities", "Cavidades"),
|
||||
("Edges and cavities", "Bordes y cavidades"),
|
||||
("Raw curvature", "Curvatura sin procesar"),
|
||||
("Detail sizes", "Tamaños de detalle"),
|
||||
(
|
||||
"Reads the curvature map as baked: changing the mode or a size turns detail sizes on.",
|
||||
"Lee el mapa de curvatura tal como se horneó: cambiar el modo o un tamaño activa los tamaños de detalle.",
|
||||
),
|
||||
(
|
||||
"A click fills what is under it; a dragged rectangle fills what it selects as it grows",
|
||||
"Un clic rellena lo que hay debajo; un rectángulo arrastrado rellena lo que selecciona mientras crece",
|
||||
),
|
||||
("Contained center: fill polygons whose center is in the rectangle", "Centro contenido: rellenar los polígonos cuyo centro está en el rectángulo"),
|
||||
(
|
||||
"Editing the quick mask: fills paint where painting is allowed. Press U to finish.",
|
||||
"Editando la máscara rápida: los rellenos pintan donde se permite pintar. Pulsa U para terminar.",
|
||||
),
|
||||
("Fill mode", "Modo de relleno"),
|
||||
("Fill only polygons the camera sees (3D view)", "Rellenar solo los polígonos que ve la cámara (vista 3D)"),
|
||||
("Hit-test", "Prueba de selección"),
|
||||
("How a rectangle selects polygons", "Cómo selecciona polígonos un rectángulo"),
|
||||
("Intersection: fill polygons the rectangle touches", "Intersección: rellenar los polígonos que toca el rectángulo"),
|
||||
("Rectangle fill", "Relleno rectangular"),
|
||||
("Select a paint layer or a layer's mask to fill", "Selecciona una capa de pintura o una máscara de capa para rellenar"),
|
||||
("Selection mode", "Modo de selección"),
|
||||
(
|
||||
"Triangle fills single triangles, Polygon whole quads and n-gons, Mesh the connected geometry, UV island the UV islands",
|
||||
"Triángulo rellena triángulos sueltos, Polígono cuadriláteros y n-gonos enteros, Malla la geometría conectada, Isla UV las islas UV",
|
||||
),
|
||||
("Visible polygons only", "Solo polígonos visibles"),
|
||||
(
|
||||
"\"{layer}\" can't be filled: select a paint layer or a layer's mask",
|
||||
"\"{layer}\" no se puede rellenar: selecciona una capa de pintura o una máscara de capa",
|
||||
),
|
||||
];
|
||||
@@ -331,6 +331,7 @@ pub const TABLE: &[(&str, &str)] = &[
|
||||
("Fill", "Remplissage"),
|
||||
("Fill the closed path (lasso)", "Remplir le tracé fermé (lasso)"),
|
||||
("Fill the path (close it first)", "Remplir le tracé (le fermer d'abord)"),
|
||||
("Filter", "Filtre"),
|
||||
("Filter the remaining noise while keeping edges and texture detail", "Filtrer le bruit restant en préservant les contours et les détails de texture"),
|
||||
("Filters", "Filtres"),
|
||||
("Fine noise", "Bruit fin"),
|
||||
@@ -722,6 +723,7 @@ pub const TABLE: &[(&str, &str)] = &[
|
||||
("Scratches", "Rayures"),
|
||||
("Screen", "Superposition"),
|
||||
("Screenshot of the viewport", "Capture de la fenêtre d'affichage"),
|
||||
("Search", "Rechercher"),
|
||||
("Search all assets", "Rechercher dans toutes les ressources"),
|
||||
("Search commands or keys", "Rechercher des commandes ou des touches"),
|
||||
("Seed", "Graine"),
|
||||
@@ -1092,4 +1094,39 @@ pub const TABLE: &[(&str, &str)] = &[
|
||||
("High Definition Mesh (HP)", "Maillage haute définition (HP)"),
|
||||
("UV Seams", "Coutures UV"),
|
||||
("Project Mesh (LP)", "Maillage de projection (LP)"),
|
||||
("Edges", "Arêtes"),
|
||||
("Cavities", "Cavités"),
|
||||
("Edges and cavities", "Arêtes et cavités"),
|
||||
("Raw curvature", "Courbure brute"),
|
||||
("Detail sizes", "Tailles de détail"),
|
||||
(
|
||||
"Reads the curvature map as baked: changing the mode or a size turns detail sizes on.",
|
||||
"Lit la carte de courbure telle que calculée : changer le mode ou une taille active les tailles de détail.",
|
||||
),
|
||||
(
|
||||
"A click fills what is under it; a dragged rectangle fills what it selects as it grows",
|
||||
"Un clic remplit ce qui est dessous ; un rectangle tracé remplit ce qu'il sélectionne à mesure qu'il grandit",
|
||||
),
|
||||
("Contained center: fill polygons whose center is in the rectangle", "Centre contenu : remplir les polygones dont le centre est dans le rectangle"),
|
||||
(
|
||||
"Editing the quick mask: fills paint where painting is allowed. Press U to finish.",
|
||||
"Modification du masque rapide : les remplissages peignent là où la peinture est autorisée. Appuyez sur U pour terminer.",
|
||||
),
|
||||
("Fill mode", "Mode de remplissage"),
|
||||
("Fill only polygons the camera sees (3D view)", "Remplir uniquement les polygones que voit la caméra (vue 3D)"),
|
||||
("Hit-test", "Test de sélection"),
|
||||
("How a rectangle selects polygons", "Comment un rectangle sélectionne les polygones"),
|
||||
("Intersection: fill polygons the rectangle touches", "Intersection : remplir les polygones que touche le rectangle"),
|
||||
("Rectangle fill", "Remplissage rectangulaire"),
|
||||
("Select a paint layer or a layer's mask to fill", "Sélectionnez un calque de peinture ou un masque de calque à remplir"),
|
||||
("Selection mode", "Mode de sélection"),
|
||||
(
|
||||
"Triangle fills single triangles, Polygon whole quads and n-gons, Mesh the connected geometry, UV island the UV islands",
|
||||
"Triangle remplit des triangles seuls, Polygone des quads et n-gones entiers, Maillage la géométrie connectée, Îlot UV les îlots UV",
|
||||
),
|
||||
("Visible polygons only", "Polygones visibles uniquement"),
|
||||
(
|
||||
"\"{layer}\" can't be filled: select a paint layer or a layer's mask",
|
||||
"« {layer} » ne peut pas être rempli : sélectionnez un calque de peinture ou un masque de calque",
|
||||
),
|
||||
];
|
||||
@@ -325,6 +325,7 @@ pub const TABLE: &[(&str, &str)] = &[
|
||||
("Fill", "Riempimento"),
|
||||
("Fill the closed path (lasso)", "Riempi il tracciato chiuso (lazo)"),
|
||||
("Fill the path (close it first)", "Riempi il tracciato (prima chiudilo)"),
|
||||
("Filter", "Filtro"),
|
||||
("Filter the remaining noise while keeping edges and texture detail", "Filtra il rumore residuo preservando i bordi e i dettagli della texture"),
|
||||
("Filters", "Filtri"),
|
||||
("Fine noise", "Rumore fine"),
|
||||
@@ -713,6 +714,7 @@ pub const TABLE: &[(&str, &str)] = &[
|
||||
("Scratches", "Graffi"),
|
||||
("Screen", "Scolora"),
|
||||
("Screenshot of the viewport", "Screenshot della viewport"),
|
||||
("Search", "Cerca"),
|
||||
("Search all assets", "Cerca in tutte le risorse"),
|
||||
("Search commands or keys", "Cerca comandi o tasti"),
|
||||
("Seed", "Seme"),
|
||||
@@ -1077,4 +1079,39 @@ pub const TABLE: &[(&str, &str)] = &[
|
||||
("High Definition Mesh (HP)", "Mesh ad alta risoluzione (HP)"),
|
||||
("UV Seams", "Cuciture UV"),
|
||||
("Project Mesh (LP)", "Mesh di proiezione (LP)"),
|
||||
("Edges", "Bordi"),
|
||||
("Cavities", "Cavità"),
|
||||
("Edges and cavities", "Bordi e cavità"),
|
||||
("Raw curvature", "Curvatura grezza"),
|
||||
("Detail sizes", "Dimensioni del dettaglio"),
|
||||
(
|
||||
"Reads the curvature map as baked: changing the mode or a size turns detail sizes on.",
|
||||
"Legge la mappa di curvatura così come è stata calcolata: cambiare la modalità o una dimensione attiva le dimensioni del dettaglio.",
|
||||
),
|
||||
(
|
||||
"A click fills what is under it; a dragged rectangle fills what it selects as it grows",
|
||||
"Un clic riempie ciò che c'è sotto; un rettangolo trascinato riempie ciò che seleziona mentre si allarga",
|
||||
),
|
||||
("Contained center: fill polygons whose center is in the rectangle", "Centro contenuto: riempi i poligoni il cui centro è nel rettangolo"),
|
||||
(
|
||||
"Editing the quick mask: fills paint where painting is allowed. Press U to finish.",
|
||||
"Modifica della maschera rapida: i riempimenti dipingono le aree in cui è consentito dipingere. Premi U per terminare.",
|
||||
),
|
||||
("Fill mode", "Modalità di riempimento"),
|
||||
("Fill only polygons the camera sees (3D view)", "Riempi solo i poligoni visti dalla camera (vista 3D)"),
|
||||
("Hit-test", "Test di selezione"),
|
||||
("How a rectangle selects polygons", "Come un rettangolo seleziona i poligoni"),
|
||||
("Intersection: fill polygons the rectangle touches", "Intersezione: riempi i poligoni toccati dal rettangolo"),
|
||||
("Rectangle fill", "Riempimento rettangolare"),
|
||||
("Select a paint layer or a layer's mask to fill", "Seleziona un livello di pittura o una maschera di livello da riempire"),
|
||||
("Selection mode", "Modalità di selezione"),
|
||||
(
|
||||
"Triangle fills single triangles, Polygon whole quads and n-gons, Mesh the connected geometry, UV island the UV islands",
|
||||
"Triangolo riempie singoli triangoli, Poligono quad e n-goni interi, Mesh la geometria connessa, Isola UV le isole UV",
|
||||
),
|
||||
("Visible polygons only", "Solo poligoni visibili"),
|
||||
(
|
||||
"\"{layer}\" can't be filled: select a paint layer or a layer's mask",
|
||||
"\"{layer}\" non può essere riempito: seleziona un livello di pittura o una maschera di livello",
|
||||
),
|
||||
];
|
||||
@@ -316,6 +316,7 @@ pub const TABLE: &[(&str, &str)] = &[
|
||||
("Fill", "塗りつぶし"),
|
||||
("Fill the closed path (lasso)", "閉じたパスを塗りつぶし (なげなわ)"),
|
||||
("Fill the path (close it first)", "パスを塗りつぶし (先にパスを閉じる)"),
|
||||
("Filter", "フィルター"),
|
||||
("Filter the remaining noise while keeping edges and texture detail", "エッジとテクスチャのディテールを保ちながら残りのノイズを除去"),
|
||||
("Filters", "フィルター"),
|
||||
("Fine noise", "細かいノイズ"),
|
||||
@@ -695,6 +696,7 @@ pub const TABLE: &[(&str, &str)] = &[
|
||||
("Scratches", "引っかき傷"),
|
||||
("Screen", "スクリーン"),
|
||||
("Screenshot of the viewport", "ビューポートのスクリーンショット"),
|
||||
("Search", "検索"),
|
||||
("Search all assets", "すべてのアセットを検索"),
|
||||
("Search commands or keys", "コマンドまたはキーを検索"),
|
||||
("Seed", "シード"),
|
||||
@@ -1062,4 +1064,39 @@ pub const TABLE: &[(&str, &str)] = &[
|
||||
("High Definition Mesh (HP)", "ハイポリメッシュ (HP)"),
|
||||
("UV Seams", "UVシーム"),
|
||||
("Project Mesh (LP)", "投影メッシュ (LP)"),
|
||||
("Edges", "エッジ"),
|
||||
("Cavities", "くぼみ"),
|
||||
("Edges and cavities", "エッジとくぼみ"),
|
||||
("Raw curvature", "生の曲率"),
|
||||
("Detail sizes", "ディテールサイズ"),
|
||||
(
|
||||
"Reads the curvature map as baked: changing the mode or a size turns detail sizes on.",
|
||||
"曲率マップをベイクされたまま読み取ります。モードやサイズを変更するとディテールサイズが有効になります。",
|
||||
),
|
||||
(
|
||||
"A click fills what is under it; a dragged rectangle fills what it selects as it grows",
|
||||
"クリックでその下を塗りつぶし、ドラッグした矩形は広げるにつれて選択した範囲を塗りつぶします",
|
||||
),
|
||||
("Contained center: fill polygons whose center is in the rectangle", "中心を含む: 中心が矩形内にあるポリゴンを塗りつぶします"),
|
||||
(
|
||||
"Editing the quick mask: fills paint where painting is allowed. Press U to finish.",
|
||||
"クイックマスク編集中: 塗りつぶしでペイントを許可する範囲を塗ります。Uキーで終了します。",
|
||||
),
|
||||
("Fill mode", "塗りつぶしモード"),
|
||||
("Fill only polygons the camera sees (3D view)", "カメラから見えるポリゴンだけを塗りつぶします (3Dビュー)"),
|
||||
("Hit-test", "ヒットテスト"),
|
||||
("How a rectangle selects polygons", "矩形がポリゴンを選択する方法"),
|
||||
("Intersection: fill polygons the rectangle touches", "交差: 矩形が触れるポリゴンを塗りつぶします"),
|
||||
("Rectangle fill", "矩形塗りつぶし"),
|
||||
("Select a paint layer or a layer's mask to fill", "塗りつぶすペイントレイヤーまたはレイヤーマスクを選択してください"),
|
||||
("Selection mode", "選択モード"),
|
||||
(
|
||||
"Triangle fills single triangles, Polygon whole quads and n-gons, Mesh the connected geometry, UV island the UV islands",
|
||||
"三角形は個々の三角形、ポリゴンは四角形やNゴン全体、メッシュはつながったジオメトリ、UVアイランドはUVアイランドを塗りつぶします",
|
||||
),
|
||||
("Visible polygons only", "表示されているポリゴンのみ"),
|
||||
(
|
||||
"\"{layer}\" can't be filled: select a paint layer or a layer's mask",
|
||||
"「{layer}」は塗りつぶせません: ペイントレイヤーまたはレイヤーマスクを選択してください",
|
||||
),
|
||||
];
|
||||
@@ -313,6 +313,7 @@ pub const TABLE: &[(&str, &str)] = &[
|
||||
("Fill", "채우기"),
|
||||
("Fill the closed path (lasso)", "닫힌 패스를 채웁니다 (올가미)"),
|
||||
("Fill the path (close it first)", "패스를 채웁니다 (먼저 패스를 닫으세요)"),
|
||||
("Filter", "필터"),
|
||||
("Filter the remaining noise while keeping edges and texture detail", "가장자리와 텍스처 디테일을 유지하면서 남은 노이즈를 걸러냅니다"),
|
||||
("Filters", "필터"),
|
||||
("Fine noise", "미세 노이즈"),
|
||||
@@ -686,6 +687,7 @@ pub const TABLE: &[(&str, &str)] = &[
|
||||
("Scratches", "스크래치"),
|
||||
("Screen", "스크린"),
|
||||
("Screenshot of the viewport", "뷰포트 스크린샷"),
|
||||
("Search", "검색"),
|
||||
("Search all assets", "모든 에셋 검색"),
|
||||
("Search commands or keys", "명령 또는 키 검색"),
|
||||
("Seed", "시드"),
|
||||
@@ -1050,4 +1052,36 @@ pub const TABLE: &[(&str, &str)] = &[
|
||||
("High Definition Mesh (HP)", "하이 폴리 메시 (HP)"),
|
||||
("UV Seams", "UV 심"),
|
||||
("Project Mesh (LP)", "투영 메시 (LP)"),
|
||||
("Edges", "가장자리"),
|
||||
("Cavities", "오목한 부분"),
|
||||
("Edges and cavities", "가장자리와 오목한 부분"),
|
||||
("Raw curvature", "원시 곡률"),
|
||||
("Detail sizes", "디테일 크기"),
|
||||
(
|
||||
"Reads the curvature map as baked: changing the mode or a size turns detail sizes on.",
|
||||
"곡률 맵을 베이크된 그대로 읽습니다. 모드나 크기를 바꾸면 디테일 크기가 켜집니다.",
|
||||
),
|
||||
(
|
||||
"A click fills what is under it; a dragged rectangle fills what it selects as it grows",
|
||||
"클릭하면 아래에 있는 것을 채우고, 드래그한 사각형은 커지면서 선택한 것을 채웁니다",
|
||||
),
|
||||
("Contained center: fill polygons whose center is in the rectangle", "중심 포함: 중심이 사각형 안에 있는 폴리곤을 채웁니다"),
|
||||
(
|
||||
"Editing the quick mask: fills paint where painting is allowed. Press U to finish.",
|
||||
"퀵 마스크 편집 중: 채우기로 페인팅을 허용할 영역을 칠합니다. U를 눌러 완료하세요.",
|
||||
),
|
||||
("Fill mode", "채우기 모드"),
|
||||
("Fill only polygons the camera sees (3D view)", "카메라에 보이는 폴리곤만 채웁니다 (3D 뷰)"),
|
||||
("Hit-test", "히트 테스트"),
|
||||
("How a rectangle selects polygons", "사각형이 폴리곤을 선택하는 방식"),
|
||||
("Intersection: fill polygons the rectangle touches", "교차: 사각형에 닿는 폴리곤을 채웁니다"),
|
||||
("Rectangle fill", "사각형 채우기"),
|
||||
("Select a paint layer or a layer's mask to fill", "채울 페인트 레이어나 레이어 마스크를 선택하세요"),
|
||||
("Selection mode", "선택 모드"),
|
||||
(
|
||||
"Triangle fills single triangles, Polygon whole quads and n-gons, Mesh the connected geometry, UV island the UV islands",
|
||||
"삼각형은 개별 삼각형, 폴리곤은 사각형과 N각형 전체, 메시는 연결된 지오메트리, UV 아일랜드는 UV 아일랜드를 채웁니다",
|
||||
),
|
||||
("Visible polygons only", "보이는 폴리곤만"),
|
||||
("\"{layer}\" can't be filled: select a paint layer or a layer's mask", "\"{layer}\"은(는) 채울 수 없습니다: 페인트 레이어나 레이어 마스크를 선택하세요"),
|
||||
];
|
||||
@@ -319,6 +319,7 @@ pub const TABLE: &[(&str, &str)] = &[
|
||||
("Fill", "Preenchimento"),
|
||||
("Fill the closed path (lasso)", "Preencher o caminho fechado (laço)"),
|
||||
("Fill the path (close it first)", "Preencher o caminho (feche-o primeiro)"),
|
||||
("Filter", "Filtro"),
|
||||
("Filter the remaining noise while keeping edges and texture detail", "Filtrar o ruído restante preservando bordas e detalhes de textura"),
|
||||
("Filters", "Filtros"),
|
||||
("Fine noise", "Ruído fino"),
|
||||
@@ -701,6 +702,7 @@ pub const TABLE: &[(&str, &str)] = &[
|
||||
("Scratches", "Arranhões"),
|
||||
("Screen", "Tela"),
|
||||
("Screenshot of the viewport", "Captura de tela da viewport"),
|
||||
("Search", "Pesquisar"),
|
||||
("Search all assets", "Pesquisar em todos os recursos"),
|
||||
("Search commands or keys", "Pesquisar comandos ou teclas"),
|
||||
("Seed", "Semente"),
|
||||
@@ -1065,4 +1067,39 @@ pub const TABLE: &[(&str, &str)] = &[
|
||||
("High Definition Mesh (HP)", "Malha de alta resolução (HP)"),
|
||||
("UV Seams", "Costuras UV"),
|
||||
("Project Mesh (LP)", "Malha de projeção (LP)"),
|
||||
("Edges", "Bordas"),
|
||||
("Cavities", "Cavidades"),
|
||||
("Edges and cavities", "Bordas e cavidades"),
|
||||
("Raw curvature", "Curvatura bruta"),
|
||||
("Detail sizes", "Tamanhos de detalhe"),
|
||||
(
|
||||
"Reads the curvature map as baked: changing the mode or a size turns detail sizes on.",
|
||||
"Lê o mapa de curvatura como foi assado: mudar o modo ou um tamanho ativa os tamanhos de detalhe.",
|
||||
),
|
||||
(
|
||||
"A click fills what is under it; a dragged rectangle fills what it selects as it grows",
|
||||
"Um clique preenche o que está embaixo; um retângulo arrastado preenche o que seleciona enquanto cresce",
|
||||
),
|
||||
("Contained center: fill polygons whose center is in the rectangle", "Centro contido: preencher os polígonos cujo centro está no retângulo"),
|
||||
(
|
||||
"Editing the quick mask: fills paint where painting is allowed. Press U to finish.",
|
||||
"Editando a máscara rápida: os preenchimentos pintam onde a pintura é permitida. Pressione U para concluir.",
|
||||
),
|
||||
("Fill mode", "Modo de preenchimento"),
|
||||
("Fill only polygons the camera sees (3D view)", "Preencher apenas os polígonos que a câmera vê (vista 3D)"),
|
||||
("Hit-test", "Teste de seleção"),
|
||||
("How a rectangle selects polygons", "Como um retângulo seleciona polígonos"),
|
||||
("Intersection: fill polygons the rectangle touches", "Interseção: preencher os polígonos que o retângulo toca"),
|
||||
("Rectangle fill", "Preenchimento retangular"),
|
||||
("Select a paint layer or a layer's mask to fill", "Selecione uma camada de pintura ou uma máscara de camada para preencher"),
|
||||
("Selection mode", "Modo de seleção"),
|
||||
(
|
||||
"Triangle fills single triangles, Polygon whole quads and n-gons, Mesh the connected geometry, UV island the UV islands",
|
||||
"Triângulo preenche triângulos isolados, Polígono quads e n-gons inteiros, Malha a geometria conectada, Ilha UV as ilhas UV",
|
||||
),
|
||||
("Visible polygons only", "Apenas polígonos visíveis"),
|
||||
(
|
||||
"\"{layer}\" can't be filled: select a paint layer or a layer's mask",
|
||||
"\"{layer}\" não pode ser preenchida: selecione uma camada de pintura ou uma máscara de camada",
|
||||
),
|
||||
];
|
||||
@@ -286,6 +286,7 @@ pub const TABLE: &[(&str, &str)] = &[
|
||||
("Fill", "填充"),
|
||||
("Fill the closed path (lasso)", "填充闭合路径(套索)"),
|
||||
("Fill the path (close it first)", "填充路径(请先闭合)"),
|
||||
("Filter", "滤镜"),
|
||||
("Filter the remaining noise while keeping edges and texture detail", "在保留边缘和纹理细节的同时过滤剩余噪点"),
|
||||
("Filters", "滤镜"),
|
||||
("Fine noise", "细噪波"),
|
||||
@@ -647,6 +648,7 @@ pub const TABLE: &[(&str, &str)] = &[
|
||||
("Scratches", "划痕"),
|
||||
("Screen", "滤色"),
|
||||
("Screenshot of the viewport", "视口截图"),
|
||||
("Search", "搜索"),
|
||||
("Search all assets", "搜索所有资产"),
|
||||
("Search commands or keys", "搜索命令或按键"),
|
||||
("Seed", "随机种子"),
|
||||
@@ -1008,4 +1010,27 @@ pub const TABLE: &[(&str, &str)] = &[
|
||||
("High Definition Mesh (HP)", "高模网格 (HP)"),
|
||||
("UV Seams", "UV 接缝"),
|
||||
("Project Mesh (LP)", "投射网格 (LP)"),
|
||||
("Edges", "边缘"),
|
||||
("Cavities", "凹陷"),
|
||||
("Edges and cavities", "边缘和凹陷"),
|
||||
("Raw curvature", "原始曲率"),
|
||||
("Detail sizes", "细节尺寸"),
|
||||
("Reads the curvature map as baked: changing the mode or a size turns detail sizes on.", "按烘焙原样读取曲率贴图:更改模式或尺寸会启用细节尺寸。"),
|
||||
("A click fills what is under it; a dragged rectangle fills what it selects as it grows", "单击填充其下方的内容;拖出的矩形在扩大时填充其选中的内容"),
|
||||
("Contained center: fill polygons whose center is in the rectangle", "包含中心:填充中心位于矩形内的多边形"),
|
||||
("Editing the quick mask: fills paint where painting is allowed. Press U to finish.", "正在编辑快速遮罩:填充绘制在允许绘画的区域。按 U 完成。"),
|
||||
("Fill mode", "填充模式"),
|
||||
("Fill only polygons the camera sees (3D view)", "仅填充相机可见的多边形(3D 视图)"),
|
||||
("Hit-test", "命中测试"),
|
||||
("How a rectangle selects polygons", "矩形选择多边形的方式"),
|
||||
("Intersection: fill polygons the rectangle touches", "相交:填充矩形触及的多边形"),
|
||||
("Rectangle fill", "矩形填充"),
|
||||
("Select a paint layer or a layer's mask to fill", "选择要填充的绘画图层或图层遮罩"),
|
||||
("Selection mode", "选择模式"),
|
||||
(
|
||||
"Triangle fills single triangles, Polygon whole quads and n-gons, Mesh the connected geometry, UV island the UV islands",
|
||||
"三角形填充单个三角形,多边形填充整个四边形和 n 边形,网格填充相连的几何体,UV 岛填充 UV 岛",
|
||||
),
|
||||
("Visible polygons only", "仅可见多边形"),
|
||||
("\"{layer}\" can't be filled: select a paint layer or a layer's mask", "“{layer}”无法填充:请选择绘画图层或图层遮罩"),
|
||||
];
|
||||
@@ -13,13 +13,15 @@ pub mod control;
|
||||
pub mod dock;
|
||||
pub mod docking;
|
||||
pub mod export_templates;
|
||||
mod filter_slot;
|
||||
pub mod fonts;
|
||||
pub mod gpu;
|
||||
pub mod i18n;
|
||||
pub mod keymap;
|
||||
mod mask_preview_image;
|
||||
mod mask_shape;
|
||||
mod material_preview_image;
|
||||
pub mod menus;
|
||||
mod orb_shape;
|
||||
pub mod parity;
|
||||
mod preview_image;
|
||||
mod preview_request;
|
||||
@@ -27,13 +29,17 @@ mod preview_worker;
|
||||
pub mod profile;
|
||||
pub mod properties_popup;
|
||||
pub mod render_mode;
|
||||
mod resource_picker;
|
||||
mod resource_picker_item;
|
||||
pub mod shelf;
|
||||
pub mod shelf_preview;
|
||||
mod soft_box;
|
||||
pub mod state;
|
||||
pub mod theme;
|
||||
pub mod thumbs;
|
||||
pub mod titlebar;
|
||||
pub mod toolbar;
|
||||
pub mod uv_paint_point;
|
||||
pub mod viewport;
|
||||
pub mod web_files;
|
||||
pub mod widgets;
|
||||
@@ -111,6 +117,8 @@ pub struct TextureCraftApp {
|
||||
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>,
|
||||
/// 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.
|
||||
pub placing_decal: Option<texturecraft_engine::core::LayerId>,
|
||||
/// The Properties popup a right click in a view opens.
|
||||
@@ -134,19 +142,23 @@ pub struct TextureCraftApp {
|
||||
}
|
||||
|
||||
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 {
|
||||
theme::install(&cc.egui_ctx);
|
||||
// Bakes cast their rays on a GPU device of their own (created on the first bake).
|
||||
|
||||
// Bakes cast their rays on a GPU device of their own (created on the first bake)
|
||||
#[cfg(not(target_arch = "wasm32"))]
|
||||
texturecraft_engine::bake::install_gpu_tracer(Arc::new(texturecraft_render::gpu_bake::GpuBaker::new()));
|
||||
let gpu = cc.wgpu_render_state.as_ref().map(|rs| gpu::init(rs, &cc.egui_ctx));
|
||||
// The first run speaks the OS (or browser) language.
|
||||
let ui = cc.storage.and_then(|s| eframe::get_value::<UiState>(s, "ui")).unwrap_or_else(|| {
|
||||
let gpu = cc.wgpu_render_state.as_ref().map(|render_state| gpu::init(render_state, &cc.egui_ctx));
|
||||
|
||||
// The first run speaks the OS (or browser) language
|
||||
let ui = cc.storage.and_then(|storage| eframe::get_value::<UiState>(storage, "ui")).unwrap_or_else(|| {
|
||||
let mut ui = UiState::default();
|
||||
ui.prefs.language = i18n::os_language().into();
|
||||
ui
|
||||
});
|
||||
let next_autosave = ui.prefs.autosave_minutes as f64 * 60.0;
|
||||
|
||||
let mut app = TextureCraftApp {
|
||||
camera_glide: None,
|
||||
session,
|
||||
@@ -167,6 +179,7 @@ impl TextureCraftApp {
|
||||
brushes: None,
|
||||
render: render_mode::RenderView::default(),
|
||||
last_paint_point: None,
|
||||
last_paint_uv: None,
|
||||
placing_decal: None,
|
||||
properties_popup: None,
|
||||
render_state: cc.wgpu_render_state.clone(),
|
||||
@@ -182,17 +195,21 @@ impl TextureCraftApp {
|
||||
app.ui.windows.new_project = false;
|
||||
i18n::set_language(&app.ui.prefs.language);
|
||||
export_templates::load_library(&mut app, cc.storage);
|
||||
|
||||
#[cfg(not(target_arch = "wasm32"))]
|
||||
{
|
||||
// The first window of the process fixes it; a new folder applies on restart.
|
||||
// The first window of the process fixes it; a new folder applies on restart
|
||||
let _ = DATA_FOLDER.set(data_folder(&app.ui.prefs.data_folder));
|
||||
// An export folder still at the default follows the data folder.
|
||||
|
||||
// An export folder still at the default follows the data folder
|
||||
if app.ui.export.dir == data_folder("").join("export").display().to_string() {
|
||||
app.ui.export.dir = user_dir("export").display().to_string();
|
||||
}
|
||||
|
||||
let skipped = app.session.load_templates(user_dir("templates"));
|
||||
app.session.log.extend(skipped.into_iter().map(|w| format!("Project template skipped: {w}")));
|
||||
app.session.log.extend(skipped.into_iter().map(|warning| format!("Project template skipped: {warning}")));
|
||||
}
|
||||
|
||||
app
|
||||
}
|
||||
|
||||
|
||||
@@ -2,7 +2,7 @@
|
||||
|
||||
use egui::{Color32, ColorImage};
|
||||
use texturecraft_engine::geom::glam::Vec3;
|
||||
use texturecraft_engine::mask_preview::MaskPreviewPixel;
|
||||
use texturecraft_engine::orb_preview::MaskPreviewPixel;
|
||||
use texturecraft_engine::texel::linear_to_srgb;
|
||||
|
||||
/// View-space lighting uses an upper-left key and a weaker right fill
|
||||
|
||||
@@ -1,33 +0,0 @@
|
||||
//! The smart mask preview shape, baked on first use
|
||||
|
||||
use texturecraft_engine::mask_preview::MaskPreview;
|
||||
|
||||
/// Whether the smart mask preview shape is baked
|
||||
#[derive(Default)]
|
||||
pub enum MaskShape {
|
||||
#[default]
|
||||
NotBaked,
|
||||
/// Box the large session to keep the unbaked worker small
|
||||
Baked(Box<MaskPreview>),
|
||||
/// The bake failed; smart mask previews stay empty
|
||||
Failed,
|
||||
}
|
||||
|
||||
impl MaskShape {
|
||||
/// Bake on first use; retain failure to avoid retrying every frame
|
||||
pub fn get(&mut self) -> Option<&mut MaskPreview> {
|
||||
if matches!(self, MaskShape::NotBaked) {
|
||||
*self = match MaskPreview::new() {
|
||||
Ok(preview) => MaskShape::Baked(Box::new(preview)),
|
||||
Err(e) => {
|
||||
log::warn!("smart mask previews: {e}");
|
||||
MaskShape::Failed
|
||||
}
|
||||
};
|
||||
}
|
||||
match self {
|
||||
MaskShape::Baked(preview) => Some(preview),
|
||||
MaskShape::NotBaked | MaskShape::Failed => None,
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,100 @@
|
||||
//! Shading of the smart material previews: a dark studio whose soft boxes show in reflections and light the diffuse color
|
||||
|
||||
use egui::{Color32, ColorImage};
|
||||
use texturecraft_engine::geom::glam::Vec3;
|
||||
use texturecraft_engine::orb_preview::MaterialPreviewPixel;
|
||||
use texturecraft_engine::texel::linear_to_srgb;
|
||||
|
||||
use crate::preview_image::{aces, bumped_normal, height_slope, preview_radius};
|
||||
use crate::soft_box::{SoftBox, smoothstep};
|
||||
|
||||
/// The studio's soft boxes: a key at the upper right, a fill at the left and a rim light above and behind
|
||||
const SOFT_BOXES: [SoftBox; 3] = [
|
||||
SoftBox { direction: [0.55, 0.75, 0.35], radius_rad: 0.6, intensity: 2.6 },
|
||||
SoftBox { direction: [-0.95, 0.2, 0.1], radius_rad: 0.7, intensity: 0.9 },
|
||||
SoftBox { direction: [0.1, 0.9, -0.45], radius_rad: 0.35, intensity: 1.6 },
|
||||
];
|
||||
/// The studio's backdrop brightness straight down and straight up (linear)
|
||||
const FLOOR: f32 = 0.03;
|
||||
const CEILING: f32 = 0.16;
|
||||
/// The lowest roughness shaded (a perfect mirror would show the soft boxes' hard edges)
|
||||
const MIN_ROUGHNESS: f32 = 0.02;
|
||||
/// Reflectance of dielectrics at normal incidence
|
||||
const DIELECTRIC_F0: f32 = 0.04;
|
||||
/// Exposure before tone mapping
|
||||
const EXPOSURE: f32 = 1.4;
|
||||
|
||||
/// A smart material preview (sRGB, transparent off the shape) from `size²` preview pixels; height bumps the normals
|
||||
pub fn material_preview_image(size: usize, pixels: &[Option<MaterialPreviewPixel>]) -> ColorImage {
|
||||
let radius = preview_radius(size);
|
||||
let height = |index: usize| pixels.get(index).copied().flatten().map(|pixel| pixel.sample.height);
|
||||
let mut image = ColorImage::filled([size, size], Color32::TRANSPARENT);
|
||||
|
||||
for (index, (out, pixel)) in image.pixels.iter_mut().zip(pixels).enumerate() {
|
||||
let Some(pixel) = pixel else { continue };
|
||||
|
||||
let sample = pixel.sample;
|
||||
let normal = bumped_normal(pixel.normal, height_slope(size, index, sample.height, height), radius);
|
||||
let roughness = sample.roughness.max(MIN_ROUGHNESS);
|
||||
let normal_dot_view = normal.z.max(0.0);
|
||||
// Mirror the direction towards the viewer (+Z) about the normal
|
||||
let reflected = (2.0 * normal_dot_view * normal - Vec3::Z).normalize_or_zero();
|
||||
let specular_light = reflected_light(reflected, roughness);
|
||||
let diffuse_light = diffuse_light(normal);
|
||||
// Schlick's Fresnel term, damped on rough surfaces below
|
||||
let fresnel = (1.0 - normal_dot_view).powi(5);
|
||||
|
||||
let color = [0, 1, 2].map(|component| {
|
||||
let base = sample.base[component];
|
||||
let f0 = DIELECTRIC_F0 + (base - DIELECTRIC_F0) * sample.metallic;
|
||||
let reflectance = f0 + ((1.0 - roughness).max(f0) - f0) * fresnel;
|
||||
let linear = reflectance * specular_light + base * (1.0 - sample.metallic) * (1.0 - reflectance) * diffuse_light;
|
||||
(linear_to_srgb(aces(linear * EXPOSURE)) * 255.0 + 0.5) as u8
|
||||
});
|
||||
let alpha = (pixel.coverage.clamp(0.0, 1.0) * 255.0 + 0.5) as u8;
|
||||
*out = Color32::from_rgba_unmultiplied(color[0], color[1], color[2], alpha);
|
||||
}
|
||||
image
|
||||
}
|
||||
|
||||
/// How far unit direction component `y` points up: 0 straight down, 1 straight up
|
||||
fn upward(y: f32) -> f32 {
|
||||
y * 0.5 + 0.5
|
||||
}
|
||||
|
||||
/// The backdrop's brightness `upward` of the way from the floor (0) to the ceiling (1)
|
||||
fn backdrop(upward: f32) -> f32 {
|
||||
FLOOR + (CEILING - FLOOR) * upward
|
||||
}
|
||||
|
||||
/// The studio seen along unit direction `view` by a surface of `roughness`
|
||||
fn reflected_light(view: Vec3, roughness: f32) -> f32 {
|
||||
// A soft horizon: reflections sweep from floor to ceiling smoothly
|
||||
backdrop(smoothstep(upward(view.y))) + SOFT_BOXES.iter().map(|soft_box| soft_box.reflected(view, roughness)).sum::<f32>()
|
||||
}
|
||||
|
||||
/// The light reaching a diffuse surface with unit normal `normal`
|
||||
fn diffuse_light(normal: Vec3) -> f32 {
|
||||
backdrop(upward(normal.y)) + SOFT_BOXES.iter().map(|soft_box| soft_box.diffuse(normal)).sum::<f32>()
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use texturecraft_engine::preview::Sample;
|
||||
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn the_studio_lights_the_shape_from_the_upper_right() {
|
||||
let polished_metal = Sample { base: [0.9; 3], metallic: 1.0, roughness: 0.3, height: 0.0 };
|
||||
let facing = |normal: Vec3| Some(MaterialPreviewPixel { sample: polished_metal, normal: normal.normalize(), coverage: 1.0 });
|
||||
// Halfway between the viewer and the key light, a mirror reflects the key
|
||||
let towards_the_key = SOFT_BOXES[0].unit_direction() + Vec3::Z;
|
||||
let pixels = [facing(towards_the_key), facing(Vec3::new(-0.3, -0.9, 0.3)), None, None];
|
||||
|
||||
let image = material_preview_image(2, &pixels);
|
||||
let [lit, unlit, outside] = [0, 1, 2].map(|index| image.pixels[index]);
|
||||
assert!(lit.r() > 200 && unlit.r() < 80, "the key light's reflection shows: {lit:?} vs {unlit:?}");
|
||||
assert_eq!((lit.a(), outside.a()), (255, 0), "opaque on the shape, transparent outside");
|
||||
}
|
||||
}
|
||||
@@ -305,6 +305,7 @@ fn effect_command<'a>(app: &TextureCraftApp, id: &'a str) -> &'a str {
|
||||
}
|
||||
}
|
||||
|
||||
/// Runs the commands bound to the keys pressed this frame, outside text fields and key capture
|
||||
pub fn shortcuts(app: &mut TextureCraftApp, ctx: &egui::Context) {
|
||||
if crate::keymap::capturing(ctx) || (ctx.memory(|memory| memory.focused().is_some()) && ctx.egui_wants_keyboard_input()) {
|
||||
return;
|
||||
@@ -319,6 +320,9 @@ pub fn shortcuts(app: &mut TextureCraftApp, ctx: &egui::Context) {
|
||||
return;
|
||||
}
|
||||
|
||||
// Escape closes an open popup first, before the Properties popup or the stroke
|
||||
let popup_open = egui::Popup::is_any_open(ctx);
|
||||
|
||||
let active_shortcuts = crate::keymap::active(&app.ui.keymap);
|
||||
let mut commands_to_invoke: Vec<&str> = Vec::new();
|
||||
ctx.input_mut(|input| {
|
||||
@@ -337,9 +341,9 @@ 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.properties_popup.is_some() && input.consume_key(Modifiers::NONE, Key::Escape) {
|
||||
if !popup_open && app.properties_popup.is_some() && input.consume_key(Modifiers::NONE, Key::Escape) {
|
||||
app.properties_popup = None;
|
||||
} else if app.ui.mode == Mode::Painting && input.consume_key(Modifiers::NONE, Key::Escape) {
|
||||
} else if app.ui.mode == Mode::Painting && !popup_open && input.consume_key(Modifiers::NONE, Key::Escape) {
|
||||
app.session.cancel_stroke();
|
||||
app.session.tool.path.points.clear();
|
||||
app.session.tool.path.editing = None;
|
||||
|
||||
@@ -0,0 +1,33 @@
|
||||
//! The preview orb of the smart mask and smart material previews, baked on first use
|
||||
|
||||
use texturecraft_engine::orb_preview::OrbPreview;
|
||||
|
||||
/// Whether the preview orb is baked
|
||||
#[derive(Default)]
|
||||
pub enum OrbShape {
|
||||
#[default]
|
||||
NotBaked,
|
||||
/// Box the large session to keep the unbaked worker small
|
||||
Baked(Box<OrbPreview>),
|
||||
/// The bake failed; previews on the orb stay empty
|
||||
Failed,
|
||||
}
|
||||
|
||||
impl OrbShape {
|
||||
/// Bake on first use; retain failure to avoid retrying every frame
|
||||
pub fn get(&mut self) -> Option<&mut OrbPreview> {
|
||||
if matches!(self, OrbShape::NotBaked) {
|
||||
*self = match OrbPreview::new() {
|
||||
Ok(preview) => OrbShape::Baked(Box::new(preview)),
|
||||
Err(e) => {
|
||||
log::warn!("preview orb: {e}");
|
||||
OrbShape::Failed
|
||||
}
|
||||
};
|
||||
}
|
||||
match self {
|
||||
OrbShape::Baked(preview) => Some(preview),
|
||||
OrbShape::NotBaked | OrbShape::Failed => None,
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -3,6 +3,7 @@
|
||||
use egui::{Color32, ColorImage};
|
||||
use texturecraft_engine::compose::ImageRes;
|
||||
use texturecraft_engine::core::ProceduralKind;
|
||||
use texturecraft_engine::geom::glam::Vec3;
|
||||
use texturecraft_engine::paint::alphas::{self, LibraryAlpha};
|
||||
use texturecraft_engine::paint::{BrushSettings, Shape};
|
||||
use texturecraft_engine::preview::{self, Sample};
|
||||
@@ -12,6 +13,14 @@ use texturecraft_engine::texel::linear_to_srgb;
|
||||
const PROCEDURAL_SCALE: f32 = 3.0;
|
||||
/// Samples per pixel along each axis of the alpha swatches
|
||||
const ALPHA_SUPERSAMPLE: usize = 2;
|
||||
/// Normal tilt per height step, relative to the shape's radius in pixels
|
||||
const BUMP_PER_RADIUS: f32 = 0.75;
|
||||
/// Exposure of the shaded previews before tone mapping
|
||||
const EXPOSURE: f32 = 1.4;
|
||||
/// Gap between a preview's shape and the image edge in pixels
|
||||
const SHAPE_MARGIN_PX: f32 = 1.0;
|
||||
/// Guards the normal division against a zero vector
|
||||
const MIN_NORMAL_LENGTH: f32 = 1e-6;
|
||||
|
||||
/// Linear shading for view-space normal `n`, viewed along +Z
|
||||
pub fn shade(n: [f32; 3], base: [f32; 3], metal: f32, rough: f32) -> [f32; 3] {
|
||||
@@ -52,28 +61,52 @@ pub fn aces(x: f32) -> f32 {
|
||||
|
||||
/// Shade row-major `size²` samples with height bumps and a transparent background
|
||||
pub fn sphere_image(size: usize, samples: &[Option<Sample>]) -> ColorImage {
|
||||
let mut img = ColorImage::filled([size, size], Color32::TRANSPARENT);
|
||||
let r = (size as f32 * 0.5 - 1.0).max(0.5);
|
||||
let h = |x: Option<usize>, y: Option<usize>| {
|
||||
let (x, y) = (x.filter(|x| *x < size)?, y?);
|
||||
samples.get(y.checked_mul(size)?.checked_add(x)?).copied().flatten().map(|s| s.height)
|
||||
};
|
||||
for (i, n) in preview::sphere_normals(size).enumerate() {
|
||||
let (Some(n), Some(Some(s))) = (n, samples.get(i)) else { continue };
|
||||
let mut image = ColorImage::filled([size, size], Color32::TRANSPARENT);
|
||||
let radius = preview_radius(size);
|
||||
let height = |index: usize| samples.get(index).copied().flatten().map(|sample| sample.height);
|
||||
|
||||
let (x, y) = (i % size, i / size);
|
||||
let c = s.height;
|
||||
// Image Y points down; the shading normal uses Y up
|
||||
let dx = h(Some(x + 1), Some(y)).unwrap_or(c) - h(x.checked_sub(1), Some(y)).unwrap_or(c);
|
||||
let dy = h(Some(x), y.checked_sub(1)).unwrap_or(c) - h(Some(x), Some(y + 1)).unwrap_or(c);
|
||||
let k = r * 0.5 * 1.5;
|
||||
let b = [n.x - dx * k, n.y - dy * k, n.z];
|
||||
let len = (b[0] * b[0] + b[1] * b[1] + b[2] * b[2]).sqrt().max(1e-6);
|
||||
let col = shade(b.map(|v| v / len), s.base, s.metallic, s.roughness).map(|v| (linear_to_srgb(aces(v * 1.4)) * 255.0 + 0.5) as u8);
|
||||
let edge = ((1.0 - (n.x * n.x + n.y * n.y).sqrt()) * r).clamp(0.0, 1.0);
|
||||
img.pixels[i] = Color32::from_rgba_unmultiplied(col[0], col[1], col[2], (edge * 255.0) as u8);
|
||||
for (index, normal) in preview::sphere_normals(size).enumerate() {
|
||||
let (Some(normal), Some(Some(sample))) = (normal, samples.get(index)) else { continue };
|
||||
|
||||
// Anti-aliased outline: opaque from one pixel inside the rim
|
||||
let coverage = ((1.0 - (normal.x * normal.x + normal.y * normal.y).sqrt()) * radius).clamp(0.0, 1.0);
|
||||
image.pixels[index] = lit_pixel(normal, height_slope(size, index, sample.height, height), radius, sample, coverage);
|
||||
}
|
||||
img
|
||||
image
|
||||
}
|
||||
|
||||
/// Radius in pixels of the shape filling a `size²` preview
|
||||
pub(crate) fn preview_radius(size: usize) -> f32 {
|
||||
(size as f32 * 0.5 - SHAPE_MARGIN_PX).max(0.5)
|
||||
}
|
||||
|
||||
/// Height change per pixel rightwards and upwards at `pixel`; None heights count as `center`
|
||||
pub(crate) fn height_slope(size: usize, pixel: usize, center: f32, height: impl Fn(usize) -> Option<f32>) -> [f32; 2] {
|
||||
let (x, y) = (pixel % size, pixel / size);
|
||||
let at = |x: Option<usize>, y: Option<usize>| {
|
||||
let (x, y) = (x.filter(|x| *x < size)?, y?);
|
||||
height(y.checked_mul(size)?.checked_add(x)?)
|
||||
};
|
||||
|
||||
// Image Y points down; the shading normal uses Y up
|
||||
let right = at(Some(x + 1), Some(y)).unwrap_or(center) - at(x.checked_sub(1), Some(y)).unwrap_or(center);
|
||||
let up = at(Some(x), y.checked_sub(1)).unwrap_or(center) - at(Some(x), Some(y + 1)).unwrap_or(center);
|
||||
[right, up]
|
||||
}
|
||||
|
||||
/// Tilt a view-space normal by the height `slope` on a shape of `radius` pixels
|
||||
pub(crate) fn bumped_normal(normal: Vec3, slope: [f32; 2], radius: f32) -> Vec3 {
|
||||
let bump = radius * BUMP_PER_RADIUS;
|
||||
let bumped = [normal.x - slope[0] * bump, normal.y - slope[1] * bump, normal.z];
|
||||
let length = (bumped[0] * bumped[0] + bumped[1] * bumped[1] + bumped[2] * bumped[2]).sqrt().max(MIN_NORMAL_LENGTH);
|
||||
Vec3::from(bumped.map(|component| component / length))
|
||||
}
|
||||
|
||||
/// One sphere pixel of `sample`, bumped by `slope` and `coverage` opaque
|
||||
fn lit_pixel(normal: Vec3, slope: [f32; 2], radius: f32, sample: &Sample, coverage: f32) -> Color32 {
|
||||
let linear = shade(bumped_normal(normal, slope, radius).to_array(), sample.base, sample.metallic, sample.roughness);
|
||||
let color = linear.map(|component| (linear_to_srgb(aces(component * EXPOSURE)) * 255.0 + 0.5) as u8);
|
||||
Color32::from_rgba_unmultiplied(color[0], color[1], color[2], (coverage * 255.0) as u8)
|
||||
}
|
||||
|
||||
/// Grayscale `size²` swatch of procedural `kind`
|
||||
|
||||
@@ -3,7 +3,8 @@
|
||||
use egui::ColorImage;
|
||||
|
||||
use crate::mask_preview_image::mask_preview_image;
|
||||
use crate::mask_shape::MaskShape;
|
||||
use crate::material_preview_image::material_preview_image;
|
||||
use crate::orb_shape::OrbShape;
|
||||
use crate::shelf_preview::ShelfPreview;
|
||||
|
||||
/// Render `preview` at `size_px²`; the answer comes back under `key`
|
||||
@@ -18,11 +19,12 @@ pub struct PreviewRequest {
|
||||
}
|
||||
|
||||
impl PreviewRequest {
|
||||
/// Render the asset, baking the mask shape on first use
|
||||
/// Render the asset, baking the orb on first use for smart masks and smart materials
|
||||
/// Unknown assets and failed bakes return None
|
||||
pub fn render(&self, shape: &mut MaskShape) -> Option<ColorImage> {
|
||||
pub fn render(&self, shape: &mut OrbShape) -> Option<ColorImage> {
|
||||
match &self.preview {
|
||||
ShelfPreview::SmartMask(id) => Some(mask_preview_image(self.size_px, &shape.get()?.render(id, self.size_px)?)),
|
||||
ShelfPreview::SmartMask(id) => Some(mask_preview_image(self.size_px, &shape.get()?.mask(id, self.size_px)?)),
|
||||
ShelfPreview::SmartMaterial(id) => Some(material_preview_image(self.size_px, &shape.get()?.material(id, self.size_px)?)),
|
||||
preview => preview.image(self.size_px),
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,8 +1,8 @@
|
||||
//! Native preview rendering uses a separate thread pool
|
||||
//! Web requests render synchronously on the UI thread
|
||||
|
||||
#[cfg(target_arch = "wasm32")]
|
||||
use crate::mask_shape::MaskShape;
|
||||
#[cfg(any(target_arch = "wasm32", test))]
|
||||
use crate::orb_shape::OrbShape;
|
||||
use crate::preview_request::PreviewRequest;
|
||||
|
||||
/// Request key and rendered image; None on failure
|
||||
@@ -17,8 +17,8 @@ pub enum PreviewWorker {
|
||||
#[cfg(not(target_arch = "wasm32"))]
|
||||
Running { requests: std::sync::mpsc::Sender<PreviewRequest>, results: std::sync::mpsc::Receiver<PreviewResult> },
|
||||
/// The web: requests render as they are made
|
||||
#[cfg(target_arch = "wasm32")]
|
||||
Inline { shape: MaskShape, results: Vec<PreviewResult> },
|
||||
#[cfg(any(target_arch = "wasm32", test))]
|
||||
Inline { shape: OrbShape, results: Vec<PreviewResult> },
|
||||
/// The worker could not start or stopped; requests are refused
|
||||
// The web has no thread to stop
|
||||
#[cfg_attr(target_arch = "wasm32", allow(dead_code))]
|
||||
@@ -27,10 +27,10 @@ pub enum PreviewWorker {
|
||||
|
||||
impl PreviewWorker {
|
||||
/// Submit work, starting the worker on first use; false if it has stopped
|
||||
/// Native results request a repaint
|
||||
pub fn request(&mut self, ctx: &egui::Context, request: PreviewRequest) -> bool {
|
||||
/// Completed results request a repaint so the UI polls them on the next pass
|
||||
pub fn request(&mut self, context: &egui::Context, request: PreviewRequest) -> bool {
|
||||
if matches!(self, PreviewWorker::NotStarted) {
|
||||
*self = PreviewWorker::start(ctx);
|
||||
*self = PreviewWorker::start(context);
|
||||
}
|
||||
|
||||
match self {
|
||||
@@ -39,12 +39,14 @@ impl PreviewWorker {
|
||||
if requests.send(request).is_ok() {
|
||||
return true;
|
||||
}
|
||||
|
||||
*self = PreviewWorker::Stopped;
|
||||
false
|
||||
}
|
||||
#[cfg(target_arch = "wasm32")]
|
||||
#[cfg(any(target_arch = "wasm32", test))]
|
||||
PreviewWorker::Inline { shape, results } => {
|
||||
results.push((request.key.clone(), request.render(shape)));
|
||||
context.request_repaint();
|
||||
true
|
||||
}
|
||||
PreviewWorker::NotStarted | PreviewWorker::Stopped => false,
|
||||
@@ -72,7 +74,7 @@ impl PreviewWorker {
|
||||
}
|
||||
ready
|
||||
}
|
||||
#[cfg(target_arch = "wasm32")]
|
||||
#[cfg(any(target_arch = "wasm32", test))]
|
||||
PreviewWorker::Inline { results, .. } => std::mem::take(results),
|
||||
PreviewWorker::NotStarted | PreviewWorker::Stopped => Vec::new(),
|
||||
}
|
||||
@@ -89,7 +91,7 @@ impl PreviewWorker {
|
||||
use std::collections::VecDeque;
|
||||
use std::sync::mpsc::channel;
|
||||
|
||||
use crate::mask_shape::MaskShape;
|
||||
use crate::orb_shape::OrbShape;
|
||||
|
||||
let (requests, request_rx) = channel::<PreviewRequest>();
|
||||
let (result_tx, results) = channel();
|
||||
@@ -101,7 +103,7 @@ impl PreviewWorker {
|
||||
if let Err(e) = &pool {
|
||||
log::warn!("shelf previews share the global thread pool: {e}");
|
||||
}
|
||||
let mut shape = MaskShape::default();
|
||||
let mut shape = OrbShape::default();
|
||||
let mut queue = VecDeque::new();
|
||||
loop {
|
||||
if queue.is_empty() {
|
||||
@@ -136,7 +138,7 @@ impl PreviewWorker {
|
||||
/// Render inline (no threads on the web)
|
||||
#[cfg(target_arch = "wasm32")]
|
||||
fn start(_ctx: &egui::Context) -> PreviewWorker {
|
||||
PreviewWorker::Inline { shape: MaskShape::default(), results: Vec::new() }
|
||||
PreviewWorker::Inline { shape: OrbShape::default(), results: Vec::new() }
|
||||
}
|
||||
}
|
||||
|
||||
@@ -160,6 +162,30 @@ mod tests {
|
||||
use super::*;
|
||||
use crate::shelf_preview::ShelfPreview;
|
||||
|
||||
#[test]
|
||||
fn inline_results_schedule_a_frame_to_display_them() {
|
||||
for id in ["steel", "nope"] {
|
||||
let context = egui::Context::default();
|
||||
for _ in 0..3 {
|
||||
let mut output = context.run_pass(Default::default(), |_| {});
|
||||
|
||||
// No renderer consumes the texture updates in this scheduling test
|
||||
output.textures_delta.clear();
|
||||
}
|
||||
assert!(!context.has_requested_repaint(), "the UI is idle before the request");
|
||||
|
||||
let mut worker = PreviewWorker::Inline { shape: OrbShape::default(), results: Vec::new() };
|
||||
assert!(worker.poll().is_empty(), "the UI polls before submitting work");
|
||||
let request = PreviewRequest { key: id.into(), preview: ShelfPreview::Material(id), size_px: 8, hover: false };
|
||||
assert!(worker.request(&context, request));
|
||||
|
||||
let results = worker.poll();
|
||||
assert_eq!(results.len(), 1);
|
||||
assert_eq!(results[0].1.is_some(), id == "steel");
|
||||
assert!(context.has_requested_repaint(), "the result needs another frame even when this is the only request");
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn requests_are_answered_and_unknown_assets_get_none() {
|
||||
let ctx = egui::Context::default();
|
||||
@@ -170,23 +196,26 @@ mod tests {
|
||||
("unknown material", ShelfPreview::Material("nope")),
|
||||
("mask", ShelfPreview::SmartMask(SMART_MASKS[0].id)),
|
||||
("unknown mask", ShelfPreview::SmartMask("nope")),
|
||||
("smart material", ShelfPreview::SmartMaterial("steel_painted_worn")),
|
||||
("unknown smart material", ShelfPreview::SmartMaterial("nope")),
|
||||
];
|
||||
let requests_sent = requests.len();
|
||||
for (key, preview) in requests {
|
||||
assert!(worker.request(&ctx, PreviewRequest { key: key.into(), preview, size_px, hover: false }), "{key}");
|
||||
}
|
||||
|
||||
let mut answers = HashMap::new();
|
||||
let start = Instant::now();
|
||||
while answers.len() < 4 && start.elapsed() < Duration::from_secs(120) {
|
||||
while answers.len() < requests_sent && start.elapsed() < Duration::from_secs(120) {
|
||||
answers.extend(worker.poll());
|
||||
std::thread::sleep(Duration::from_millis(10));
|
||||
}
|
||||
|
||||
for key in ["material", "mask"] {
|
||||
for key in ["material", "mask", "smart material"] {
|
||||
let image = answers.get(key).and_then(Option::as_ref).unwrap_or_else(|| panic!("{key}: {answers:?}"));
|
||||
assert_eq!(image.size, [size_px, size_px], "{key}");
|
||||
}
|
||||
for key in ["unknown material", "unknown mask"] {
|
||||
for key in ["unknown material", "unknown mask", "unknown smart material"] {
|
||||
assert!(matches!(answers.get(key), Some(None)), "{key}: {answers:?}");
|
||||
}
|
||||
assert!(!worker.is_stopped());
|
||||
|
||||
@@ -0,0 +1,126 @@
|
||||
//! A popup under a slot that picks a resource, such as a filter, from grouped shelf tiles searched by name
|
||||
|
||||
use egui::{Id, Response, Stroke, Ui};
|
||||
|
||||
use crate::i18n::tr;
|
||||
use crate::resource_picker_item::ResourcePickerItem;
|
||||
use crate::shelf;
|
||||
use crate::shelf_preview::ShelfPreview;
|
||||
use crate::theme::Tokens;
|
||||
use crate::thumbs::Thumbs;
|
||||
|
||||
/// Four shelf tiles and the scrollbar
|
||||
const PICKER_WIDTH: f32 = 320.0;
|
||||
/// The grid's height, fixed so the popup keeps its place while searching
|
||||
const PICKER_HEIGHT: f32 = 340.0;
|
||||
const CURRENT_OUTLINE_WIDTH: f32 = 1.5;
|
||||
const TILE_ROUNDING: f32 = 3.0;
|
||||
|
||||
/// Opens the picker `popup_id` with an empty, focused search field, or closes it
|
||||
pub(crate) fn toggle(ctx: &egui::Context, popup_id: Id) {
|
||||
if egui::Popup::is_id_open(ctx, popup_id) {
|
||||
egui::Popup::close_id(ctx, popup_id);
|
||||
return;
|
||||
}
|
||||
|
||||
egui::Popup::open_id(ctx, popup_id);
|
||||
ctx.data_mut(|data| {
|
||||
data.insert_temp(search_id(popup_id), String::new());
|
||||
data.insert_temp(focus_id(popup_id), true);
|
||||
});
|
||||
}
|
||||
|
||||
/// Draws picker `popup_id` at `slot` while open and returns the id clicked (`items` runs only then)
|
||||
pub(crate) fn show(
|
||||
slot: &Response,
|
||||
popup_id: Id,
|
||||
thumbs: &mut Thumbs,
|
||||
current: Option<&str>,
|
||||
items: impl FnOnce(&mut Thumbs) -> Vec<ResourcePickerItem>,
|
||||
preview: impl Fn(&'static str) -> ShelfPreview,
|
||||
) -> Option<&'static str> {
|
||||
let ctx = slot.ctx.clone();
|
||||
if !egui::Popup::is_id_open(&ctx, popup_id) {
|
||||
return None;
|
||||
}
|
||||
|
||||
let items = items(thumbs);
|
||||
let mut picked = None;
|
||||
egui::Popup::from_response(slot)
|
||||
.id(popup_id)
|
||||
.open_memory(None)
|
||||
.close_behavior(egui::PopupCloseBehavior::CloseOnClickOutside)
|
||||
.align(egui::RectAlign::BOTTOM_END)
|
||||
.width(PICKER_WIDTH)
|
||||
.show(|ui| {
|
||||
ui.set_width(PICKER_WIDTH);
|
||||
let just_opened = ui.data_mut(|data| data.remove_temp::<bool>(focus_id(popup_id))).unwrap_or(false);
|
||||
let query = search_field(ui, popup_id, just_opened);
|
||||
egui::ScrollArea::vertical().max_height(PICKER_HEIGHT).show(ui, |ui| {
|
||||
// A search that leaves few tiles must not shrink the popup, or egui moves it
|
||||
ui.set_min_height(PICKER_HEIGHT);
|
||||
picked = grid(ui, thumbs, &items, &query, current, just_opened, &preview);
|
||||
});
|
||||
});
|
||||
|
||||
if picked.is_some() {
|
||||
egui::Popup::close_id(&ctx, popup_id);
|
||||
}
|
||||
picked
|
||||
}
|
||||
|
||||
/// The search field, focused the frame the picker opens; returns the lowercase query
|
||||
fn search_field(ui: &mut Ui, popup_id: Id, just_opened: bool) -> String {
|
||||
let mut search: String = ui.data(|data| data.get_temp(search_id(popup_id))).unwrap_or_default();
|
||||
let field = ui.add(egui::TextEdit::singleline(&mut search).hint_text(tr("Search")).desired_width(f32::INFINITY));
|
||||
if just_opened {
|
||||
field.request_focus();
|
||||
}
|
||||
|
||||
let query = search.trim().to_lowercase();
|
||||
ui.data_mut(|data| data.insert_temp(search_id(popup_id), search));
|
||||
query
|
||||
}
|
||||
|
||||
/// The items matching `query` as tiles under group headers, `current` outlined; returns the one clicked
|
||||
fn grid(
|
||||
ui: &mut Ui,
|
||||
thumbs: &mut Thumbs,
|
||||
items: &[ResourcePickerItem],
|
||||
query: &str,
|
||||
current: Option<&str>,
|
||||
reveal_current: bool,
|
||||
preview: &impl Fn(&'static str) -> ShelfPreview,
|
||||
) -> Option<&'static str> {
|
||||
let tk = Tokens::get(ui.ctx());
|
||||
let shown: Vec<&ResourcePickerItem> = items.iter().filter(|item| shelf::matches(query, &[item.label, item.id])).collect();
|
||||
let mut picked = None;
|
||||
for group in shelf::categories(&shown, |item| item.group) {
|
||||
shelf::header(ui, group);
|
||||
shelf::tiles(ui, |ui| {
|
||||
for item in shown.iter().filter(|item| item.group == group) {
|
||||
let response = shelf::tile(ui, thumbs, item.thumbnail.as_ref(), || preview(item.id), item.label, None);
|
||||
if current == Some(item.id) {
|
||||
if reveal_current {
|
||||
response.scroll_to_me(Some(egui::Align::Center));
|
||||
}
|
||||
ui.painter().rect_stroke(response.rect, TILE_ROUNDING, Stroke::new(CURRENT_OUTLINE_WIDTH, tk.accent), egui::StrokeKind::Inside);
|
||||
}
|
||||
if response.clicked() {
|
||||
picked = Some(item.id);
|
||||
}
|
||||
}
|
||||
});
|
||||
}
|
||||
picked
|
||||
}
|
||||
|
||||
/// Where the picker keeps its search text
|
||||
fn search_id(popup_id: Id) -> Id {
|
||||
popup_id.with("search")
|
||||
}
|
||||
|
||||
/// Set while the picker waits for its first frame open
|
||||
fn focus_id(popup_id: Id) -> Id {
|
||||
popup_id.with("focus")
|
||||
}
|
||||
@@ -0,0 +1,9 @@
|
||||
//! One choice offered by a resource picker
|
||||
|
||||
/// A resource the picker offers: its id, translated label and group, and its thumbnail
|
||||
pub(crate) struct ResourcePickerItem {
|
||||
pub id: &'static str,
|
||||
pub label: &'static str,
|
||||
pub group: &'static str,
|
||||
pub thumbnail: Option<egui::TextureHandle>,
|
||||
}
|
||||
+35
-24
@@ -12,8 +12,8 @@ use texturecraft_engine::filter_lib::FILTERS;
|
||||
#[cfg(not(target_arch = "wasm32"))]
|
||||
use texturecraft_engine::formats::mcmat::MCMAT_EXT;
|
||||
use texturecraft_engine::geom::glam::Vec2;
|
||||
use texturecraft_engine::mask_preview::MAX_PREVIEW_SIZE_PX;
|
||||
use texturecraft_engine::materials::MATERIALS;
|
||||
use texturecraft_engine::orb_preview::MAX_PREVIEW_SIZE_PX;
|
||||
use texturecraft_engine::paint::alphas;
|
||||
use texturecraft_engine::paint::presets::{BrushPreset, PRESETS};
|
||||
use texturecraft_engine::smart_masks::SMART_MASKS;
|
||||
@@ -34,8 +34,9 @@ const TILE_ROUNDING: f32 = 3.0;
|
||||
/// The thumbnail's size in a tile and its center below the tile's top, in points
|
||||
const THUMBNAIL_SIZE: f32 = 56.0;
|
||||
const THUMBNAIL_CENTER_Y: f32 = 32.0;
|
||||
/// A placeholder disc's radius relative to the thumbnail's width
|
||||
const PLACEHOLDER_RADIUS: f32 = 0.45;
|
||||
/// Loading icon size relative to the thumbnail width, and its opacity over the dim text color
|
||||
const LOADING_ICON_SCALE: f32 = 0.9;
|
||||
const LOADING_ICON_OPACITY: f32 = 0.5;
|
||||
/// A tile label's font size, its gap below the thumbnail and its total side margin, in points
|
||||
const LABEL_FONT_SIZE: f32 = 9.5;
|
||||
const LABEL_GAP: f32 = 3.0;
|
||||
@@ -266,7 +267,7 @@ fn drag_preview(ctx: &egui::Context) {
|
||||
p.galley(rect.min + vec2(6.0, 3.0), galley, tk.text_strong);
|
||||
}
|
||||
|
||||
fn matches(filter: &str, texts: &[&str]) -> bool {
|
||||
pub(crate) fn matches(filter: &str, texts: &[&str]) -> bool {
|
||||
filter.is_empty() || texts.iter().any(|t| t.to_lowercase().contains(filter))
|
||||
}
|
||||
|
||||
@@ -275,13 +276,13 @@ fn title(ui: &mut Ui, text: &str) {
|
||||
ui.label(RichText::new(text).strong().color(tk.text_strong));
|
||||
}
|
||||
|
||||
fn header(ui: &mut Ui, text: &str) {
|
||||
pub(crate) fn header(ui: &mut Ui, text: &str) {
|
||||
let tk = Tokens::get(ui.ctx());
|
||||
ui.add_space(2.0);
|
||||
ui.label(RichText::new(text).size(11.0).color(tk.text_dim));
|
||||
}
|
||||
|
||||
fn tiles(ui: &mut Ui, body: impl FnOnce(&mut Ui)) {
|
||||
pub(crate) fn tiles(ui: &mut Ui, body: impl FnOnce(&mut Ui)) {
|
||||
ui.horizontal_wrapped(|ui| {
|
||||
ui.spacing_mut().item_spacing = vec2(4.0, 4.0);
|
||||
body(ui);
|
||||
@@ -290,7 +291,7 @@ fn tiles(ui: &mut Ui, body: impl FnOnce(&mut Ui)) {
|
||||
}
|
||||
|
||||
/// The distinct categories of `items`, in order of first appearance.
|
||||
fn categories<T>(items: &[T], category: impl Fn(&T) -> &'static str) -> Vec<&'static str> {
|
||||
pub(crate) fn categories<T>(items: &[T], category: impl Fn(&T) -> &'static str) -> Vec<&'static str> {
|
||||
let mut out: Vec<&'static str> = Vec::new();
|
||||
for c in items.iter().map(category) {
|
||||
if !out.contains(&c) {
|
||||
@@ -300,20 +301,22 @@ fn categories<T>(items: &[T], category: impl Fn(&T) -> &'static str) -> Vec<&'st
|
||||
out
|
||||
}
|
||||
|
||||
/// Built-in materials (or smart materials), grouped by category.
|
||||
/// Built-in materials or smart materials, grouped by category
|
||||
fn materials(app: &mut TextureCraftApp, ui: &mut Ui, ctx: &egui::Context, filter: &str, smart: bool, name: &str) {
|
||||
let shown: Vec<_> = MATERIALS.iter().filter(|m| m.smart == smart && matches(filter, &[m.label, m.category, m.id])).collect();
|
||||
let shown: Vec<_> =
|
||||
MATERIALS.iter().filter(|material| material.smart == smart && matches(filter, &[material.label, material.category, material.id])).collect();
|
||||
if shown.is_empty() {
|
||||
return;
|
||||
}
|
||||
|
||||
title(ui, name);
|
||||
for cat in categories(&shown, |m| m.category) {
|
||||
header(ui, cat);
|
||||
for category in categories(&shown, |material| material.category) {
|
||||
header(ui, category);
|
||||
tiles(ui, |ui| {
|
||||
for m in shown.iter().filter(|m| m.category == cat) {
|
||||
let tex = app.thumbs.material(ctx, m.id);
|
||||
let asset = Asset::Material(m.id);
|
||||
if tile(ui, &mut app.thumbs, tex.as_ref(), || ShelfPreview::Material(m.id), m.label, Some(&asset)).clicked() {
|
||||
for material in shown.iter().filter(|material| material.category == category) {
|
||||
let texture = app.thumbs.material(ctx, material.id);
|
||||
let asset = Asset::Material(material.id);
|
||||
if tile(ui, &mut app.thumbs, texture.as_ref(), || ShelfPreview::material(material.id), material.label, Some(&asset)).clicked() {
|
||||
apply(app, &asset);
|
||||
}
|
||||
}
|
||||
@@ -586,7 +589,7 @@ fn textures(app: &mut TextureCraftApp, ui: &mut Ui, ctx: &egui::Context, filter:
|
||||
}
|
||||
|
||||
/// Asset tile with optional dragging and a larger hover preview
|
||||
fn tile(
|
||||
pub(crate) fn tile(
|
||||
ui: &mut Ui,
|
||||
thumbs: &mut Thumbs,
|
||||
tex: Option<&egui::TextureHandle>,
|
||||
@@ -623,8 +626,9 @@ fn big_preview(ui: &Ui, thumbs: &mut Thumbs, preview: impl FnOnce() -> ShelfPrev
|
||||
let preview = preview();
|
||||
let requested_size_px = (BIG_PREVIEW_SIZE * ctx.pixels_per_point()).round() as usize;
|
||||
|
||||
// High display scales must respect the mask camera's allocation limit
|
||||
let size_px = if matches!(&preview, ShelfPreview::SmartMask(_)) { requested_size_px.clamp(1, MAX_PREVIEW_SIZE_PX) } else { requested_size_px };
|
||||
// High display scales must respect the orb camera's allocation limit
|
||||
let on_the_orb = matches!(&preview, ShelfPreview::SmartMask(_) | ShelfPreview::SmartMaterial(_));
|
||||
let size_px = if on_the_orb { requested_size_px.clamp(1, MAX_PREVIEW_SIZE_PX) } else { requested_size_px };
|
||||
|
||||
// Scrolling moves tiles beneath a stationary pointer
|
||||
let idle_seconds = ui.input(|input| if input.is_scrolling() { 0.0 } else { input.pointer.time_since_last_movement().min(input.time_since_last_scroll()) });
|
||||
@@ -636,14 +640,21 @@ fn big_preview(ui: &Ui, thumbs: &mut Thumbs, preview: impl FnOnce() -> ShelfPrev
|
||||
thumbs.rendered_big(ctx, &preview, size_px)
|
||||
}
|
||||
|
||||
/// `tex` drawn into `rect`, or a placeholder disc while it renders
|
||||
fn thumbnail(painter: &egui::Painter, tex: Option<&egui::TextureHandle>, rect: egui::Rect, tk: &Tokens) {
|
||||
match tex {
|
||||
Some(t) => {
|
||||
painter.image(t.id(), rect, egui::Rect::from_min_max(egui::pos2(0.0, 0.0), egui::pos2(1.0, 1.0)), Color32::WHITE);
|
||||
/// `texture` drawn into `rect`, or a dim loading icon while it renders
|
||||
fn thumbnail(painter: &egui::Painter, texture: Option<&egui::TextureHandle>, rect: egui::Rect, tk: &Tokens) {
|
||||
match texture {
|
||||
Some(texture) => {
|
||||
painter.image(texture.id(), rect, egui::Rect::from_min_max(egui::pos2(0.0, 0.0), egui::pos2(1.0, 1.0)), Color32::WHITE);
|
||||
}
|
||||
None => {
|
||||
painter.circle_filled(rect.center(), rect.width() * PLACEHOLDER_RADIUS, tk.row_hover);
|
||||
let font = egui::FontId::proportional(rect.width() * LOADING_ICON_SCALE);
|
||||
painter.text(
|
||||
rect.center(),
|
||||
egui::Align2::CENTER_CENTER,
|
||||
egui_phosphor::regular::ARROWS_CLOCKWISE,
|
||||
font,
|
||||
tk.text_dim.gamma_multiply(LOADING_ICON_OPACITY),
|
||||
);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -5,6 +5,7 @@ use std::sync::Arc;
|
||||
use egui::ColorImage;
|
||||
use texturecraft_engine::compose::ImageRes;
|
||||
use texturecraft_engine::core::ProceduralKind;
|
||||
use texturecraft_engine::materials;
|
||||
use texturecraft_engine::paint::BrushSettings;
|
||||
use texturecraft_engine::paint::alphas::LibraryAlpha;
|
||||
use texturecraft_engine::paint::presets::BrushPreset;
|
||||
@@ -14,9 +15,11 @@ use crate::preview_image::{alpha_image, image_preview, procedural_image, sphere_
|
||||
|
||||
/// The asset a shelf tile previews
|
||||
pub enum ShelfPreview {
|
||||
/// A built-in material or smart material on a sphere
|
||||
/// A built-in plain material on a sphere
|
||||
Material(&'static str),
|
||||
/// Smart mask rendering requires the worker's baked shape
|
||||
/// Smart material rendering requires the worker's baked orb
|
||||
SmartMaterial(&'static str),
|
||||
/// Smart mask rendering requires the worker's baked orb
|
||||
SmartMask(&'static str),
|
||||
/// A library filter on a sample material on a sphere
|
||||
Filter(&'static str),
|
||||
@@ -31,10 +34,19 @@ pub enum ShelfPreview {
|
||||
}
|
||||
|
||||
impl ShelfPreview {
|
||||
/// Smart materials preview on the orb, plain materials on a sphere
|
||||
pub fn material(id: &'static str) -> ShelfPreview {
|
||||
match materials::find(id) {
|
||||
Some(found) if found.smart => ShelfPreview::SmartMaterial(id),
|
||||
Some(_) | None => ShelfPreview::Material(id),
|
||||
}
|
||||
}
|
||||
|
||||
/// The cache key of the preview (one per asset)
|
||||
pub fn key(&self) -> String {
|
||||
match self {
|
||||
ShelfPreview::Material(id) => format!("mat:{id}"),
|
||||
ShelfPreview::SmartMaterial(id) => format!("smart-mat:{id}"),
|
||||
ShelfPreview::SmartMask(id) => format!("mask:{id}"),
|
||||
ShelfPreview::Filter(id) => format!("filter:{id}"),
|
||||
ShelfPreview::Procedural(kind) => format!("proc:{kind:?}"),
|
||||
@@ -45,11 +57,11 @@ impl ShelfPreview {
|
||||
}
|
||||
|
||||
/// Render a `size²` image; unknown assets return None
|
||||
/// Smart masks return None here because their bake belongs to the worker
|
||||
/// Smart masks and smart materials return None here because their bake belongs to the worker
|
||||
pub fn image(&self, size: usize) -> Option<ColorImage> {
|
||||
match self {
|
||||
ShelfPreview::Material(id) => Some(sphere_image(size, &preview::material(id, size)?)),
|
||||
ShelfPreview::SmartMask(_) => None,
|
||||
ShelfPreview::SmartMask(_) | ShelfPreview::SmartMaterial(_) => None,
|
||||
ShelfPreview::Filter(id) => Some(sphere_image(size, &preview::filter(id, size)?)),
|
||||
ShelfPreview::Procedural(kind) => Some(procedural_image(*kind, size)),
|
||||
ShelfPreview::Alpha(alpha) => Some(alpha_image(alpha, size)),
|
||||
@@ -86,14 +98,23 @@ mod tests {
|
||||
let key = preview.key();
|
||||
let image = preview.image(BIG_PX).unwrap_or_else(|| panic!("{key}"));
|
||||
assert_eq!(image.size, [BIG_PX, BIG_PX], "{key}");
|
||||
assert!(image.pixels.iter().any(|c| c.a() > 0 && c.r().max(c.g()).max(c.b()) > 0), "{key}: something shows");
|
||||
assert!(image.pixels.iter().any(|color| color.a() > 0 && color.r().max(color.g()).max(color.b()) > 0), "{key}: something shows");
|
||||
}
|
||||
|
||||
let finite = |samples: Vec<Option<preview::Sample>>| {
|
||||
samples.iter().flatten().all(|s| s.base.iter().chain([&s.metallic, &s.roughness, &s.height]).all(|v| v.is_finite()))
|
||||
samples.iter().flatten().all(|sample| sample.base.into_iter().chain([sample.metallic, sample.roughness, sample.height]).all(f32::is_finite))
|
||||
};
|
||||
assert!(finite(preview::material(MATERIALS[0].id, BIG_PX).unwrap_or_default()));
|
||||
assert!(finite(preview::filter(FILTERS[0].id, BIG_PX).unwrap_or_default()));
|
||||
assert!(ShelfPreview::SmartMask("edges_sharp").image(BIG_PX).is_none(), "smart masks need the baked shape");
|
||||
assert!(ShelfPreview::SmartMask("edges_sharp").image(BIG_PX).is_none(), "smart masks need the baked orb");
|
||||
assert!(ShelfPreview::SmartMaterial("steel_painted_worn").image(BIG_PX).is_none(), "smart materials need the baked orb");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn smart_materials_and_only_they_preview_on_the_orb() {
|
||||
for material in MATERIALS {
|
||||
let on_the_orb = matches!(ShelfPreview::material(material.id), ShelfPreview::SmartMaterial(_));
|
||||
assert_eq!(on_the_orb, material.smart, "{}", material.id);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,48 @@
|
||||
//! A soft box of the smart material preview studio (see [`crate::material_preview_image`])
|
||||
|
||||
use texturecraft_engine::geom::glam::Vec3;
|
||||
|
||||
/// How much roughness widens a soft box's reflection, in radians per unit of roughness
|
||||
const BLUR_RAD_PER_ROUGHNESS: f32 = 1.1;
|
||||
/// A reflected disc's soft edge: this share of its reflected radius plus a minimum in radians
|
||||
const EDGE_SOFTNESS: f32 = 0.25;
|
||||
const EDGE_SOFTNESS_MIN_RAD: f32 = 0.02;
|
||||
/// The share of a soft box's light that reaches a diffuse surface facing it
|
||||
const DIFFUSE_SHARE: f32 = 0.9;
|
||||
|
||||
/// A round area light far away, seen as a disc in reflections
|
||||
pub struct SoftBox {
|
||||
/// Direction towards the light in view space (+X right, +Y up, +Z towards the viewer), not normalized
|
||||
pub direction: [f32; 3],
|
||||
/// Angular radius of the disc in radians
|
||||
pub radius_rad: f32,
|
||||
/// Brightness of the disc (linear)
|
||||
pub intensity: f32,
|
||||
}
|
||||
|
||||
impl SoftBox {
|
||||
/// The unit direction towards the light
|
||||
pub fn unit_direction(&self) -> Vec3 {
|
||||
Vec3::from(self.direction).normalize_or_zero()
|
||||
}
|
||||
|
||||
/// The light seen along unit direction `view` by a surface of `roughness`: rougher surfaces see the disc wider and dimmer (the same light spread out)
|
||||
pub fn reflected(&self, view: Vec3, roughness: f32) -> f32 {
|
||||
let reflected_radius_rad = self.radius_rad.hypot(roughness * BLUR_RAD_PER_ROUGHNESS);
|
||||
let angle_rad = view.dot(self.unit_direction()).clamp(-1.0, 1.0).acos();
|
||||
let edge_width_rad = EDGE_SOFTNESS * reflected_radius_rad + EDGE_SOFTNESS_MIN_RAD;
|
||||
let inside = smoothstep((reflected_radius_rad - angle_rad) / edge_width_rad);
|
||||
self.intensity * (self.radius_rad / reflected_radius_rad).powi(2) * inside
|
||||
}
|
||||
|
||||
/// The light reaching a diffuse surface with unit normal `normal`
|
||||
pub fn diffuse(&self, normal: Vec3) -> f32 {
|
||||
self.intensity * self.radius_rad * self.radius_rad * DIFFUSE_SHARE * normal.dot(self.unit_direction()).max(0.0)
|
||||
}
|
||||
}
|
||||
|
||||
/// Smooth 0..=1 ramp of `t` (clamped), flat at both ends
|
||||
pub fn smoothstep(t: f32) -> f32 {
|
||||
let t = t.clamp(0.0, 1.0);
|
||||
t * t * (3.0 - 2.0 * t)
|
||||
}
|
||||
@@ -1,6 +1,6 @@
|
||||
//! Shelf and brush preview caches
|
||||
//! Small synchronous renders are limited per frame
|
||||
//! Smart masks and hover previews use [`PreviewWorker`]
|
||||
//! Smart masks, smart materials and hover previews use [`PreviewWorker`]
|
||||
|
||||
use std::collections::{HashMap, VecDeque};
|
||||
|
||||
@@ -16,7 +16,7 @@ use crate::preview_worker::PreviewWorker;
|
||||
use crate::shelf_preview::ShelfPreview;
|
||||
use crate::worker_preview::WorkerPreview;
|
||||
|
||||
/// Shelf thumbnails rendered per frame at most (the rest follow on the next frames)
|
||||
/// UI-thread renders per frame at most; a web worker request uses the whole budget
|
||||
const PER_FRAME: usize = 2;
|
||||
/// Shelf sphere and smart mask thumbnail size in pixels
|
||||
const SPHERE_PX: usize = 72;
|
||||
@@ -37,7 +37,7 @@ pub struct Thumbs {
|
||||
images: HashMap<String, TextureHandle>,
|
||||
/// (frame, thumbnails rendered in it)
|
||||
budget: (u64, usize),
|
||||
/// Renders the smart mask thumbnails and the big previews
|
||||
/// Renders the orb thumbnails and the big previews
|
||||
worker: PreviewWorker,
|
||||
/// Worker-rendered previews by [`worker_key`]
|
||||
rendered: HashMap<String, WorkerPreview>,
|
||||
@@ -82,25 +82,34 @@ impl Thumbs {
|
||||
/// Render within the frame budget; deferred thumbnails request a repaint
|
||||
fn shelf(&mut self, ctx: &egui::Context, preview: ShelfPreview, size_px: usize) -> Option<TextureHandle> {
|
||||
let key = preview.key();
|
||||
if let Some(t) = self.shelf.get(&key) {
|
||||
return Some(t.clone());
|
||||
if let Some(texture) = self.shelf.get(&key) {
|
||||
return Some(texture.clone());
|
||||
}
|
||||
|
||||
if !self.spend_budget(ctx, 1) {
|
||||
return None;
|
||||
}
|
||||
|
||||
// An unknown asset shows as an empty thumbnail
|
||||
let image = preview.image(size_px).unwrap_or_else(|| ColorImage::filled([size_px, size_px], Color32::TRANSPARENT));
|
||||
let texture = ctx.load_texture(format!("thumb_{key}"), image, TextureOptions::LINEAR);
|
||||
self.shelf.insert(key, texture.clone());
|
||||
Some(texture)
|
||||
}
|
||||
|
||||
/// Spend `renders` of this frame's UI-thread budget; when it is spent, request a repaint
|
||||
fn spend_budget(&mut self, ctx: &egui::Context, renders: usize) -> bool {
|
||||
let frame = ctx.cumulative_pass_nr();
|
||||
if self.budget.0 != frame {
|
||||
self.budget = (frame, 0);
|
||||
}
|
||||
if self.budget.1 >= PER_FRAME {
|
||||
if self.budget.1 + renders > PER_FRAME {
|
||||
ctx.request_repaint();
|
||||
return None;
|
||||
return false;
|
||||
}
|
||||
self.budget.1 += 1;
|
||||
|
||||
// An unknown asset shows as an empty thumbnail
|
||||
let image = preview.image(size_px).unwrap_or_else(|| ColorImage::filled([size_px, size_px], Color32::TRANSPARENT));
|
||||
let t = ctx.load_texture(format!("thumb_{key}"), image, TextureOptions::LINEAR);
|
||||
self.shelf.insert(key, t.clone());
|
||||
Some(t)
|
||||
self.budget.1 += renders;
|
||||
true
|
||||
}
|
||||
|
||||
/// Request once per asset and size; return None while pending or after failure
|
||||
@@ -109,13 +118,19 @@ impl Thumbs {
|
||||
self.receive(ctx);
|
||||
|
||||
let key = worker_key(&preview, size_px);
|
||||
if !self.rendered.contains_key(&key) {
|
||||
if !self.rendered.contains_key(&key) && self.may_request(ctx) {
|
||||
let queued = self.worker.request(ctx, PreviewRequest { key: key.clone(), preview, size_px, hover });
|
||||
self.rendered.insert(key.clone(), if queued { WorkerPreview::Rendering } else { WorkerPreview::Failed });
|
||||
}
|
||||
|
||||
self.ready(&key)
|
||||
}
|
||||
|
||||
/// Native workers take every request; the web renders inline, so it takes one per frame
|
||||
fn may_request(&mut self, ctx: &egui::Context) -> bool {
|
||||
!cfg!(target_arch = "wasm32") || self.spend_budget(ctx, PER_FRAME)
|
||||
}
|
||||
|
||||
/// The worker-rendered preview under `key` if it arrived
|
||||
fn ready(&self, key: &str) -> Option<TextureHandle> {
|
||||
match self.rendered.get(key) {
|
||||
@@ -169,9 +184,12 @@ impl Thumbs {
|
||||
self.ready(&worker_key(preview, size_px))
|
||||
}
|
||||
|
||||
/// Sphere thumbnail of built-in material `id`
|
||||
/// Material thumbnail: smart materials come from the worker's orb, plain ones are spheres
|
||||
pub fn material(&mut self, ctx: &egui::Context, id: &'static str) -> Option<TextureHandle> {
|
||||
self.shelf(ctx, ShelfPreview::Material(id), SPHERE_PX)
|
||||
match ShelfPreview::material(id) {
|
||||
preview @ ShelfPreview::SmartMaterial(_) => self.worker_rendered(ctx, preview, SPHERE_PX, false),
|
||||
preview => self.shelf(ctx, preview, SPHERE_PX),
|
||||
}
|
||||
}
|
||||
|
||||
/// Smart mask thumbnail; None until the worker returns it
|
||||
|
||||
@@ -281,19 +281,7 @@ fn tool_controls(app: &mut TextureCraftApp, ui: &mut egui::Ui, tokens: &Tokens)
|
||||
path_controls(app, ui);
|
||||
}
|
||||
}
|
||||
Tool::PolygonFill => {
|
||||
use texturecraft_engine::FillMode;
|
||||
|
||||
for (fill_mode, icon, tooltip) in [
|
||||
(FillMode::Triangle, ic::POLYGON, tr("Triangle fill")),
|
||||
(FillMode::UvIsland, ic::SHAPES, tr("UV island fill")),
|
||||
(FillMode::Mesh, ic::CUBE, tr("Mesh fill")),
|
||||
] {
|
||||
if icon_button(ui, icon, tooltip, app.session.tool.fill_mode == fill_mode, button_size).clicked() {
|
||||
app.session.tool.fill_mode = fill_mode;
|
||||
}
|
||||
}
|
||||
}
|
||||
Tool::PolygonFill => fill_mode_buttons(app, ui),
|
||||
Tool::ColorPicker => {
|
||||
ui.label(RichText::new(tr("Click the mesh to pick its material into the brush")).color(tokens.text_dim));
|
||||
}
|
||||
@@ -317,6 +305,23 @@ fn mode_buttons(app: &mut TextureCraftApp, ui: &mut egui::Ui) {
|
||||
}
|
||||
}
|
||||
|
||||
/// Polygon fill's fill modes (top bar and properties)
|
||||
pub fn fill_mode_buttons(app: &mut TextureCraftApp, ui: &mut egui::Ui) {
|
||||
use texturecraft_engine::FillMode;
|
||||
|
||||
let button_size = ui.spacing().interact_size.y;
|
||||
for (fill_mode, icon, tooltip) in [
|
||||
(FillMode::Triangle, ic::TRIANGLE, tr("Triangle fill")),
|
||||
(FillMode::Polygon, ic::PARALLELOGRAM, tr("Polygon fill")),
|
||||
(FillMode::Mesh, ic::CUBE, tr("Mesh fill")),
|
||||
(FillMode::UvIsland, ic::CHECKERBOARD, tr("UV island fill")),
|
||||
] {
|
||||
if icon_button(ui, icon, tooltip, app.session.tool.fill_mode == fill_mode, button_size).clicked() {
|
||||
app.session.tool.fill_mode = fill_mode;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Path tool options and actions (top bar and properties)
|
||||
pub fn path_controls(app: &mut TextureCraftApp, ui: &mut egui::Ui) {
|
||||
let button_size = ui.spacing().interact_size.y;
|
||||
|
||||
@@ -0,0 +1,21 @@
|
||||
//! A finished stroke's endpoint in one mesh's UV layout
|
||||
|
||||
use texturecraft_engine::{Session, geom::glam::Vec2};
|
||||
|
||||
/// A line anchor scoped to its project, UV layout and texture set
|
||||
#[derive(Clone, Copy, Debug)]
|
||||
pub struct UvPaintPoint {
|
||||
mesh_id: u64,
|
||||
texture_set: usize,
|
||||
uv: Vec2,
|
||||
}
|
||||
|
||||
impl UvPaintPoint {
|
||||
pub(crate) fn new(session: &Session, uv: Vec2) -> Self {
|
||||
Self { mesh_id: session.mesh_id, texture_set: session.ts(), uv }
|
||||
}
|
||||
|
||||
pub(crate) fn uv_for(self, session: &Session) -> Option<Vec2> {
|
||||
(self.mesh_id == session.mesh_id && self.texture_set == session.ts()).then_some(self.uv)
|
||||
}
|
||||
}
|
||||
+219
-33
@@ -9,7 +9,7 @@ use serde_json::json;
|
||||
use texturecraft_engine::camera_cmds::DEFAULT_CAMERA;
|
||||
use texturecraft_engine::core::BakedMap;
|
||||
use texturecraft_engine::geom::glam::{Vec2, Vec3};
|
||||
use texturecraft_engine::{Tool, ViewMode};
|
||||
use texturecraft_engine::{Session, Tool, ViewMode};
|
||||
use texturecraft_render::{Frame, SetHighlight, Shade, ViewKind};
|
||||
|
||||
use crate::TextureCraftApp;
|
||||
@@ -165,6 +165,18 @@ const UV_VIEW_MAX_ZOOM: f32 = 40.0;
|
||||
/// UV zoom change per point of mouse wheel, as a fraction of the zoom
|
||||
const UV_WHEEL_ZOOM_PER_POINT: f32 = 0.002;
|
||||
|
||||
/// Dash length of the straight-line preview, in points
|
||||
const RUBBER_BAND_DASH: f32 = 6.0;
|
||||
|
||||
/// Gap between the straight-line preview's dashes, in points
|
||||
const RUBBER_BAND_GAP: f32 = 4.0;
|
||||
|
||||
/// Opacity of the UV tile outlines in the 2D view
|
||||
const UV_TILE_OUTLINE_ALPHA: u8 = 40;
|
||||
|
||||
/// Smallest skew brush circle in the 2D view, in points, so a tiny brush stays visible
|
||||
const BAKE_PAINT_CURSOR_MIN_RADIUS: f32 = 2.0;
|
||||
|
||||
/// The 2D view's width when the split divider is at `divider_x`
|
||||
fn uv_view_width(full: Rect, divider_x: f32) -> f32 {
|
||||
(full.right() - divider_x - SPLIT_LINE_HALF_WIDTH).max(1.0)
|
||||
@@ -213,12 +225,14 @@ fn shade(app: &TextureCraftApp) -> Shade {
|
||||
};
|
||||
let set_index = app.session.ts();
|
||||
let height_strength = app.session.doc.project.texture_sets.get(set_index).map(|texture_set| texture_set.atlas_height_strength()).unwrap_or(1.0);
|
||||
// Polygon fill shows the polygons it fills without changing the saved wireframe toggles
|
||||
let polygon_fill_tool = app.ui.mode == crate::state::Mode::Painting && app.session.tool.tool == Tool::PolygonFill;
|
||||
Shade {
|
||||
height_strength,
|
||||
view_mode,
|
||||
channel,
|
||||
wireframe: app.ui.uv_wireframe,
|
||||
wireframe_3d: app.ui.wireframe_3d,
|
||||
wireframe: app.ui.uv_wireframe || polygon_fill_tool,
|
||||
wireframe_3d: app.ui.wireframe_3d || polygon_fill_tool,
|
||||
..Shade::from_project(&app.session.doc.project)
|
||||
}
|
||||
}
|
||||
@@ -588,8 +602,17 @@ fn view_3d(app: &mut TextureCraftApp, ui: &mut Ui, rect: Rect, sync: &mut Pendin
|
||||
let path_tool = app.session.tool.tool == Tool::Path;
|
||||
let viewport = app.session.viewport;
|
||||
let show = |app: &TextureCraftApp, point: Vec3| project(app, rect, point);
|
||||
let mut fill_box = None;
|
||||
if painting && path_tool {
|
||||
path_input(app, ui, &response, false, |app, pointer| app.session.pick(local(pointer), viewport).map(|hit| hit.pos), show);
|
||||
} else if painting && app.session.tool.tool == Tool::PolygonFill {
|
||||
fill_box = polygon_fill_input(
|
||||
app,
|
||||
ui,
|
||||
&response,
|
||||
|session, point| session.polygon_fill(local(point), viewport),
|
||||
|session, corner, opposite| session.drag_polygon_fill_box(local(corner), local(opposite), viewport),
|
||||
);
|
||||
} else if painting {
|
||||
let pressure = pen_pressure(ui);
|
||||
if response.drag_started_by(PointerButton::Primary) || response.clicked_by(PointerButton::Primary) {
|
||||
@@ -634,6 +657,7 @@ fn view_3d(app: &mut TextureCraftApp, ui: &mut Ui, rect: Rect, sync: &mut Pendin
|
||||
visible: app.session.doc.project.texture_sets.iter().map(|texture_set| texture_set.visible).collect(),
|
||||
};
|
||||
add_callback(app, ui, rect, frame, sync);
|
||||
polygon_fill_box_overlay(ui, rect, fill_box);
|
||||
|
||||
// Shelf drops: a material goes above the selection of the set under the pointer, an alpha on the brush
|
||||
crate::shelf::drop_target(app, ui, &response, crate::shelf::DropZone::View3d);
|
||||
@@ -1022,11 +1046,101 @@ fn path_overlay(app: &TextureCraftApp, ui: &Ui, rect: Rect, resp: &egui::Respons
|
||||
}
|
||||
}
|
||||
|
||||
/// Dashed preview of a straight segment.
|
||||
/// Dashed preview of a straight segment, clipped to `rect` so an end far off screen adds no dashes.
|
||||
fn rubber_band(ui: &Ui, rect: Rect, from: Pos2, to: Pos2) {
|
||||
let p = ui.painter_at(rect);
|
||||
p.add(egui::Shape::dashed_line(&[from, to], Stroke::new(2.5, Color32::from_black_alpha(120)), 6.0, 4.0));
|
||||
p.add(egui::Shape::dashed_line(&[from, to], Stroke::new(1.0, Color32::from_white_alpha(200)), 6.0, 4.0));
|
||||
let Some(visible) = visible_dashes(rect, from, to) else { return };
|
||||
let painter = ui.painter_at(rect);
|
||||
for stroke in [Stroke::new(2.5, Color32::from_black_alpha(120)), Stroke::new(1.0, Color32::from_white_alpha(200))] {
|
||||
painter.add(egui::Shape::dashed_line(&visible, stroke, RUBBER_BAND_DASH, RUBBER_BAND_GAP));
|
||||
}
|
||||
}
|
||||
|
||||
/// The part of `from`→`to` inside `rect`, its start moved back to a whole dash period so the dashes keep their place.
|
||||
fn visible_dashes(rect: Rect, from: Pos2, to: Pos2) -> Option<[Pos2; 2]> {
|
||||
let direction = to - from;
|
||||
let length = direction.length();
|
||||
if length == 0.0 {
|
||||
return rect.contains(from).then_some([from, to]);
|
||||
}
|
||||
|
||||
// Clip the segment's parameter range against each axis's slab
|
||||
let (mut enter, mut exit) = (0.0_f32, 1.0_f32);
|
||||
for (delta, origin, low, high) in [(direction.x, from.x, rect.left(), rect.right()), (direction.y, from.y, rect.top(), rect.bottom())] {
|
||||
if delta == 0.0 {
|
||||
if origin < low || origin > high {
|
||||
return None;
|
||||
}
|
||||
continue;
|
||||
}
|
||||
let (at_low, at_high) = ((low - origin) / delta, (high - origin) / delta);
|
||||
enter = enter.max(at_low.min(at_high));
|
||||
exit = exit.min(at_low.max(at_high));
|
||||
}
|
||||
if enter > exit {
|
||||
return None;
|
||||
}
|
||||
|
||||
let period = RUBBER_BAND_DASH + RUBBER_BAND_GAP;
|
||||
let start = (enter * length / period).floor() * period / length;
|
||||
Some([from + direction * start, from + direction * exit])
|
||||
}
|
||||
|
||||
/// Polygon fill in a view: a click fills one target, a drag fills its box live (one undo step); returns the box to draw over the view image
|
||||
fn polygon_fill_input(
|
||||
app: &mut TextureCraftApp,
|
||||
ui: &Ui,
|
||||
response: &egui::Response,
|
||||
fill_at: impl Fn(&mut Session, Pos2) -> texturecraft_engine::Result<usize>,
|
||||
drag_box: impl Fn(&mut Session, Pos2, Pos2) -> texturecraft_engine::Result<usize>,
|
||||
) -> Option<Rect> {
|
||||
let origin_id = response.id.with("polygon_fill_box");
|
||||
let dragging = response.dragged_by(PointerButton::Primary);
|
||||
let released = response.drag_stopped_by(PointerButton::Primary);
|
||||
let held = ui.input(|input| input.pointer.primary_down());
|
||||
if !held && !released {
|
||||
// A drag this view started and cut short (Alt, a second finger) keeps what it filled as one step
|
||||
if ui.data_mut(|data| data.remove_temp::<Pos2>(origin_id)).is_some() {
|
||||
app.session.end_polygon_fill_box();
|
||||
}
|
||||
} else if dragging && let Some(press) = ui.input(|input| input.pointer.press_origin()) {
|
||||
ui.data_mut(|data| data.insert_temp(origin_id, press));
|
||||
}
|
||||
|
||||
// Consume the origin on release so a new press cannot resume the previous rectangle
|
||||
let origin = if released { ui.data_mut(|data| data.remove_temp::<Pos2>(origin_id)) } else { ui.data(|data| data.get_temp::<Pos2>(origin_id)) };
|
||||
let pointer = ui.input(|input| input.pointer.latest_pos());
|
||||
let (filled, dragged_box) = match (origin, pointer) {
|
||||
_ if response.clicked_by(PointerButton::Primary) => (response.interact_pointer_pos().map(|point| fill_at(&mut app.session, point)), None),
|
||||
(Some(origin), Some(pointer)) if released => {
|
||||
// The drag ends on release even when its last move failed
|
||||
let shown = drag_box(&mut app.session, origin, pointer);
|
||||
let filled = app.session.end_polygon_fill_box();
|
||||
(Some(shown.map(|_| filled)), None)
|
||||
}
|
||||
_ if released => {
|
||||
app.session.end_polygon_fill_box();
|
||||
(None, None)
|
||||
}
|
||||
(Some(origin), Some(pointer)) => (Some(drag_box(&mut app.session, origin, pointer)), Some(Rect::from_two_pos(origin, pointer))),
|
||||
_ => (None, None),
|
||||
};
|
||||
|
||||
if let Some(Err(error)) = filled {
|
||||
app.toast(error.to_string(), true);
|
||||
}
|
||||
|
||||
dragged_box
|
||||
}
|
||||
|
||||
/// How strongly the polygon fill box tints what it covers (0..1)
|
||||
const FILL_BOX_TINT: f32 = 0.15;
|
||||
|
||||
/// The polygon fill box being dragged, over view `rect`
|
||||
fn polygon_fill_box_overlay(ui: &Ui, rect: Rect, fill_box: Option<Rect>) {
|
||||
let Some(fill_box) = fill_box else { return };
|
||||
|
||||
let accent = Tokens::get(ui.ctx()).viewport_accent;
|
||||
ui.painter_at(rect).rect(fill_box, 0.0, accent.gamma_multiply(FILL_BOX_TINT), Stroke::new(1.0, accent), egui::StrokeKind::Inside);
|
||||
}
|
||||
|
||||
/// V held with the Clone tool in painting mode: clicks set the clone source.
|
||||
@@ -1174,11 +1288,12 @@ fn pen_pressure(ui: &Ui) -> f32 {
|
||||
}
|
||||
}
|
||||
|
||||
/// The 2D (UV) view: navigation, painting in texture coordinates and the overlays drawn over the texture.
|
||||
fn view_2d(app: &mut TextureCraftApp, ui: &mut Ui, rect: Rect, sync: &mut PendingSync) {
|
||||
let tokens = Tokens::get(ui.ctx());
|
||||
let response = ui.interact(rect, ui.scope_id().with("view2d"), Sense::click_and_drag());
|
||||
let size = rect.size();
|
||||
let alt = ui.input(|input| input.modifiers.alt);
|
||||
let (alt, shift) = ui.input(|input| (input.modifiers.alt, input.modifiers.shift));
|
||||
let adjusting = brush_drag(app, ui, &response);
|
||||
|
||||
// Pan with a middle drag or Alt+left drag, zoom with the wheel about the cursor
|
||||
@@ -1239,32 +1354,19 @@ fn view_2d(app: &mut TextureCraftApp, ui: &mut Ui, rect: Rect, sync: &mut Pendin
|
||||
|
||||
// Painting in UV space
|
||||
let painting = app.ui.mode == crate::state::Mode::Painting && app.properties_popup.is_none() && !alt && !adjusting && !v_held;
|
||||
let mut fill_box = None;
|
||||
if painting && path_tool {
|
||||
path_input(app, ui, &response, true, |_, pointer| Some(to_uv(pointer).extend(0.0)), show);
|
||||
} else if painting && app.session.tool.tool == Tool::PolygonFill {
|
||||
fill_box = polygon_fill_input(
|
||||
app,
|
||||
ui,
|
||||
&response,
|
||||
|session, point| session.polygon_fill_uv(to_uv(point)),
|
||||
|session, corner, opposite| session.drag_polygon_fill_box_uv(to_uv(corner), to_uv(opposite)),
|
||||
);
|
||||
} else if painting {
|
||||
let pressure = pen_pressure(ui);
|
||||
if response.drag_started_by(PointerButton::Primary) || response.clicked_by(PointerButton::Primary) {
|
||||
if let Some(pointer) = response.interact_pointer_pos()
|
||||
&& let Err(error) = app.session.begin_stroke_uv(to_uv(pointer), pressure)
|
||||
{
|
||||
app.toast(error.to_string(), true);
|
||||
}
|
||||
if response.clicked_by(PointerButton::Primary)
|
||||
&& let Err(error) = app.session.end_stroke()
|
||||
{
|
||||
app.toast(error.to_string(), true);
|
||||
}
|
||||
} else if response.dragged_by(PointerButton::Primary)
|
||||
&& app.session.stroke_active()
|
||||
&& let Some(pointer) = response.interact_pointer_pos()
|
||||
{
|
||||
app.session.continue_stroke_uv(to_uv(pointer), pressure);
|
||||
}
|
||||
if response.drag_stopped_by(PointerButton::Primary)
|
||||
&& let Err(error) = app.session.end_stroke()
|
||||
{
|
||||
app.toast(error.to_string(), true);
|
||||
}
|
||||
paint_2d_input(app, ui, &response, shift, &to_uv);
|
||||
}
|
||||
if response.double_clicked() && !(painting && path_tool) {
|
||||
app.ui.uv_zoom = 1.0;
|
||||
@@ -1280,12 +1382,13 @@ fn view_2d(app: &mut TextureCraftApp, ui: &mut Ui, rect: Rect, sync: &mut Pendin
|
||||
visible: app.session.doc.project.texture_sets.iter().map(|texture_set| texture_set.visible).collect(),
|
||||
};
|
||||
add_callback(app, ui, rect, frame, sync);
|
||||
polygon_fill_box_overlay(ui, rect, fill_box);
|
||||
crate::shelf::drop_target(app, ui, &response, crate::shelf::DropZone::View2d);
|
||||
|
||||
// The UV tile outlines (numbered for UDIM sets) and the path being edited
|
||||
let painter = ui.painter_at(rect);
|
||||
let set = app.session.doc.project.texture_sets.get(ts);
|
||||
let outline = |tile: Rect| painter.rect_stroke(tile, 0.0, Stroke::new(1.0, Color32::from_white_alpha(40)), egui::StrokeKind::Outside);
|
||||
let outline = |tile: Rect| painter.rect_stroke(tile, 0.0, Stroke::new(1.0, Color32::from_white_alpha(UV_TILE_OUTLINE_ALPHA)), egui::StrokeKind::Outside);
|
||||
match set.and_then(|texture_set| Some((texture_set, texture_set.tile_grid()?))) {
|
||||
Some((texture_set, grid)) => {
|
||||
for (udim, (block_x, block_y)) in texture_set.uv_tiles.iter().filter_map(|udim| Some((*udim, grid.block(*udim)?))) {
|
||||
@@ -1311,10 +1414,21 @@ fn view_2d(app: &mut TextureCraftApp, ui: &mut Ui, rect: Rect, sync: &mut Pendin
|
||||
path_overlay(app, ui, rect, &response, true, show);
|
||||
}
|
||||
|
||||
// Shift: preview the straight line Shift+click paints from the last stroke
|
||||
if painting
|
||||
&& shift
|
||||
&& !path_tool
|
||||
&& brush_tool(app.session.tool.tool)
|
||||
&& let Some(from) = app.last_paint_uv.and_then(|point| point.uv_for(&app.session))
|
||||
&& let Some(hover) = response.hover_pos()
|
||||
{
|
||||
rubber_band(ui, rect, to_screen(from.x, from.y), hover);
|
||||
}
|
||||
|
||||
if app.ui.mode == crate::state::Mode::Baking {
|
||||
bake_paint_overlay(app, ui, &painter, to_screen(0.0, 1.0), to_screen(1.0, 0.0));
|
||||
if bake_paint_on && let Some(hover) = response.hover_pos() {
|
||||
let radius = (to_screen(app.ui.bake_paint_brush.radius, 0.0).x - to_screen(0.0, 0.0).x).abs().max(2.0);
|
||||
let radius = (to_screen(app.ui.bake_paint_brush.radius, 0.0).x - to_screen(0.0, 0.0).x).abs().max(BAKE_PAINT_CURSOR_MIN_RADIUS);
|
||||
painter.circle_stroke(hover, radius, Stroke::new(1.0, Color32::from_white_alpha(200)));
|
||||
}
|
||||
}
|
||||
@@ -1326,6 +1440,47 @@ fn view_2d(app: &mut TextureCraftApp, ui: &mut Ui, rect: Rect, sync: &mut Pendin
|
||||
ui.painter().text(rect.right_bottom() + vec2(-10.0, -10.0), egui::Align2::RIGHT_BOTTOM, name, egui::FontId::proportional(11.0), tokens.viewport_text);
|
||||
}
|
||||
|
||||
/// Paint in the 2D view: a press starts a stroke, a drag continues it, Shift+click draws a line from the last stroke.
|
||||
fn paint_2d_input(app: &mut TextureCraftApp, ui: &Ui, response: &egui::Response, shift: bool, to_uv: &dyn Fn(egui::Pos2) -> Vec2) {
|
||||
let pressure = pen_pressure(ui);
|
||||
|
||||
// Where the stroke under way is; it becomes the line start only when the stroke finishes
|
||||
let stroke_end = ui.scope_id().with("paint_2d_stroke_end");
|
||||
|
||||
if response.drag_started_by(PointerButton::Primary) || response.clicked_by(PointerButton::Primary) {
|
||||
let line_start = app.last_paint_uv.filter(|_| shift).and_then(|point| point.uv_for(&app.session));
|
||||
if let Some(pointer) = response.interact_pointer_pos() {
|
||||
let uv = to_uv(pointer);
|
||||
match app.session.begin_stroke_uv(line_start.unwrap_or(uv), pressure) {
|
||||
Ok(()) => {
|
||||
if line_start.is_some() {
|
||||
app.session.continue_stroke_uv(uv, pressure);
|
||||
}
|
||||
ui.data_mut(|data| data.insert_temp(stroke_end, crate::uv_paint_point::UvPaintPoint::new(&app.session, uv)));
|
||||
}
|
||||
Err(error) => app.toast(error.to_string(), true),
|
||||
}
|
||||
}
|
||||
} else if response.dragged_by(PointerButton::Primary)
|
||||
&& app.session.stroke_active()
|
||||
&& let Some(pointer) = response.interact_pointer_pos()
|
||||
{
|
||||
let uv = to_uv(pointer);
|
||||
app.session.continue_stroke_uv(uv, pressure);
|
||||
ui.data_mut(|data| data.insert_temp(stroke_end, crate::uv_paint_point::UvPaintPoint::new(&app.session, uv)));
|
||||
}
|
||||
|
||||
// Escape cancels the stroke and ends the drag without a primary release, so a cancelled stroke never gets here
|
||||
if response.clicked_by(PointerButton::Primary) || response.drag_stopped_by(PointerButton::Primary) {
|
||||
let finishing = app.session.stroke_active();
|
||||
match app.session.end_stroke() {
|
||||
Ok(()) if finishing => app.last_paint_uv = ui.data(|data| data.get_temp(stroke_end)),
|
||||
Ok(()) => {}
|
||||
Err(error) => app.toast(error.to_string(), true),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Paint the skew map under the pointer in the 2D view (a click is one dab, a drag a stroke).
|
||||
fn bake_paint_input(app: &mut TextureCraftApp, ui: &Ui, resp: &egui::Response, to_uv: &dyn Fn(egui::Pos2) -> Vec2) {
|
||||
let last = ui.scope_id().with(("bake_paint_last", app.session.ts(), app.ui.bake_paint_brush.target as u8));
|
||||
@@ -1377,3 +1532,34 @@ fn bake_paint_overlay(app: &TextureCraftApp, ui: &Ui, painter: &egui::Painter, t
|
||||
};
|
||||
painter.image(tex.id(), Rect::from_two_pos(top_left, bottom_right), Rect::from_min_max(pos2(0.0, 0.0), pos2(1.0, 1.0)), Color32::WHITE);
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
const VIEW: Rect = Rect::from_min_max(pos2(0.0, 0.0), pos2(100.0, 100.0));
|
||||
const DASH_PERIOD: f32 = RUBBER_BAND_DASH + RUBBER_BAND_GAP;
|
||||
|
||||
#[test]
|
||||
fn a_far_start_is_clipped_to_the_view_on_a_whole_dash_period() {
|
||||
let far_start = pos2(-10_003.0, 50.0);
|
||||
|
||||
let [start, end] = visible_dashes(VIEW, far_start, pos2(50.0, 50.0)).unwrap();
|
||||
|
||||
assert!(start.x <= VIEW.left() && start.x > VIEW.left() - DASH_PERIOD, "starts at the view's edge: {start:?}");
|
||||
let periods = (start.x - far_start.x) / DASH_PERIOD;
|
||||
assert!((periods - periods.round()).abs() < 1e-3, "a whole number of dash periods from the real start: {periods}");
|
||||
assert_eq!(end, pos2(50.0, 50.0));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_segment_inside_the_view_is_kept_whole() {
|
||||
assert_eq!(visible_dashes(VIEW, pos2(10.0, 20.0), pos2(90.0, 80.0)), Some([pos2(10.0, 20.0), pos2(90.0, 80.0)]));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_segment_outside_the_view_draws_nothing() {
|
||||
assert_eq!(visible_dashes(VIEW, pos2(-50.0, -10.0), pos2(150.0, -10.0)), None);
|
||||
assert_eq!(visible_dashes(VIEW, pos2(-50.0, 120.0), pos2(120.0, 300.0)), None);
|
||||
}
|
||||
}
|
||||
@@ -7,6 +7,6 @@ pub enum WorkerPreview {
|
||||
/// Requested; the worker has not answered yet
|
||||
Rendering,
|
||||
Ready(TextureHandle),
|
||||
/// The asset is unknown or the worker could not render it (the tile keeps its placeholder)
|
||||
/// The asset is unknown or the worker could not render it (the tile keeps its loading icon)
|
||||
Failed,
|
||||
}
|
||||
File renamed without changes.
File renamed without changes.
File renamed without changes.
File renamed without changes.
@@ -0,0 +1,86 @@
|
||||
use egui::Role;
|
||||
use egui_kittest::Harness;
|
||||
use egui_kittest::kittest::Queryable;
|
||||
use serde_json::json;
|
||||
use texturecraft_engine::core::{CurvatureMode, EffectKind, LayerId};
|
||||
use texturecraft_engine::{ViewMode, execute};
|
||||
use texturecraft_ui_egui::TextureCraftApp;
|
||||
use texturecraft_ui_egui::docking::Panel;
|
||||
|
||||
fn harness(render: bool) -> (Harness<'static, TextureCraftApp>, LayerId) {
|
||||
let mut session = texturecraft_engine::sample_session(512, 256).unwrap();
|
||||
session.active_set = 1;
|
||||
session.camera.pitch = 0.5;
|
||||
let layer = execute(&mut session, "layer.add.fill", &json!({"color": [0.8, 0.3, 0.1]})).unwrap()["layer"].as_u64().unwrap();
|
||||
execute(&mut session, "mask.add.black", &json!({})).unwrap();
|
||||
let effect = execute(&mut session, "effect.add.generator", &json!({"generator": "curvature"})).unwrap()["effect"].as_u64().unwrap();
|
||||
session.view = ViewMode::Mask(LayerId(layer));
|
||||
session.update();
|
||||
let builder = Harness::builder().with_size(egui::vec2(1600.0, 1200.0));
|
||||
let builder = if render { builder.wgpu() } else { builder };
|
||||
let mut harness = builder.build_eframe(|context| TextureCraftApp::new(context, session));
|
||||
harness.state_mut().ui.dock.close(Panel::Layers);
|
||||
harness.state_mut().ui.dock.close(Panel::TextureSetSettings);
|
||||
harness.state_mut().ui.dock.focus(Panel::Properties);
|
||||
harness.run_steps(6);
|
||||
(harness, LayerId(effect))
|
||||
}
|
||||
|
||||
fn select_mode(harness: &mut Harness<'_, TextureCraftApp>, current: CurvatureMode, next: CurvatureMode) {
|
||||
harness.get_all_by_role(Role::ComboBox).find(|node| node.value().as_deref() == Some(current.label())).unwrap().click();
|
||||
harness.run_steps(2);
|
||||
harness.get_by_label(next.label()).click();
|
||||
harness.run_steps(4);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn mode_and_detail_controls_apply_and_undo() {
|
||||
let (mut harness, effect) = harness(false);
|
||||
select_mode(&mut harness, CurvatureMode::Edges, CurvatureMode::Cavities);
|
||||
let detail = |harness: &Harness<'_, TextureCraftApp>| match &harness.state().session.doc.project.effect(effect).unwrap().1.kind {
|
||||
EffectKind::Generator(generator) => generator.detail.clone().unwrap(),
|
||||
_ => panic!("expected a curvature generator"),
|
||||
};
|
||||
assert_eq!(detail(&harness).mode, CurvatureMode::Cavities);
|
||||
let previous = detail(&harness);
|
||||
let history = harness.state().session.history_labels().len();
|
||||
harness.get_by_label("8 px").scroll_to_me();
|
||||
harness.run_steps(3);
|
||||
let label = harness.get_by_label("8 px").rect();
|
||||
let start = egui::pos2(label.left() + 20.0, label.bottom() + 10.0);
|
||||
let end = start + egui::vec2(100.0, 0.0);
|
||||
harness.drag_at(start);
|
||||
harness.run_steps(2);
|
||||
harness.hover_at(end);
|
||||
harness.run_steps(2);
|
||||
harness.drop_at(end);
|
||||
harness.run_steps(3);
|
||||
assert_ne!(detail(&harness).weights[4], previous.weights[4]);
|
||||
assert_eq!(harness.state().session.history_labels().len(), history + 1);
|
||||
harness.state_mut().session.undo().unwrap();
|
||||
assert_eq!(detail(&harness), previous);
|
||||
}
|
||||
|
||||
#[test]
|
||||
#[ignore = "requires a GPU adapter and TC_UI_SNAPSHOTS"]
|
||||
fn curvature_mode_snapshots() {
|
||||
let directory = std::path::PathBuf::from(std::env::var_os("TC_UI_SNAPSHOTS").expect("set TC_UI_SNAPSHOTS"));
|
||||
std::fs::create_dir_all(&directory).unwrap();
|
||||
let (mut harness, _) = harness(true);
|
||||
eprintln!("Rendering adapter: {}", harness.state().gpu.as_ref().unwrap().adapter);
|
||||
let mut current = CurvatureMode::Edges;
|
||||
for (mode, filename) in [
|
||||
(CurvatureMode::Edges, "curvature-edges.png"),
|
||||
(CurvatureMode::Cavities, "curvature-cavities.png"),
|
||||
(CurvatureMode::Both, "curvature-both.png"),
|
||||
(CurvatureMode::Raw, "curvature-raw.png"),
|
||||
] {
|
||||
if mode != current {
|
||||
select_mode(&mut harness, current, mode);
|
||||
}
|
||||
current = mode;
|
||||
harness.state_mut().session.update();
|
||||
harness.run_steps(12);
|
||||
harness.render().unwrap().save(directory.join(filename)).unwrap();
|
||||
}
|
||||
}
|
||||
File renamed without changes.
File renamed without changes.
File renamed without changes.
File renamed without changes.
@@ -0,0 +1,199 @@
|
||||
//! The filter slot in Properties swaps a filter through its picker, and Add filter adds one
|
||||
|
||||
use egui::accesskit::Role;
|
||||
use egui_kittest::Harness;
|
||||
use egui_kittest::kittest::Queryable;
|
||||
use serde_json::{Value, json};
|
||||
use texturecraft_engine::core::{EffectKind, Filter, LayerId};
|
||||
use texturecraft_engine::{StackTarget, execute};
|
||||
use texturecraft_ui_egui::TextureCraftApp;
|
||||
|
||||
/// The app with an Invert filter on a fill layer's content, selected so Properties shows its slot
|
||||
fn app_with_invert() -> (Harness<'static, TextureCraftApp>, LayerId) {
|
||||
let mut session = texturecraft_engine::sample_session(256, 64).unwrap();
|
||||
let layer = execute(&mut session, "layer.add.fill", &Value::Null).unwrap();
|
||||
let effect = execute(&mut session, "effect.add.filter", &json!({"target": "content", "filter": "invert"})).unwrap();
|
||||
let effect = LayerId(effect["effect"].as_u64().unwrap());
|
||||
execute(&mut session, "layer.select", &json!({"layer": layer["layer"]})).unwrap();
|
||||
session.target = StackTarget::Effect(effect);
|
||||
|
||||
let mut harness = Harness::builder().with_size(egui::vec2(1600.0, 1400.0)).build_eframe(|cc| TextureCraftApp::new(cc, session));
|
||||
harness.run_steps(4);
|
||||
(harness, effect)
|
||||
}
|
||||
|
||||
/// The kind of effect `effect` now
|
||||
fn kind(harness: &Harness<'_, TextureCraftApp>, effect: LayerId) -> EffectKind {
|
||||
harness.state().session.doc.project.effect(effect).unwrap().1.kind.clone()
|
||||
}
|
||||
|
||||
/// Clicks the Invert slot, which opens its picker
|
||||
fn open_picker(harness: &mut Harness<'_, TextureCraftApp>) {
|
||||
harness.get_by_role_and_label(Role::ComboBox, "Invert").click();
|
||||
harness.run_steps(3);
|
||||
assert!(egui::Popup::is_any_open(&harness.ctx), "clicking the slot opens the picker");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn picking_from_the_slot_swaps_the_filter() {
|
||||
let (mut harness, effect) = app_with_invert();
|
||||
open_picker(&mut harness);
|
||||
|
||||
// The picker's search field has the focus as it opens
|
||||
harness.event(egui::Event::Text("sharp".into()));
|
||||
harness.run_steps(3);
|
||||
assert_eq!(harness.query_all_by_label("Blur").count(), 0, "the search hides filters that don't match");
|
||||
|
||||
harness.get_by_label("Sharpen").click();
|
||||
harness.run_steps(3);
|
||||
|
||||
assert!(matches!(kind(&harness, effect), EffectKind::Filter(Filter::Sharpen { .. })), "{:?}", kind(&harness, effect));
|
||||
assert!(!egui::Popup::is_any_open(&harness.ctx), "a pick closes the picker");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn escape_closes_the_picker_without_changes() {
|
||||
let (mut harness, effect) = app_with_invert();
|
||||
open_picker(&mut harness);
|
||||
|
||||
// Without the search field's focus, the painting shortcuts see Escape first
|
||||
harness.ctx.memory_mut(|memory| memory.stop_text_input());
|
||||
harness.run_steps(2);
|
||||
harness.key_press(egui::Key::Escape);
|
||||
harness.run_steps(3);
|
||||
|
||||
assert!(!egui::Popup::is_any_open(&harness.ctx));
|
||||
assert!(matches!(kind(&harness, effect), EffectKind::Filter(Filter::Invert)));
|
||||
}
|
||||
|
||||
/// Opens the wand's Add effect menu and clicks Add filter
|
||||
fn add_filter_from_the_wand(harness: &mut Harness<'_, TextureCraftApp>) {
|
||||
harness.get_by_label(egui_phosphor::regular::MAGIC_WAND).click();
|
||||
harness.run_steps(3);
|
||||
|
||||
harness.get_by_label("Add filter").click();
|
||||
harness.run_steps(3);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn add_filter_adds_a_filter_selects_it_and_opens_its_picker() {
|
||||
let (mut harness, _) = app_with_invert();
|
||||
add_filter_from_the_wand(&mut harness);
|
||||
|
||||
let StackTarget::Effect(added) = harness.state().session.target else { panic!("the new filter is selected") };
|
||||
assert!(matches!(kind(&harness, added), EffectKind::Filter(Filter::Hsl { .. })), "{:?}", kind(&harness, added));
|
||||
assert!(harness.query_by_role_and_label(Role::ComboBox, "HSL Perceptive").is_some(), "Properties shows the new filter's slot");
|
||||
assert!(egui::Popup::is_any_open(&harness.ctx), "the new filter's picker is open to choose the real filter");
|
||||
|
||||
// The search field has the focus, and a search brings Sharpen into view
|
||||
harness.event(egui::Event::Text("sharp".into()));
|
||||
harness.run_steps(3);
|
||||
harness.get_by_label("Sharpen").click();
|
||||
harness.run_steps(3);
|
||||
assert!(matches!(kind(&harness, added), EffectKind::Filter(Filter::Sharpen { .. })), "{:?}", kind(&harness, added));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn escape_after_add_filter_keeps_the_neutral_filter() {
|
||||
let (mut harness, _) = app_with_invert();
|
||||
add_filter_from_the_wand(&mut harness);
|
||||
assert!(harness.query_by_label("Sharpen").is_some(), "Add filter opened the picker");
|
||||
|
||||
harness.key_press(egui::Key::Escape);
|
||||
harness.run_steps(3);
|
||||
|
||||
let StackTarget::Effect(added) = harness.state().session.target else { panic!("the new filter stays selected") };
|
||||
assert!(!egui::Popup::is_any_open(&harness.ctx));
|
||||
assert!(matches!(kind(&harness, added), EffectKind::Filter(Filter::Hsl { .. })), "{:?}", kind(&harness, added));
|
||||
|
||||
harness.state_mut().run("edit.undo", Value::Null);
|
||||
assert!(harness.state().session.doc.project.effect(added).is_none(), "one undo removes the neutral filter");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn add_filter_on_a_mask_adds_it_to_the_mask() {
|
||||
let (mut harness, _) = app_with_invert();
|
||||
let layer = harness.state().session.selected_layer().unwrap();
|
||||
// A new mask becomes the selected target, so the wand adds to it
|
||||
harness.state_mut().run("mask.add.white", json!({"layer": layer.0}));
|
||||
harness.run_steps(3);
|
||||
|
||||
add_filter_from_the_wand(&mut harness);
|
||||
|
||||
let StackTarget::Effect(added) = harness.state().session.target else { panic!("the new filter is selected") };
|
||||
let mask = harness.state().session.doc.project.layer(layer).unwrap().mask.clone().unwrap();
|
||||
assert!(mask.effects.iter().any(|effect| effect.id == added), "the filter went on the mask");
|
||||
assert!(matches!(kind(&harness, added), EffectKind::Filter(Filter::Hsl { .. })), "{:?}", kind(&harness, added));
|
||||
assert!(harness.query_by_label("Sharpen").is_some(), "the mask filter's picker is open");
|
||||
assert!(harness.query_by_label("Grayscale").is_none(), "the picker leaves out content-only filters");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn add_filter_reopens_closed_properties_to_show_its_picker() {
|
||||
let (mut harness, _) = app_with_invert();
|
||||
harness.state_mut().ui.dock.close(texturecraft_ui_egui::docking::Panel::Properties);
|
||||
harness.run_steps(3);
|
||||
assert!(harness.query_by_role_and_label(Role::ComboBox, "Invert").is_none());
|
||||
|
||||
add_filter_from_the_wand(&mut harness);
|
||||
|
||||
assert!(harness.query_by_role_and_label(Role::ComboBox, "HSL Perceptive").is_some(), "Add filter reveals Properties");
|
||||
assert!(harness.query_by_label("Sharpen").is_some(), "the picker opens immediately");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn keyboard_opens_the_slot_and_outside_click_closes_it() {
|
||||
let (mut harness, effect) = app_with_invert();
|
||||
for key in [egui::Key::Enter, egui::Key::Space] {
|
||||
harness.get_by_role_and_label(Role::ComboBox, "Invert").focus();
|
||||
harness.key_press(key);
|
||||
harness.run_steps(3);
|
||||
assert!(egui::Popup::is_any_open(&harness.ctx));
|
||||
|
||||
let position = harness.state().viewport_rect.center();
|
||||
harness.hover_at(position);
|
||||
for pressed in [true, false] {
|
||||
harness.event(egui::Event::PointerButton { pos: position, button: egui::PointerButton::Primary, pressed, modifiers: egui::Modifiers::NONE });
|
||||
harness.run_steps(1);
|
||||
}
|
||||
harness.run_steps(3);
|
||||
assert!(!egui::Popup::is_any_open(&harness.ctx));
|
||||
assert!(matches!(kind(&harness, effect), EffectKind::Filter(Filter::Invert)));
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
#[ignore = "requires an offscreen GPU adapter and TC_UI_SNAPSHOTS"]
|
||||
fn filter_picker_snapshots_and_frame_timings() {
|
||||
let output = std::path::PathBuf::from(std::env::var_os("TC_UI_SNAPSHOTS").expect("set TC_UI_SNAPSHOTS"));
|
||||
std::fs::create_dir_all(&output).unwrap();
|
||||
let mut session = texturecraft_engine::sample_session(256, 64).unwrap();
|
||||
execute(&mut session, "layer.add.fill", &Value::Null).unwrap();
|
||||
execute(&mut session, "effect.add.filter", &json!({"target": "content", "filter": "invert"})).unwrap();
|
||||
let mut harness = Harness::builder().with_size(egui::vec2(1600.0, 960.0)).wgpu().build_eframe(|cc| {
|
||||
eprintln!("selected graphics adapter: {:?}", cc.wgpu_render_state.as_ref().unwrap().adapter.get_info());
|
||||
TextureCraftApp::new(cc, session)
|
||||
});
|
||||
harness.run_steps(20);
|
||||
let start = std::time::Instant::now();
|
||||
open_picker(&mut harness);
|
||||
eprintln!("picker open and first 3 UI frames: {:.3} ms", start.elapsed().as_secs_f64() * 1000.0);
|
||||
harness.run_steps(20);
|
||||
for (brightness, name) in
|
||||
[(texturecraft_ui_egui::theme::Brightness::MediumDark, "filter-picker"), (texturecraft_ui_egui::theme::Brightness::Light, "filter-picker-light")]
|
||||
{
|
||||
harness.state_mut().ui.prefs.brightness = brightness;
|
||||
harness.run_steps(3);
|
||||
harness.render().unwrap().save(output.join(format!("{name}.png"))).unwrap();
|
||||
}
|
||||
let start = std::time::Instant::now();
|
||||
harness.run_steps(120);
|
||||
eprintln!("warm open picker: {:.3} ms/UI frame (120 frames, excluding GPU readback)", start.elapsed().as_secs_f64() * 1000.0 / 120.0);
|
||||
|
||||
harness.event(egui::Event::Text("sharp".into()));
|
||||
harness.run_steps(3);
|
||||
harness.render().unwrap().save(output.join("filter-picker-search.png")).unwrap();
|
||||
harness.get_by_label("Sharpen").click();
|
||||
harness.run_steps(3);
|
||||
harness.render().unwrap().save(output.join("filter-picker-selected.png")).unwrap();
|
||||
}
|
||||
File renamed without changes.
File renamed without changes.
File renamed without changes.
@@ -0,0 +1,27 @@
|
||||
//! One integration-test executable avoids linking the same dependencies for every feature.
|
||||
//! Keep feature tests in their own modules; the standalone ui_snapshots.rs target remains available.
|
||||
|
||||
mod bake_mode;
|
||||
mod brush_drag;
|
||||
mod close_unsaved;
|
||||
mod color_picker;
|
||||
mod curvature_generator;
|
||||
mod effect_rows;
|
||||
mod effect_sliders;
|
||||
mod fill_channel_image;
|
||||
mod fill_projection_section;
|
||||
mod filter_picker;
|
||||
mod history_panel;
|
||||
mod layer_clipboard;
|
||||
mod layer_rename;
|
||||
mod path_list;
|
||||
mod pen_pressure;
|
||||
mod polygon_fill;
|
||||
mod properties_popup;
|
||||
mod shelf_drop;
|
||||
mod shelf_hover_preview;
|
||||
mod shift_lines_2d;
|
||||
mod skew_paint;
|
||||
mod split_divider;
|
||||
mod start_window;
|
||||
mod toolbar;
|
||||
Loaded 100 of 115 files, more files were not shown because too many files have changed in this diff.
Show more
Reference in new issue
Block a user