Auto: Integrate main and streamline History and Log panels

Name the scrollbars for assistive technology. Verify that resizing keeps the whole current History row visible and that a horizontally scrolled Log entry copies with its original line breaks.

Borrow visible History labels and reuse formatted Log text to reduce temporary allocations. Validate with the focused Linux suite and the WebAssembly checks.
This commit is contained in:
chasse20 committed 2026-11-29 20:18:13 +00:00
commit a020271842
218 files changed
+11627 -2234

No files matched your search

+21 -7
View File
@@ -103,7 +103,7 @@ pub fn specs() -> Vec<CommandSpec> {
"List export outputs",
[],
None,
"{preset?: name or preset object, ts?, format?, bitDepth?, dithering?, size?, colorSpace?, maps?} → [{ts, map, file, tile: UV tile number or null, udimPattern: file pattern with <UDIM> or null, format, bitDepth, dithering, size, sourceSize, warnings, layers: [{map, name}] (a PSD's maps, top first)}] (keeps the first file per case-insensitive name, warns about later duplicates, and rejects file and folder conflicts)",
"{preset?: name or preset object, ts?, format?, bitDepth?, dithering?, size?, colorSpace?, maps?} → [{ts, map, file, tile: UV tile number or null, udimPattern: file pattern with <UDIM> or null, format, bitDepth, dithering, size (width), height, sourceSize, sourceHeight, warnings, layers: [{map, name}] (a PSD's maps, top first)}] (keeps the first file per case-insensitive name, warns about later duplicates, and rejects file and folder conflicts)",
always,
plan
),
@@ -426,6 +426,7 @@ impl Session {
let files = self.with_export_input(
set_index,
&mesh_name,
options.padding != Padding::None,
|grid| Cow::Owned(grid.coverage_mask()),
|input| texturecraft_formats::export::render_planned_maps(input, options, plans).map_err(fe),
)?;
@@ -440,6 +441,7 @@ impl Session {
&self,
set_index: usize,
mesh_name: &str,
needs_padding: bool,
coverage: impl FnOnce(&UvGBuffer) -> Cow<'_, [Coverage]>,
with: impl FnOnce(&ExportInput<Coverage>) -> Result<T>,
) -> Result<T> {
@@ -447,6 +449,11 @@ impl Session {
let cache = self.caches.get(set_index).ok_or_else(missing)?;
let composite = self.document_composite(set_index, &cache.covered_tiles).ok_or_else(missing)?;
let coverage = coverage(&cache.gbuf);
let seams = if needs_padding {
self.doc.project.texture_sets.get(set_index).and_then(|set| crate::session::padding_seams(&self.mesh, set, &cache.gbuf))
} else {
None
};
let empty = Default::default();
let input = ExportInput {
project: &self.doc.project,
@@ -454,6 +461,7 @@ impl Session {
composite: &composite,
baked: self.doc.baked.get(&set_index).unwrap_or(&empty),
coverage: &coverage,
seams: seams.as_ref(),
mesh_name,
};
with(&input)
@@ -472,6 +480,7 @@ impl Session {
self.with_export_input(
set_index,
&mesh_name,
false,
|grid| Cow::Borrowed(&grid.tri),
|input| MapPreview::sample_triangles(input, &options, map, side).map_err(fe),
)
@@ -611,7 +620,7 @@ fn preview(session: &mut Session, params: &Value) -> Result<Value> {
}
fn plan(session: &mut Session, params: &Value) -> Result<Value> {
use texturecraft_formats::export::{list_set_outputs, scale_export_side};
use texturecraft_formats::export::{list_set_outputs, output_dimensions};
let options = export_options(session, params, "export.plan")?;
let project = &session.doc.project;
@@ -624,12 +633,15 @@ fn plan(session: &mut Session, params: &Value) -> Result<Value> {
let Some((set_index, _)) = set_outputs.first() else { continue };
let set = project.texture_set(*set_index).map_err(|error| EngineError::Other(error.to_string()))?;
let block_size = set.block_resolution();
for (_, output) in set_outputs {
let source_size = output.tile.map_or(set.resolution, |tile| set.tile_resolution(tile));
let source = output_dimensions(set, output.tile, None);
// A map's own size wins over the export's; a PSD is the size of its largest layer
let size = output.maps().map(|map| scale_export_side(source_size, block_size, options.map_size(map))).max().unwrap_or(source_size);
// A PSD's canvas takes the largest width and height of its exported layers
let (size, height) = output
.maps()
.map(|map| output_dimensions(set, output.tile, options.map_size(map)))
.reduce(|(width, height), (next_width, next_height)| (width.max(next_width), height.max(next_height)))
.unwrap_or(source);
files.push(json!({
"ts": set_index,
@@ -641,7 +653,9 @@ fn plan(session: &mut Session, params: &Value) -> Result<Value> {
"bitDepth": output.bit_depth,
"dithering": output.dither,
"size": size,
"sourceSize": source_size,
"height": height,
"sourceSize": source.0,
"sourceHeight": source.1,
"warnings": output.warnings,
"layers": output.layers.iter().map(|layer| json!({ "map": layer.map, "name": layer.name })).collect::<Vec<_>>(),
}));
+8 -1
View File
@@ -271,18 +271,25 @@ pub fn texture_set(session: &Session, index: usize) -> Value {
json!({
"index": index,
"name": texture_set.name,
"originalName": session.original_set_name(index),
"description": texture_set.description,
"resolution": texture_set.resolution,
"height": texture_set.height(),
"size": texture_set.size(),
"blockResolution": texture_set.block_resolution(),
"uvTiles": texture_set.uv_tiles,
"tiles": tiles,
"channels": texture_set.channels.iter().map(|(channel, format)| json!({ "channel": channel.id(), "format": format.label() })).collect::<Vec<_>>(),
"channels": texture_set.formats().iter().map(|(channel, format)| json!({ "channel": channel.id(), "format": format.label(), "shaded": channel.is_shaded() })).collect::<Vec<_>>(),
"layers": session.doc.project.walk(index).len(),
"parts": crate::set_cmds::parts(session, index),
"baked": crate::project_cmds::baked_json(session.doc.baked.get(&index)),
"outOfDate": out_of_date,
"autoRebake": texture_set.auto_rebake.map(texturecraft_core::BakedMap::id),
"visible": texture_set.visible,
"normalMixing": texture_set.normal_mixing.id(),
"aoMixing": texture_set.ao_mixing.id(),
"heightToNormal": texture_set.height_to_normal.id(),
"uvPadding": texture_set.uv_padding.id(),
"active": index == session.ts(),
})
}
+83 -4
View File
@@ -313,7 +313,8 @@ fn save_source(_: &mut Session, _: &Value) -> Result<Value> {
Err(EngineError::Other("file paths are not available in the browser".into()))
}
/// A MaterialCraft executable: `$<env>`, else next to this program, else `name` on `PATH`.
/// A MaterialCraft executable: `$<env>`, else next to this program, else in the sibling
/// `MaterialCraft` folder (the launcher's layout), else `name` on `PATH`.
#[cfg(not(target_arch = "wasm32"))]
pub fn materialcraft_tool(name: &str, env: &str) -> std::path::PathBuf {
if let Some(p) = std::env::var_os(env).filter(|p| !p.is_empty()) {
@@ -321,7 +322,18 @@ pub fn materialcraft_tool(name: &str, env: &str) -> std::path::PathBuf {
}
let exe = format!("{name}{}", std::env::consts::EXE_SUFFIX);
std::env::current_exe().ok().and_then(|e| Some(e.parent()?.join(&exe))).filter(|p| p.is_file()).unwrap_or_else(|| exe.into())
let app_dir = std::env::current_exe().ok().and_then(|e| e.parent().map(std::path::Path::to_path_buf));
app_dir.and_then(|d| find_installed_tool(&d, &exe)).unwrap_or_else(|| exe.into())
}
/// `exe` in `app_dir` (next to this program), else in the sibling `MaterialCraft` folder beside `app_dir`
/// (`<root>/TextureCraft` and `<root>/MaterialCraft`, as the ArtCraft Launcher installs them). `None` if neither has it.
/// Versioned `<app>/<version>/` layouts and macOS `.app` bundles are not searched.
#[cfg(not(target_arch = "wasm32"))]
fn find_installed_tool(app_dir: &std::path::Path, exe: &str) -> Option<std::path::PathBuf> {
let beside = app_dir.join(exe);
let sibling = app_dir.parent().map(|root| root.join("MaterialCraft").join(exe));
std::iter::once(beside).chain(sibling).find(|p| p.is_file())
}
/// A command for a MaterialCraft executable that opens no console window.
@@ -335,12 +347,15 @@ fn quiet(program: &std::path::Path) -> std::process::Command {
}
/// Open `package` (a published material or authoring package) in the MaterialCraft app (`$MATERIALCRAFT`, next to this
/// program, or on `PATH`).
/// program, in the sibling `MaterialCraft` folder, or on `PATH`).
#[cfg(not(target_arch = "wasm32"))]
pub fn open_in_materialcraft(package: &std::path::Path) -> Result<()> {
let app = materialcraft_tool("materialcraft", "MATERIALCRAFT");
quiet(&app).arg(package).spawn().map(drop).map_err(|e| {
EngineError::Other(format!("MaterialCraft ({}) did not start: {e}. Install MaterialCraft next to TextureCraft or set MATERIALCRAFT", app.display()))
EngineError::Other(format!(
"MaterialCraft ({}) did not start: {e}. Install MaterialCraft next to TextureCraft or in a sibling MaterialCraft folder, or set MATERIALCRAFT",
app.display()
))
})
}
@@ -775,6 +790,70 @@ mod tests {
assert!(typed(&p, &json!("#ff8000")).is_some());
}
#[cfg(not(target_arch = "wasm32"))]
fn touch(dir: &std::path::Path, exe: &str) -> std::path::PathBuf {
std::fs::create_dir_all(dir).unwrap();
let p = dir.join(exe);
std::fs::write(&p, b"").unwrap();
p
}
#[cfg(not(target_arch = "wasm32"))]
#[test]
fn launcher_layout_finds_the_sibling_materialcraft_folder() {
let root = tempfile::tempdir().unwrap();
let app = root.path().join("TextureCraft");
std::fs::create_dir_all(&app).unwrap();
let tool = touch(&root.path().join("MaterialCraft"), "materialcraft-cli");
assert_eq!(super::find_installed_tool(&app, "materialcraft-cli"), Some(tool));
}
#[cfg(not(target_arch = "wasm32"))]
#[test]
fn a_tool_beside_the_program_wins_over_the_sibling_folder() {
let root = tempfile::tempdir().unwrap();
let app = root.path().join("TextureCraft");
let beside = touch(&app, "materialcraft-cli");
touch(&root.path().join("MaterialCraft"), "materialcraft-cli");
assert_eq!(super::find_installed_tool(&app, "materialcraft-cli"), Some(beside));
}
#[cfg(not(target_arch = "wasm32"))]
#[test]
fn a_missing_tool_is_none_so_the_caller_falls_back_to_path() {
let root = tempfile::tempdir().unwrap();
let app = root.path().join("TextureCraft");
std::fs::create_dir_all(root.path().join("MaterialCraft")).unwrap();
assert_eq!(super::find_installed_tool(&app, "materialcraft-cli"), None);
}
#[cfg(not(target_arch = "wasm32"))]
#[test]
fn a_folder_named_like_the_tool_is_not_the_tool() {
let root = tempfile::tempdir().unwrap();
let app = root.path().join("TextureCraft");
std::fs::create_dir_all(app.join("materialcraft-cli")).unwrap();
std::fs::create_dir_all(root.path().join("MaterialCraft").join("materialcraft-cli")).unwrap();
assert_eq!(super::find_installed_tool(&app, "materialcraft-cli"), None);
}
#[cfg(not(target_arch = "wasm32"))]
#[test]
fn an_app_folder_with_no_parent_does_not_panic() {
// The root (or an empty path) has no parent: only the beside-the-program step can apply.
assert_eq!(super::find_installed_tool(std::path::Path::new(""), "no-such-materialcraft-tool"), None);
let root = std::env::temp_dir().ancestors().last().map(std::path::Path::to_path_buf).unwrap_or_default();
assert_eq!(super::find_installed_tool(&root, "no-such-materialcraft-tool"), None);
}
#[cfg(not(target_arch = "wasm32"))]
#[test]
fn a_missing_app_folder_is_none() {
let root = tempfile::tempdir().unwrap();
let gone = root.path().join("nowhere").join("TextureCraft");
assert_eq!(super::find_installed_tool(&gone, "materialcraft-cli"), None);
}
#[cfg(not(target_arch = "wasm32"))]
fn scratch(name: &str) -> std::path::PathBuf {
let dir = std::env::temp_dir().join(format!("tc_handoff_{name}_{}", std::process::id()));
+1 -1
View File
@@ -120,7 +120,7 @@ fn run_bounded(command: &std::process::Command, stdout: &Path, stderr: &Path, re
.stdout(std::fs::File::create(stdout).map_err(io)?)
.stderr(std::fs::File::create(stderr).map_err(io)?)
.spawn()
.map_err(|error| io(format!("could not start the MaterialCraft cook: {error}. Install MaterialCraft or set MATERIALCRAFT_CLI")))?;
.map_err(|error| io(format!("could not start the MaterialCraft cook: {error}. Install MaterialCraft next to TextureCraft or in a sibling MaterialCraft folder, or set MATERIALCRAFT_CLI")))?;
loop {
if canceled.load(Ordering::Relaxed) {
+9 -7
View File
@@ -42,20 +42,22 @@ impl Session {
let (width, height, values) = atlas;
let set = self.doc.project.texture_set(ts).map_err(|e| EngineError::Other(e.to_string()))?;
let Some(grid) = set.tile_grid().filter(|_| per_tile) else { return Ok(vec![MaskBitmap { tile: None, width, height, values }]) };
let block = set.block_resolution();
let (block_width, block_height) = set.block_size();
set.uv_tiles
.iter()
.map(|&tile| {
let (block_x, block_y) = grid.block(tile).ok_or_else(|| EngineError::Other(format!("UV tile {tile} is not in the set's grid")))?;
// A tile smaller than its block fills the block's top-left corner
let side = ((block as f32 * set.tile_scale(tile)).round() as u32).clamp(1, block);
let mut tile_values = Vec::with_capacity(side as usize * side as usize);
for row in 0..side {
let start = ((block_y * block + row) as usize) * width as usize + (block_x * block) as usize;
tile_values.extend_from_slice(values.get(start..start + side as usize).unwrap_or(&[]));
let scale = set.tile_scale(tile);
let tile_width = ((block_width as f32 * scale).round() as u32).clamp(1, block_width);
let tile_height = ((block_height as f32 * scale).round() as u32).clamp(1, block_height);
let mut tile_values = Vec::with_capacity(tile_width as usize * tile_height as usize);
for row in 0..tile_height {
let start = ((block_y * block_height + row) as usize) * width as usize + (block_x * block_width) as usize;
tile_values.extend_from_slice(values.get(start..start + tile_width as usize).unwrap_or(&[]));
}
Ok(MaskBitmap { tile: Some(tile), width: side, height: side, values: tile_values })
Ok(MaskBitmap { tile: Some(tile), width: tile_width, height: tile_height, values: tile_values })
})
.collect()
}
+16 -6
View File
@@ -7,7 +7,7 @@ use std::sync::Arc;
use serde_json::Value;
use texturecraft_compose::PixelStore;
use texturecraft_core::{LayerId, LayerKind, Project, Source, TextureSet};
use texturecraft_core::{EffectKind, Fill, LayerId, LayerKind, Project, Source, TextureSet};
use crate::commands::{CommandSpec, always, has_layer};
use crate::materials::Place;
@@ -36,7 +36,15 @@ fn fe(e: texturecraft_formats::FormatError) -> EngineError {
EngineError::Other(e.to_string())
}
/// Image resources a layer subtree uses (fill sources and their patterns, mask or content effects and the images its paths paint with)
/// The package and cooked maps of the MaterialCraft material linked to `fill`, if any
fn link_images(fill: &Fill, out: &mut Vec<String>) {
if let Some(link) = &fill.link {
out.push(link.package.clone());
out.extend(link.outputs.values().cloned());
}
}
/// Image resources a layer subtree uses (fill sources and their patterns, linked materials, mask or content effects and the images its paths paint with)
pub(crate) fn images_used(project: &Project, id: LayerId, out: &mut Vec<String>, depth: usize) {
if depth > texturecraft_core::project::MAX_DEPTH {
return;
@@ -46,15 +54,15 @@ pub(crate) fn images_used(project: &Project, id: LayerId, out: &mut Vec<String>,
if let LayerKind::Fill(fill) = &layer.kind {
out.extend(fill.sources.values().flat_map(Source::images).map(str::to_string));
if let Some(link) = &fill.link {
out.push(link.package.clone());
out.extend(link.outputs.values().cloned());
}
link_images(fill, out);
}
for effect in layer.mask.iter().flat_map(|mask| mask.effects.iter()).chain(&layer.content_effects) {
out.extend(effect.images_read().map(str::to_string));
out.extend(crate::path_tool::path_images(&effect.kind));
if let EffectKind::Material(fill) = &effect.kind {
link_images(fill, out);
}
}
for child in layer.children() {
@@ -66,9 +74,11 @@ pub(crate) fn images_used(project: &Project, id: LayerId, out: &mut Vec<String>,
pub(crate) fn one_set_document(src_set: &TextureSet, name: &str) -> Document {
let mut project = Project::new(name, "builtin:none");
let mut set = TextureSet::new(name, 0, src_set.resolution);
set.resolution_height = src_set.resolution_height;
set.uv_tiles = src_set.uv_tiles.clone();
set.tile_resolutions = src_set.tile_resolutions.clone();
set.channels = src_set.channels.clone();
set.format_precision = src_set.format_precision;
project.texture_sets.push(set);
Document {
+101 -31
View File
@@ -217,15 +217,17 @@ impl Session {
.collect()
}
/// Common setup of 3D and 2D strokes. `first_uv` is where the stroke starts on the mesh
/// (the Clone tool's destination anchor).
/// Common setup of 3D and 2D strokes, `first_uv` being where the stroke starts on the mesh (the Clone tool's destination anchor)
fn start_stroke(&mut self, viewport: Vec2, uv_mode: bool, first_uv: Option<Vec2>) -> Result<()> {
// Texture size a stroke paints at before the texture set has a cache
const FALLBACK_TEXTURE_SIZE: (u32, u32) = (1024, 1024);
self.refuse_while_baking()?;
let tool = self.tool.tool;
let erase = tool == Tool::Eraser;
let quick_mask = self.quick_mask.editing;
let ts = self.ts();
let size = self.caches.get(ts).map(|c| c.size).unwrap_or((1024, 1024));
let size = self.caches.get(ts).map_or(FALLBACK_TEXTURE_SIZE, |cache| cache.size);
let pickup = if quick_mask { None } else { self.pickup_mode(first_uv)? };
let composite_pickup = tool == Tool::Smudge || (tool == Tool::Clone && self.tool.clone_from == CloneFrom::Composite);
if pickup.is_some() && composite_pickup && !self.paints_mask() && self.solo.is_none() {
@@ -240,26 +242,30 @@ impl Session {
}
_ => None,
};
let before = self.doc.clone();
let target = if quick_mask {
None
} else {
match self.paint_target() {
Ok(t) => Some(t),
Err(e) => {
Ok(target) => Some(target),
Err(error) => {
self.doc = before;
return Err(e);
return Err(error);
}
}
};
let values = target.map(|t| self.stroke_values(t)).unwrap_or_default();
let values = target.map(|target| self.stroke_values(target)).unwrap_or_default();
// Clone and smudge on a mask read the mask as it was before the stroke
let mask_owner = match target {
Some(PaintTarget::Mask(effect)) if pickup.is_some() => self.doc.project.effect(effect).map(|(owner, _)| owner),
_ => None,
};
let stencil = if tool == Tool::Projection && !quick_mask { self.capture_stencil(viewport) } else { None };
// The 2D view doesn't show the stencil, so there it shapes only the Projection tool
let stencil = if !quick_mask && tool.uses_stencil() && (tool == Tool::Projection || !uv_mode) { self.capture_stencil(viewport) } else { None };
let problem = if !erase && values.is_empty() && matches!(target, Some(PaintTarget::Layer(_))) {
Some("no channel enabled to paint: enable channels in the tool's material")
} else if tool == Tool::Projection && !quick_mask && stencil.is_none() && !uv_mode {
@@ -267,9 +273,10 @@ impl Session {
} else {
None
};
if let Some(msg) = problem {
if let Some(message) = problem {
self.doc = before;
return Err(EngineError::Other(msg.into()));
return Err(EngineError::Other(message.into()));
}
let depth = (!uv_mode).then(|| self.eye_depth(viewport));
@@ -278,6 +285,7 @@ impl Session {
if !quick_mask {
canvas.limit = self.stroke_limit(ts, size);
}
if let Some((mode, offset)) = pickup
&& let Some(cache) = self.caches.get(ts)
{
@@ -285,7 +293,7 @@ impl Session {
PickupMode::Clone { .. } => {
PickupMode::Clone { offset: [(offset[0] * size.0 as f32).round() as i64, (offset[1] * size.1 as f32).round() as i64] }
}
m => m,
other_mode => other_mode,
};
let mut pickup = match (&layer_source, mask_owner) {
// On a mask the stroke reads the mask's own values
@@ -317,20 +325,23 @@ impl Session {
canvas.pickup = Some(pickup);
if tool == Tool::Clone
&& self.tool.clone_aligned
&& let Some(src) = self.tool.clone_source.as_mut()
&& let Some(clone_source) = self.tool.clone_source.as_mut()
{
src.offset.get_or_insert(offset);
clone_source.offset.get_or_insert(offset);
}
}
if canvas.pickup.is_none() && tool == Tool::Paint && matches!(target, Some(PaintTarget::Layer(_))) {
canvas.pickup = self.brush_pattern(&values);
}
let label = if quick_mask {
QUICK_MASK_STROKE_LABEL.to_string()
} else {
let on_mask = matches!(target, Some(PaintTarget::Mask(_)));
history_label(stroke_template(tool, on_mask), &self.stroke_layer_name())
};
self.stroke = Some(ActiveStroke {
ts,
target,
@@ -345,6 +356,7 @@ impl Session {
erase,
stencil,
before,
start_revision: self.revision,
label,
staging: Staging::default(),
});
@@ -394,13 +406,14 @@ impl Session {
}
}
/// The stencil placed for the current camera and viewport.
/// The stencil placed for the current camera and viewport
fn capture_stencil(&self, viewport: Vec2) -> Option<texturecraft_compose::Stencil> {
let st = self.tool.stencil.as_ref()?;
let image = self.images.get(&st.image)?.clone();
let stencil_state = self.tool.stencil.as_ref()?;
let image = self.images.get(&stencil_state.image)?.clone();
let aspect = viewport.x.max(1.0) / viewport.y.max(1.0);
let (center, half, rotation) = st.placement(image.width as f32 / image.height.max(1) as f32, aspect);
Some(texturecraft_compose::Stencil { image, view_proj: self.camera.view_proj(aspect), center, half, rotation, tile: st.tile })
let (center, half, rotation) = stencil_state.placement(image.width as f32 / image.height.max(1) as f32, aspect);
let colors = self.tool.tool == Tool::Projection;
Some(texturecraft_compose::Stencil { image, view_proj: self.camera.view_proj(aspect), center, half, rotation, tile: stencil_state.tile, colors })
}
/// Painting is paused while a bake preview shows the baked maps instead of the material.
@@ -558,6 +571,7 @@ impl Session {
/// Commit the active stroke as one undo step
pub fn end_stroke(&mut self) -> Result<()> {
let Some(mut stroke) = self.stroke.take() else { return Ok(()) };
let size = (stroke.canvas.alpha.width(), stroke.canvas.alpha.height());
if stroke.canvas.dirty.is_empty() {
// Nothing painted: drop any mask effect the stroke created
@@ -566,8 +580,15 @@ impl Session {
}
let gbuf = self.caches.get(stroke.ts).map(|c| c.gbuf.clone());
if stroke.stencil.is_some() && !with_commit_source(&stroke, gbuf.as_deref(), &self.mesh, &stroke.canvas.dirty, stencil_allows_stroke) {
self.mark_painted(stroke.ts, stroke.target, stroke.canvas.dirty.iter().copied());
self.discard_unused_stroke_mask(&stroke);
return Ok(());
}
let mesh = self.mesh.clone();
let mut staging = std::mem::take(&mut stroke.staging);
match stroke.target {
Some(PaintTarget::Layer(id)) => {
let pixels = &mut self.doc.pixels;
@@ -586,7 +607,8 @@ impl Session {
return Ok(());
}
}
self.add_step(stroke.label.clone(), stroke.before);
self.add_step(stroke.label, stroke.before);
self.redo.clear();
self.mark_modified();
@@ -595,6 +617,32 @@ impl Session {
Ok(())
}
fn discard_unused_stroke_mask(&mut self, stroke: &ActiveStroke) {
// An intervening edit may already have recorded the mask effect
if self.revision != stroke.start_revision {
return;
}
self.doc.project.next_id = stroke.before.project.next_id;
if let Some(PaintTarget::Mask(effect)) = stroke.target
&& let Some((owner, _)) = self.doc.project.effect(effect)
&& let Some(previous_layer) = stroke.before.project.layers.get(&owner)
&& !previous_layer.mask.iter().flat_map(|mask| &mask.effects).any(|previous| previous.id == effect)
&& let Some(layer) = self.doc.project.layers.get_mut(&owner)
{
layer.mask = previous_layer.mask.clone();
// Removing a new mask background can change texels outside the dabs
if previous_layer.mask.is_none() {
for texture_set in self.doc.project.sets_drawing(owner) {
if let Some(cache) = self.caches.get_mut(texture_set) {
cache.invalidate_all();
}
}
}
}
}
/// Abandon the active stroke (Esc).
pub fn cancel_stroke(&mut self) {
if let Some(st) = self.stroke.take() {
@@ -735,22 +783,44 @@ impl Session {
}
}
/// Run `f` with stroke `st` as a commit source over `tiles` (the Projection tool's stencil
/// colors and alpha come from the surface under each texel).
/// Check that some rasterized paint survives the stencil before writing tiles or history.
fn stencil_allows_stroke(source: CommitSource) -> bool {
use texturecraft_texel::{TILE, from_u16};
let Some(sample_stencil) = source.per_texel else { return true };
let opacity = source.opacity.clamp(0.0, 1.0);
source.tiles.iter().any(|&(tile_x, tile_y)| {
source.alpha.tile(tile_x, tile_y).is_some_and(|alpha| {
alpha.iter().enumerate().any(|(index, &coverage)| {
let weight = from_u16(coverage) * opacity;
if weight <= 0.0 {
return false;
}
let x = tile_x * TILE + index as u32 % TILE;
let y = tile_y * TILE + index as u32 / TILE;
sample_stencil(x, y).is_some_and(|(_, factor)| weight * factor > 0.0)
})
})
})
}
/// Run `f` with `stroke` as a commit source over `tiles` (the stencil's alpha and, on the Projection tool, its colors come from the surface under each texel)
fn with_commit_source<R>(
st: &ActiveStroke,
gbuf: Option<&texturecraft_geom::UvGBuffer>,
stroke: &ActiveStroke,
gbuffer: Option<&texturecraft_geom::UvGBuffer>,
mesh: &texturecraft_geom::Mesh,
tiles: &BTreeSet<(u32, u32)>,
f: impl FnOnce(CommitSource) -> R,
) -> R {
let stencil_fn = |x: u32, y: u32| -> Option<([f32; 3], f32)> {
let g = gbuf?;
let p = g.surface(mesh, (y * g.width + x) as usize)?.pos;
st.stencil.as_ref()?.sample_world(p)
let stencil_fn = |x: u32, y: u32| -> Option<(Option<[f32; 3]>, f32)> {
let gbuffer = gbuffer?;
let position = gbuffer.surface(mesh, (y * gbuffer.width + x) as usize)?.pos;
stroke.stencil.as_ref()?.paint_world(position)
};
let per_texel: Option<texturecraft_paint::TexelFn> = if st.stencil.is_some() { Some(&stencil_fn) } else { None };
let carried = st.canvas.pickup.as_ref().map(|p| &p.values);
let carried_mask = st.canvas.pickup.as_ref().and_then(|p| p.mask_values());
f(CommitSource { alpha: &st.canvas.alpha, tiles, opacity: st.stroke.settings.opacity, erase: st.erase, per_texel, carried, carried_mask })
let per_texel: Option<texturecraft_paint::TexelFn> = if stroke.stencil.is_some() { Some(&stencil_fn) } else { None };
let carried = stroke.canvas.pickup.as_ref().map(|pickup| &pickup.values);
let carried_mask = stroke.canvas.pickup.as_ref().and_then(|pickup| pickup.mask_values());
f(CommitSource { alpha: &stroke.canvas.alpha, tiles, opacity: stroke.stroke.settings.opacity, erase: stroke.erase, per_texel, carried, carried_mask })
}
+58 -20
View File
@@ -1007,36 +1007,51 @@ impl Session {
}
_ => 0,
};
// Each path goes through the regular stroke and fill code with its own settings; their
// own history entries are dropped (the caller records one step).
let mut out = vec![Value::Null; start];
let result = self.while_painting_paths(eid, |s| {
let mut result = Ok(());
for i in start..=shapes.len() {
if i == from.min(shapes.len()) && i > start {
let pixels = &s.doc.pixels;
let layers = pixels.layers.iter().filter(|((id, _), _)| *id == eid).map(|(k, v)| (*k, v.clone())).collect();
s.path_cache = Some(PathCache { eid, key, below: shapes[..i].to_vec(), mask: pixels.masks.get(&eid).cloned(), layers });
}
let Some(sh) = shapes.get(i) else { break };
match s.paint_shape(sh) {
Ok(v) => out.push(v),
Err(e) => {
result = Err(e);
break;
}
}
}
result
});
result.map(|_| out)
}
// Regular stroke and fill code paints each path with its own settings
// Discard its history entries because the caller records one undo step
/// Run `f` with the session switched into path-painting state (path tool on sublayer `eid`,
/// empty history), then put the tool, camera, target, quick-mask flag and the undo/redo
/// stacks back. A panic in `f` restores them too before it continues unwinding: the
/// automation servers catch panics and keep serving this session, and must not find its
/// history gone.
fn while_painting_paths<T>(&mut self, eid: LayerId, f: impl FnOnce(&mut Session) -> T) -> T {
let saved = (self.tool.clone(), self.camera, self.target, self.quick_mask.editing);
let history = (std::mem::take(&mut self.undo), std::mem::take(&mut self.redo));
self.target = StackTarget::Effect(eid);
self.quick_mask.editing = false;
self.tool.tool = Tool::Path;
self.painting_paths = true;
let mut out = vec![Value::Null; start];
let mut result = Ok(());
for i in start..=shapes.len() {
if i == from.min(shapes.len()) && i > start {
let pixels = &self.doc.pixels;
let layers = pixels.layers.iter().filter(|((id, _), _)| *id == eid).map(|(k, v)| (*k, v.clone())).collect();
self.path_cache = Some(PathCache { eid, key, below: shapes[..i].to_vec(), mask: pixels.masks.get(&eid).cloned(), layers });
}
let Some(sh) = shapes.get(i) else { break };
match self.paint_shape(sh) {
Ok(v) => out.push(v),
Err(e) => {
result = Err(e);
break;
}
}
}
let ran = std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| f(self)));
self.painting_paths = false;
(self.tool, self.camera, self.target, self.quick_mask.editing) = saved;
(self.undo, self.redo) = history;
result.map(|_| out)
match ran {
Ok(v) => v,
Err(panic) => std::panic::resume_unwind(panic),
}
}
fn paint_shape(&mut self, shape: &PathShape) -> Result<Value> {
@@ -1417,4 +1432,27 @@ mod tests {
assert!(!off_mesh.is_empty());
assert!(off_mesh.iter().flatten().all(Option::is_none));
}
#[test]
fn a_panic_while_painting_paths_restores_history_and_tool_state() {
let mut s = Session::new_project("t", texturecraft_geom::primitives::sphere(1.0, 24, 12), "builtin:test", None, 128).unwrap();
s.update();
execute(&mut s, "tool.brush", &json!({"size": 6})).unwrap();
let r = execute(&mut s, "tool.path", &json!({"uvPoints": [[0.1, 0.2], [0.9, 0.25]], "commit": true})).unwrap();
let eid = texturecraft_core::LayerId(r["committed"]["effect"].as_u64().unwrap());
assert!(!s.history_labels().is_empty());
let labels = s.history_labels();
let (target, tool) = (s.target, s.tool.tool);
let panicked = std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| {
s.while_painting_paths(eid, |s| {
s.edit("nested", |_| Ok(())).unwrap();
panic!("paint failed");
})
}));
assert!(panicked.is_err());
assert_eq!(s.history_labels(), labels);
assert_eq!((s.target, s.tool.tool), (target, tool));
assert!(!s.painting_paths);
}
}
+3
View File
@@ -472,6 +472,7 @@ mod tests {
assert!(warnings.is_empty(), "{warnings:?}");
assert_eq!(run(&mut s, "export.preset.get", json!({"name": name.to_ascii_lowercase()})).unwrap(), custom);
let plan = run(&mut s, "export.plan", json!({"preset": name, "ts": 0})).unwrap();
assert_eq!(plan.as_array().unwrap().len(), 1);
assert!(plan[0]["file"].as_str().unwrap().ends_with("_R.png"));
@@ -481,9 +482,11 @@ mod tests {
let builtin = format!("builtin:{name}");
assert!(names.iter().any(|entry| entry["name"] == builtin && entry["builtin"] == true));
let builtin_plan = run(&mut s, "export.plan", json!({"preset": builtin, "ts": 0})).unwrap();
assert!(builtin_plan.as_array().unwrap().len() > 1);
run(&mut s, "export.preset.save", json!({"preset": custom})).unwrap();
run(&mut s, "export.preset.remove", json!({"name": name})).unwrap();
assert_eq!(run(&mut s, "export.preset.get", json!({"name": name})).unwrap()["maps"].as_array().unwrap().len(), 4);
}
+37 -1
View File
@@ -1,4 +1,4 @@
//! Project-level commands: new project, sample project, smart materials, inspection.
//! Project-level commands: new project, rename, sample project, smart materials, inspection.
use serde_json::{Value, json};
use texturecraft_compose::BakedMaps;
@@ -9,6 +9,9 @@ use crate::commands::{CommandSpec, always, bad, boolp, strp, u64p};
use crate::materials::Place;
use crate::{Result, Session, cmd};
/// Longest project name, in characters; it goes into export file names.
pub const MAX_PROJECT_NAME_CHARS: usize = 128;
pub fn specs() -> Vec<CommandSpec> {
vec![
cmd!(
@@ -22,6 +25,15 @@ pub fn specs() -> Vec<CommandSpec> {
),
cmd!("project.sample", "Open sample project", ["File"], None, "{}", always, sample),
cmd!("project.inspect", "Inspect project", [], None, "{}", always, |s, _| Ok(crate::inspect::session(s))),
cmd!(
"project.rename",
"Rename project",
[],
None,
"{name: 1-128 characters without control characters} — the name `$project` stands for in export file names; the project file keeps its own name",
always,
rename
),
cmd!(
"material.apply",
"Add smart material",
@@ -51,6 +63,30 @@ fn new(s: &mut Session, p: &Value) -> Result<Value> {
Ok(crate::inspect::session(s))
}
/// Trim and validate a proposed name without changing the project.
pub fn validate_project_name(name: &str) -> Result<&str> {
let name = name.trim();
if name.is_empty() || name.chars().nth(MAX_PROJECT_NAME_CHARS).is_some() || name.chars().any(char::is_control) {
return Err(bad("project.rename", format!("`name` must be 1-{MAX_PROJECT_NAME_CHARS} characters without control characters")));
}
Ok(name)
}
fn rename(session: &mut Session, params: &Value) -> Result<Value> {
let name = validate_project_name(strp(params, "name").unwrap_or_default())?;
// The same name is not an undo step and leaves a saved project unmodified
if name != session.doc.project.name {
session.edit("Rename project", |session| {
session.doc.project.name = name.to_owned();
Ok(())
})?;
}
Ok(json!({ "name": name }))
}
fn material(s: &mut Session, p: &Value) -> Result<Value> {
let id = strp(p, "material").ok_or_else(|| bad("material.apply", "`material` is required"))?;
let l = crate::materials::apply_at(s, id, Place::from_params(p))?;
+16 -7
View File
@@ -341,6 +341,7 @@ fn rename(s: &mut Session, p: &Value) -> Result<Value> {
if to == name {
return Ok(json!({ "name": name }));
}
if s.doc.resources.contains_key(&to) || crate::fill_alpha::library_alpha_of(&to).is_some() {
return Err(bad(command, format!("a resource named `{to}` exists already")));
}
@@ -348,6 +349,7 @@ fn rename(s: &mut Session, p: &Value) -> Result<Value> {
s.edit("Rename resource", |s| {
let bytes = s.doc.resources.remove(&name).ok_or_else(|| bad(command, format!("no resource `{name}`")))?;
s.doc.resources.insert(to.clone(), bytes);
// The Resources Updater keeps following the file the image came from
if let Some(source) = s.doc.project.resource_sources.remove(&name) {
s.doc.project.resource_sources.insert(to.clone(), source);
@@ -428,17 +430,23 @@ fn images_in_use(s: &Session) -> Vec<String> {
}
/// Drop resources unused by layers, mesh maps, paint tools or the environment (one undo step)
fn remove_unused(s: &mut Session, _: &Value) -> Result<Value> {
let used = images_in_use(s);
let unused: Vec<String> = s.doc.resources.keys().filter(|k| !used.contains(k)).cloned().collect();
fn remove_unused(session: &mut Session, _: &Value) -> Result<Value> {
let mut used = images_in_use(session);
used.sort_unstable();
let unused: Vec<_> = session.doc.resources.keys().filter(|name| used.binary_search(name).is_err()).cloned().collect();
if !unused.is_empty() {
s.edit("Remove unused resources", |s| {
s.doc.resources.retain(|k, _| !unused.contains(k));
s.doc.project.resource_sources.retain(|k, _| !unused.contains(k));
session.edit("Remove unused resources", |session| {
for name in &unused {
session.doc.resources.remove(name);
session.doc.project.resource_sources.remove(name);
}
Ok(())
})?;
s.sync_images();
session.sync_images();
}
Ok(json!({ "removed": unused }))
}
@@ -538,6 +546,7 @@ mod tests {
let renamed = crate::execute(&mut session, "resource.rename", &json!({"name": name, "to": "stone"})).unwrap()["name"].as_str().unwrap().to_string();
std::fs::write(&path, texturecraft_formats::gray16_png(1, 1, [0.75].into_iter()).unwrap()).unwrap();
// An equal-size file counts as changed once its time moved, as a later save's does
let later = std::time::SystemTime::now() + std::time::Duration::from_secs(10);
std::fs::File::options().write(true).open(&path).unwrap().set_modified(later).unwrap();
+131 -37
View File
@@ -5,13 +5,13 @@ use std::sync::Arc;
use serde::{Deserialize, Serialize};
use texturecraft_compose::{
BakedMaps, BelowCache, Composite, PaintTarget, PixelStore, StackKey, StrokePreview, covered_tiles, pad_tiles, stack_reads_neighbours,
BakedMaps, BelowCache, Composite, PaddingMaps, PaintTarget, PixelStore, SeamPaddingInput, StackKey, StrokePreview, covered_tiles, pad_tiles,
stack_reads_neighbours,
};
use texturecraft_core::{Channel, Layer, LayerId, LayerKind, Project, TextureSet};
use texturecraft_core::{Channel, ChannelFormat, Layer, LayerId, LayerKind, Project, TextureSet, UvPaddingMode};
use texturecraft_geom::glam::Vec2;
use texturecraft_geom::{Bvh, Mesh, OrbitCamera, UvGBuffer};
use texturecraft_paint::{BrushSettings, EyeDepth, Stroke, StrokeCanvas};
use texturecraft_texel::DilationMap;
use crate::fill_mode::FillMode;
pub use crate::stencil_look::StencilLook;
@@ -43,7 +43,11 @@ pub struct SetCache {
/// Texels across and down (`TextureSet::size`).
pub size: (u32, u32),
pub gbuf: Arc<UvGBuffer>,
pub dilation: Arc<DilationMap>,
/// The set's UV padding mode and the display padding it gives
pub uv_padding: UvPaddingMode,
pub padding: Arc<PaddingMaps>,
/// The channels' storage formats the composite was made with
pub formats: Vec<(Channel, ChannelFormat)>,
pub covered_tiles: Arc<Vec<(u32, u32)>>,
pub composite: Composite,
/// Tiles to recomposite.
@@ -65,15 +69,15 @@ impl SetCache {
pub(crate) fn new(mesh: &Mesh, ts: &TextureSet) -> SetCache {
let (w, h) = ts.size();
let gbuf = UvGBuffer::new(mesh, ts.material, w, h);
// Padding stays inside each UV tile
let dilation = DilationMap::in_blocks(&gbuf.coverage_mask(), w, h, Some(DISPLAY_PADDING), ts.block_resolution());
let padding = display_padding(mesh, ts, &gbuf);
let covered = covered_tiles(&gbuf);
let all: BTreeSet<(u32, u32)> = texturecraft_compose::all_tiles(w, h).into_iter().collect();
SetCache {
size: (w, h),
gbuf: Arc::new(gbuf),
dilation: Arc::new(dilation),
uv_padding: ts.uv_padding,
padding: Arc::new(padding),
formats: ts.formats(),
covered_tiles: Arc::new(covered),
composite: Composite { block_scales: ts.block_scales(), ..Composite::with_size(&ts.channel_list(), w, h) },
dirty: all.clone(),
@@ -85,11 +89,44 @@ impl SetCache {
}
}
fn has_channels(&self, set: &TextureSet) -> bool {
if self.composite.channels.len() != set.channels.len() {
return false;
}
if self.composite.channels.keys().copied().eq(set.channels.iter().map(|&(channel, _)| channel)) {
return true;
}
// Saved sets can list their channels in a different order from the composite
let mut present = [false; Channel::ALL.len()];
for &(channel, _) in &set.channels {
present[channel.index()] = true;
}
self.composite.channels.keys().all(|channel| present[channel.index()])
}
pub fn invalidate_all(&mut self) {
self.dirty.extend(self.covered_tiles.iter().copied());
}
}
/// The geometry needed to continue UV padding across the seams of this set
pub(crate) fn padding_seams<'a>(mesh: &'a Mesh, set: &TextureSet, grid: &'a UvGBuffer) -> Option<SeamPaddingInput<'a>> {
if set.uv_padding == UvPaddingMode::Space2d {
return None;
}
SeamPaddingInput::of_material(mesh, set.material, &grid.tri)
}
/// The viewport's padding of `set`, which stays inside each UV tile
fn display_padding(mesh: &Mesh, set: &TextureSet, grid: &UvGBuffer) -> PaddingMaps {
let seams = padding_seams(mesh, set, grid);
PaddingMaps::new(set.uv_padding, &grid.coverage_mask(), (grid.width, grid.height), Some(DISPLAY_PADDING), set.block_size(), seams.as_ref())
}
/// Active tool.
#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize, Default)]
pub enum Tool {
@@ -110,6 +147,12 @@ pub enum Tool {
impl Tool {
pub const ALL: [Tool; 9] =
[Tool::Paint, Tool::Eraser, Tool::Projection, Tool::PolygonFill, Tool::Smudge, Tool::Clone, Tool::ColorPicker, Tool::Path, Tool::GeometryMask];
/// The brush tools whose strokes the stencil shapes
pub fn uses_stencil(self) -> bool {
matches!(self, Tool::Paint | Tool::Eraser | Tool::Projection | Tool::Smudge | Tool::Clone)
}
pub fn label(self) -> &'static str {
match self {
Tool::Paint => "Paint",
@@ -181,7 +224,7 @@ impl ViewMode {
}
}
/// A screen-pinned image for the Projection tool (a stencil).
/// A screen-pinned image the brush tools paint through (a stencil)
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub struct StencilState {
/// Image resource name.
@@ -252,7 +295,7 @@ pub struct ToolState {
/// 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.
/// Stencil the brush tools paint through (the Projection tool paints its colors)
#[serde(default)]
pub stencil: Option<StencilState>,
/// Placement the next stencil starts with: the last stencil's, kept when the stencil is
@@ -364,10 +407,12 @@ pub(crate) struct ActiveStroke {
/// What a mask stroke paints, resolved once so staging, preview and commit read one image
pub mask_gray: texturecraft_compose::MaskGray,
pub erase: bool,
/// Projection tool: the stencil captured with the stroke's camera.
/// The stencil captured with the stroke's camera.
pub stencil: Option<texturecraft_compose::Stencil>,
/// History snapshot taken when the stroke began.
pub before: Document,
/// Document revision before any edits made during the stroke.
pub start_revision: u64,
pub label: String,
/// The commit's destination tiles, copied as the stroke reaches them.
pub staging: texturecraft_paint::Staging,
@@ -441,7 +486,7 @@ pub struct Session {
pub(crate) undo: Vec<(String, Document)>,
pub(crate) redo: Vec<(String, Document)>,
/// New undo steps so far: it moves even when a full history keeps its length
pub(crate) steps_added: u64,
steps_added: u64,
/// Set by [`crate::execute`] from a command's `merge` param: its edits continue the previous
/// undo step with the same label (a slider drag is one step however many values it applies).
pub(crate) merge_edits: bool,
@@ -703,7 +748,8 @@ impl Session {
// -----------------------------------------------------------------------------------------
// History
/// Run an undoable edit. On error the document is left untouched.
/// Run an undoable edit. On error, or if `f` panics, the document is left untouched (other
/// session state, such as the selection, is not restored).
pub fn edit<T>(&mut self, label: &str, f: impl FnOnce(&mut Session) -> Result<T>) -> Result<T> {
self.edit_merging(label, self.merge_edits, f)
}
@@ -719,7 +765,18 @@ impl Session {
self.end_polygon_fill_box();
let before = self.doc.clone();
let result = change(self).and_then(|(value, changed)| {
// A panic inside `change` must not leave a half-edited document behind: the automation
// servers catch panics and keep serving this session. (On wasm a panic aborts, so
// there is nothing to restore.)
let ran = std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| change(self)));
let result = match ran {
Ok(result) => result,
Err(panic) => {
self.restore_after_failed_edit(before);
std::panic::resume_unwind(panic);
}
};
let result = result.and_then(|(value, changed)| {
if changed && let Some(id) = self.doc.project.instance_cycle() {
return Err(EngineError::Other(format!("instance layer {} would draw itself", id.0)));
}
@@ -735,15 +792,21 @@ impl Session {
Ok(value)
}
Err(error) => {
self.doc = before;
// A failed repaint may have cached tiles from the discarded document
self.path_cache = None;
self.restore_after_failed_edit(before);
Err(error)
}
}
}
/// Put `before` back after an edit failed or panicked. The edit may have recomposited the
/// discarded document (draining the dirty tiles) or cached path tiles from it, so mark what
/// differs between the two dirty again, as undo does.
fn restore_after_failed_edit(&mut self, before: Document) {
let discarded = std::mem::replace(&mut self.doc, before);
self.path_cache = None;
self.invalidate_changed(&discarded);
}
pub(crate) fn push_history(&mut self, label: &str, before: Document) {
self.record(label, before, false);
}
@@ -860,6 +923,12 @@ impl Session {
)
};
for (texture_set_index, cache) in self.caches.iter_mut().enumerate() {
// Display-only settings change the uploaded textures, not the composite
let ao_mixing = |document: &Document| document.project.texture_sets.get(texture_set_index).map(|set| set.ao_mixing);
if ao_mixing(previous_document) != ao_mixing(&self.doc) {
cache.upload.extend(texturecraft_compose::all_tiles(cache.size.0, cache.size.1));
}
if uses_added_resource(texture_set_index) {
cache.invalidate_all();
continue;
@@ -935,22 +1004,33 @@ impl Session {
/// Make caches agree with the project's texture sets (resolution or channel changes).
pub fn sync_caches(&mut self) {
let sets = self.doc.project.texture_sets.clone();
let sets = &self.doc.project.texture_sets;
self.caches.truncate(sets.len());
for (i, ts) in sets.iter().enumerate() {
match self.caches.get_mut(i) {
Some(c) if c.size == ts.size() => {
let (want, scales) = (ts.channel_list(), ts.block_scales());
if c.composite.channels.keys().copied().collect::<Vec<_>>() != want || c.composite.block_scales != scales {
c.composite = Composite { block_scales: scales, ..Composite::with_size(&want, c.size.0, c.size.1) };
c.upload.extend(texturecraft_compose::all_tiles(c.size.0, c.size.1));
c.invalidate_all();
for (index, set) in sets.iter().enumerate() {
match self.caches.get_mut(index) {
Some(cache) if cache.size == set.size() => {
if cache.uv_padding != set.uv_padding {
cache.uv_padding = set.uv_padding;
cache.padding = Arc::new(display_padding(&self.mesh, set, &cache.gbuf));
cache.invalidate_all();
}
if !cache.formats.iter().copied().eq(set.iter_formats()) {
cache.formats = set.formats();
cache.invalidate_all();
}
let scales = set.block_scales();
if !cache.has_channels(set) || cache.composite.block_scales != scales {
cache.composite = Composite { block_scales: scales, ..Composite::with_size(&set.channel_list(), cache.size.0, cache.size.1) };
cache.upload.extend(texturecraft_compose::all_tiles(cache.size.0, cache.size.1));
cache.invalidate_all();
}
}
_ => {
let cache = SetCache::new(&self.mesh, ts);
if i < self.caches.len() {
self.caches[i] = cache;
let cache = SetCache::new(&self.mesh, set);
if index < self.caches.len() {
self.caches[index] = cache;
} else {
self.caches.push(cache);
}
@@ -987,7 +1067,12 @@ impl Session {
/// The undone steps, the next one to redo first.
pub fn redo_labels(&self) -> Vec<String> {
self.redo.iter().rev().map(|(l, _)| l.clone()).collect()
self.iter_redo_labels().map(str::to_owned).collect()
}
/// Borrow undone step labels, with the next step to redo first
pub fn iter_redo_labels(&self) -> impl ExactSizeIterator<Item = &str> {
self.redo.iter().rev().map(|(label, _)| label.as_str())
}
/// Changes with every new undo step, not when a merged edit continues one
@@ -997,7 +1082,12 @@ impl Session {
/// The done steps, the oldest first
pub fn history_labels(&self) -> Vec<String> {
self.undo.iter().map(|(l, _)| l.clone()).collect()
self.iter_history_labels().map(str::to_owned).collect()
}
/// Borrow the labels of completed steps, oldest first
pub fn iter_history_labels(&self) -> impl ExactSizeIterator<Item = &str> {
self.undo.iter().map(|(label, _)| label.as_str())
}
/// Undo a point edit, cancel an uncommitted path, or restore a document snapshot, in that order
@@ -1061,13 +1151,17 @@ impl Session {
self.invalidate_changed(other);
// An undone add or duplicate takes the selected effect away
if let StackTarget::Effect(e) = self.target
&& self.doc.project.effect(e).is_none()
if let StackTarget::Effect(effect_id) = self.target
&& self.doc.project.effect(effect_id).is_none()
{
let p = &other.project;
let content = p.effect(e).and_then(|(owner, _)| p.layers.get(&owner)).is_some_and(|l| l.content_effects.iter().any(|x| x.id == e));
let previous_project = &other.project;
let content = previous_project
.effect(effect_id)
.and_then(|(owner, _)| previous_project.layers.get(&owner))
.is_some_and(|layer| layer.content_effects.iter().any(|effect| effect.id == effect_id));
self.target = if content { StackTarget::Content } else { StackTarget::Mask };
}
let has_mask = self.selected_layer().and_then(|lid| self.doc.project.layer(self.doc.project.mask_owner(lid)).ok()).is_some_and(|l| l.mask.is_some());
if self.target == StackTarget::Mask && !has_mask {
self.target = StackTarget::Content;
@@ -1202,7 +1296,7 @@ impl Session {
);
// The composited tiles and the neighbours their padding reached change
let padded = pad_tiles(&mut cache.composite, &cache.dilation, &tiles);
let padded = pad_tiles(&mut cache.composite, &cache.padding, &tiles);
cache.upload.extend(tiles.iter().copied().chain(padded));
cache.revision = cache.revision.wrapping_add(1);
changed = true;
+485 -50
View File
@@ -1,7 +1,7 @@
//! Texture set commands (Texture Set List / Texture Set Settings).
use serde_json::{Value, json};
use texturecraft_core::{Channel, ChannelBlend, ChannelFormat};
use texturecraft_core::{AoMixing, Channel, ChannelBlend, ChannelFormat, HeightToNormalMethod, NormalMixing, UvPaddingMode};
use std::sync::Arc;
@@ -20,13 +20,23 @@ pub fn specs() -> Vec<CommandSpec> {
"Inspect texture set",
[],
None,
"{ts?} → {index, name, resolution, size: [w, h], uvTiles: [UDIM numbers] (empty: no UV tiles), tiles: [{udim, block: [x, y]}], channels, layers, baked, visible, active}",
"{ts?} → {index, name, originalName, description, resolution, height, size: [w, h], blockResolution, uvTiles: [UDIM numbers] (empty: no UV tiles), tiles: [{udim, block: [x, y], resolution, bakeEnabled}], channels: [{channel, format, shaded}], layers, parts, baked, visible, normalMixing, aoMixing, heightToNormal, uvPadding, active}",
always,
|s, p| Ok(crate::inspect::texture_set(s, ts_param(s, p, "textureSet.inspect")?))
),
cmd!("textureSet.resolution", "Texture set size", [], None, "{ts?, resolution: 128..8192 (power of two)}", always, resolution),
cmd!(
"textureSet.resolution",
"Texture set size",
[],
None,
"{ts?, resolution: 128..8192 (power of two, texels across), height?: 128..8192 (texels down; default = resolution, a square set)}",
always,
resolution
),
cmd!("textureSet.channel.add", "Add channel", [], None, "{ts?, channel}", always, |s, p| channel(s, p, true)),
cmd!("textureSet.channel.remove", "Remove channel", [], None, "{ts?, channel}", always, |s, p| channel(s, p, false)),
cmd!("textureSet.channels", "Add or remove channels", [], None, "{ts?, add?: [channel], remove?: [channel], allSets?}", always, channels),
cmd!("textureSet.channel.format", "Set channel format", [], None, "{ts?, channel, format}", always, channel_format),
cmd!("textureSet.visible", "Toggle texture set visibility", [], None, "{ts?, visible?}", always, visible),
cmd!(
"textureSet.visibility",
@@ -37,8 +47,24 @@ pub fn specs() -> Vec<CommandSpec> {
always,
visibility
),
cmd!("textureSet.rename", "Rename texture set", [], None, "{ts?, name}", always, rename),
cmd!("textureSet.settings", "Texture set settings", [], None, "{ts?, description?, heightStrength?, normalFormat?: openGl|directX}", always, settings),
cmd!(
"textureSet.rename",
"Rename texture set",
[],
None,
"{ts?, name} or {ts?, reset: true} (back to the mesh material's name, `originalName` in inspect)",
always,
rename
),
cmd!(
"textureSet.settings",
"Texture set settings",
[],
None,
"{ts?, description?, heightStrength?, normalMixing?: combine|replace, aoMixing?: multiply|none, heightToNormal?: sharp|smooth, uvPadding?: 3d|2d, normalFormat?: openGl|directX}",
always,
settings
),
cmd!(
"textureSet.parts",
"List mesh parts",
@@ -67,18 +93,21 @@ pub fn parts(s: &Session, ts: usize) -> Vec<String> {
}
pub(crate) fn ts_param(s: &Session, p: &Value, cmd: &str) -> Result<usize> {
match u64p(p, "ts") {
Some(t) if (t as usize) < s.set_count() => Ok(t as usize),
Some(t) => Err(bad(cmd, format!("no texture set {t}"))),
None => Ok(s.ts()),
if p.get("ts").is_none_or(Value::is_null) {
return Ok(s.ts());
}
let index = u64p(p, "ts").ok_or_else(|| bad(cmd, "valid `ts` index required"))?;
usize::try_from(index).ok().filter(|&index| index < s.set_count()).ok_or_else(|| bad(cmd, format!("no texture set {index}")))
}
fn select(s: &mut Session, p: &Value) -> Result<Value> {
let ts = u64p(p, "ts")
.map(|index| index as usize)
.filter(|index| *index < s.set_count())
.ok_or_else(|| bad("textureSet.select", "valid `ts` index required"))?;
let cmd = "textureSet.select";
if p.get("ts").is_none_or(Value::is_null) {
return Err(bad(cmd, "valid `ts` index required"));
}
let ts = ts_param(s, p, cmd)?;
select_set(s, ts)?;
Ok(json!({ "ts": ts }))
}
@@ -103,8 +132,12 @@ pub(crate) fn select_set(s: &mut Session, ts: usize) -> Result<()> {
fn resolution(s: &mut Session, p: &Value) -> Result<Value> {
let ts = ts_param(s, p, "textureSet.resolution")?;
let r = u64p(p, "resolution").ok_or_else(|| bad("textureSet.resolution", "`resolution` is required"))?;
let task = s.resize_task(ts, u32::try_from(r).unwrap_or(0))?;
let width = u64p(p, "resolution").ok_or_else(|| bad("textureSet.resolution", "`resolution` is required"))?;
let height = match p.get("height") {
None | Some(Value::Null) => width,
Some(_) => u64p(p, "height").ok_or_else(|| bad("textureSet.resolution", "`height` must be a number of texels"))?,
};
let task = s.resize_task_to(ts, u32::try_from(width).unwrap_or(0), u32::try_from(height).unwrap_or(0))?;
let out = task.run(&texturecraft_bake::Progress::new())?;
s.apply_resize(out)
}
@@ -115,9 +148,11 @@ fn resolution(s: &mut Session, p: &Value) -> Result<Value> {
pub struct ResizeTask {
ts: usize,
resolution: u32,
height: u32,
doc: Document,
mesh: Arc<Mesh>,
/// The session's revision and mesh when the task was made: the result applies only to them.
project_id: u64,
/// The revision and mesh used to calculate this result.
from: (u64, u64),
}
@@ -125,10 +160,12 @@ pub struct ResizeTask {
pub struct ResizeOutput {
ts: usize,
resolution: u32,
height: u32,
doc: Document,
/// The set's new caches (None when its UV tile layout moved: the session rebuilds them).
cache: Option<SetCache>,
log: crate::log::SessionLog,
project_id: u64,
from: (u64, u64),
}
@@ -136,10 +173,14 @@ impl ResizeTask {
/// Resample the set's painted pixels (bilinear; strokes are not replayed) and build its
/// caches. Progress goes from 0 to 1.
pub fn run(self, progress: &texturecraft_bake::Progress) -> Result<ResizeOutput> {
let ResizeTask { ts, resolution, mut doc, mesh, from } = self;
let ResizeTask { ts, resolution, height, mut doc, mesh, project_id, from } = self;
let set = doc.project.texture_set_mut(ts)?;
let old = set.clone();
set.resolution = resolution;
set.set_size(resolution, height);
if set.resolution_height.is_some() && !set.tile_resolutions.is_empty() {
return Err(bad("textureSet.resolution", "a texture set whose UV tiles have their own sizes stays square"));
}
crate::session::check_size(set)?;
let size = set.size();
let mut log = crate::log::SessionLog::new();
@@ -154,7 +195,7 @@ impl ResizeTask {
let set = doc.project.texture_set(ts)?;
let cache = (crate::session::uv_layout(&old) == crate::session::uv_layout(set)).then(|| SetCache::new(&mesh, set));
progress.done.store(10_000, std::sync::atomic::Ordering::Relaxed);
Ok(ResizeOutput { ts, resolution, doc, cache, log, from })
Ok(ResizeOutput { ts, resolution, height, doc, cache, log, project_id, from })
}
}
@@ -166,23 +207,43 @@ impl ResizeOutput {
}
impl Session {
/// Prepare resizing texture set `ts` to `resolution` (a power of two, 128..8192).
/// Prepare resizing texture set `ts` to a square `resolution` (a power of two, 128..8192)
pub fn resize_task(&mut self, ts: usize, resolution: u32) -> Result<ResizeTask> {
let resolution = check_resolution(resolution)?;
self.doc.project.texture_set(ts)?;
self.cancel_stroke();
Ok(ResizeTask { ts, resolution, doc: self.doc.clone(), mesh: self.mesh.clone(), from: (self.revision, self.mesh_id) })
self.resize_task_to(ts, resolution, resolution)
}
/// Apply a finished resize as one undo step. When the document changed while it ran, the
/// resize runs again here on the current document.
pub fn apply_resize(&mut self, out: ResizeOutput) -> Result<Value> {
if out.from != (self.revision, self.mesh_id) || self.stroke_active() {
let task = self.resize_task(out.ts, out.resolution)?;
return self.apply_resize(task.run(&texturecraft_bake::Progress::new())?);
/// Prepare resizing texture set `ts` to `width × height` texels (powers of two, 128..8192)
pub fn resize_task_to(&mut self, ts: usize, width: u32, height: u32) -> Result<ResizeTask> {
let (resolution, height) = (check_resolution(width)?, check_resolution(height)?);
self.doc.project.texture_set(ts)?;
self.cancel_stroke();
Ok(ResizeTask {
ts,
resolution,
height,
doc: self.doc.clone(),
mesh: self.mesh.clone(),
project_id: self.project_id,
from: (self.revision, self.mesh_id),
})
}
/// Apply a finished resize to its original project as one undo step. Edits made while the
/// resize ran are preserved by recomputing from the current document.
pub fn apply_resize(&mut self, mut out: ResizeOutput) -> Result<Value> {
if out.project_id != self.project_id {
return Err(bad("textureSet.resolution", "the project changed while the texture set was resizing"));
}
let ResizeOutput { ts, resolution, doc, cache, log, .. } = out;
if out.from != (self.revision, self.mesh_id) || self.stroke_active() {
let (ts, width, height) = (out.ts, out.resolution, out.height);
// Release the stale pixels and cache before building their replacement
drop(out);
out = self.resize_task_to(ts, width, height)?.run(&texturecraft_bake::Progress::new())?;
}
let ResizeOutput { ts, resolution, height, doc, cache, log, .. } = out;
let before = std::mem::replace(&mut self.doc, doc);
// Install the new caches before adding history to avoid rebuilding them
@@ -197,7 +258,7 @@ impl Session {
}
self.log.append(log);
self.push_history("Texture set size", before);
Ok(json!({ "ts": ts, "resolution": resolution }))
Ok(json!({ "ts": ts, "resolution": resolution, "height": height }))
}
}
@@ -217,15 +278,82 @@ fn channel(s: &mut Session, p: &Value, add: bool) -> Result<Value> {
Ok(Value::Null)
}
/// Add and remove several channels in one undo step, on one texture set or on all of them
fn channels(s: &mut Session, p: &Value) -> Result<Value> {
let cmd = "textureSet.channels";
let list = |key: &str| -> Result<Vec<Channel>> {
match p.get(key) {
None | Some(Value::Null) => Ok(Vec::new()),
Some(Value::Array(items)) => items
.iter()
.map(|item| {
let name = item.as_str().ok_or_else(|| bad(cmd, format!("`{key}` lists channel names")))?;
Channel::parse(name).ok_or_else(|| bad(cmd, format!("unknown channel `{name}`")))
})
.collect(),
Some(_) => Err(bad(cmd, format!("`{key}` must be a list of channels"))),
}
};
let add = list("add")?;
let remove = list("remove")?;
if remove.contains(&Channel::BaseColor) {
return Err(bad(cmd, "base color can't be removed"));
}
if let Some(both) = add.iter().find(|c| remove.contains(c)) {
return Err(bad(cmd, format!("{} is both added and removed", both.label())));
}
let all_sets = match p.get("allSets") {
None | Some(Value::Null) => false,
Some(value) => value.as_bool().ok_or_else(|| bad(cmd, "`allSets` must be a boolean"))?,
};
let sets: Vec<usize> = if all_sets { (0..s.set_count()).collect() } else { vec![ts_param(s, p, cmd)?] };
s.edit("Add or remove channels", |s| {
for &ts in &sets {
// A channel the set already has keeps its layers' channel switches
for &c in &add {
if !s.doc.project.texture_set(ts)?.has_channel(c) {
add_channel(s, ts, c)?;
}
}
s.doc.project.texture_set_mut(ts)?.channels.retain(|(c, _)| !remove.contains(c));
}
Ok(())
})?;
Ok(json!({ "ts": sets }))
}
/// Store a channel in another format; layer data keeps its precision, so a wider format brings back what was painted
fn channel_format(s: &mut Session, p: &Value) -> Result<Value> {
let cmd = "textureSet.channel.format";
let ts = ts_param(s, p, cmd)?;
let c = channel_param(cmd, p, "channel")?.ok_or_else(|| bad(cmd, "`channel` is required"))?;
let name = strp(p, "format").ok_or_else(|| bad(cmd, "`format` is required"))?;
let all = || ChannelFormat::ALL.map(ChannelFormat::label).join(", ");
let format = ChannelFormat::parse(name).ok_or_else(|| bad(cmd, format!("unknown format {name:?} ({})", all())))?;
s.edit("Channel format", |s| {
if s.doc.project.texture_set_mut(ts)?.set_channel_format(c, format) {
Ok(())
} else {
Err(bad(cmd, format!("the texture set has no {} channel", c.label())))
}
})?;
let float = matches!(format, ChannelFormat::L16F | ChannelFormat::Rgb16F | ChannelFormat::L32F | ChannelFormat::Rgb32F);
Ok(if float { json!({"note": "float formats are stored at 16 bits for now, and values stay in the channel's range"}) } else { Value::Null })
}
/// Add channel `c` to texture set `ts` (no-op when present) and enable it on the set's layers.
/// Call inside [`Session::edit`].
pub(crate) fn add_channel(s: &mut Session, ts: usize, c: Channel) -> Result<()> {
let set = s.doc.project.texture_set_mut(ts)?;
if !set.has_channel(c) {
set.channels.push((c, ChannelFormat::default_for(c)));
set.channels.sort_by_key(|(c, _)| c.index());
}
// Existing layers get the new channel enabled.
s.doc.project.texture_set_mut(ts)?.add_channel(c);
let ids: Vec<_> = s.doc.project.walk(ts).into_iter().map(|(id, _)| id).collect();
for id in ids {
if let Ok(l) = s.doc.project.layer_mut(id) {
@@ -264,13 +392,25 @@ fn visibility(s: &mut Session, p: &Value) -> Result<Value> {
Ok(json!({ "visible": s.doc.project.texture_sets.iter().map(|t| t.visible).collect::<Vec<_>>() }))
}
/// Longest texture set name and description, in characters
const MAX_NAME_CHARS: usize = 128;
const MAX_DESCRIPTION_CHARS: usize = 4096;
/// Highest height strength a set takes
const MAX_HEIGHT_STRENGTH: f32 = 100.0;
fn rename(s: &mut Session, p: &Value) -> Result<Value> {
let ts = ts_param(s, p, "textureSet.rename")?;
let name = strp(p, "name")
.map(str::trim)
.filter(|n| !n.is_empty() && n.chars().count() <= 128)
.ok_or_else(|| bad("textureSet.rename", "`name` is required"))?
.to_string();
let name = if boolp(p, "reset") == Some(true) {
s.original_set_name(ts).ok_or_else(|| bad("textureSet.rename", "the mesh has no material name for this set"))?.to_string()
} else {
let name = strp(p, "name").map(str::trim).filter(|name| !name.is_empty());
let name = name.ok_or_else(|| bad("textureSet.rename", "`name` or `reset: true` is required"))?;
if name.chars().count() > MAX_NAME_CHARS {
return Err(bad("textureSet.rename", format!("`name` is at most {MAX_NAME_CHARS} characters")));
}
name.to_string()
};
s.edit("Rename texture set", |s| {
s.doc.project.texture_set_mut(ts)?.name = name;
Ok(())
@@ -278,29 +418,184 @@ fn rename(s: &mut Session, p: &Value) -> Result<Value> {
Ok(Value::Null)
}
impl Session {
/// The name set `ts` had when the mesh loaded: its material's name in the mesh
pub fn original_set_name(&self, ts: usize) -> Option<&str> {
let set = self.doc.project.texture_sets.get(ts)?;
self.mesh.materials.get(set.material).map(String::as_str).filter(|name| !name.trim().is_empty())
}
}
fn settings(s: &mut Session, p: &Value) -> Result<Value> {
let ts = ts_param(s, p, "textureSet.settings")?;
let nf = normal_format_param("textureSet.settings", p)?;
let normal_format = normal_format_param("textureSet.settings", p)?;
let normal_mixing = choice_param(p, "normalMixing", "normal mixing", NormalMixing::parse, &NormalMixing::ALL.map(NormalMixing::id))?;
let ao_mixing = choice_param(p, "aoMixing", "ambient occlusion mixing", AoMixing::parse, &AoMixing::ALL.map(AoMixing::id))?;
let height_to_normal =
choice_param(p, "heightToNormal", "height to normal method", HeightToNormalMethod::parse, &HeightToNormalMethod::ALL.map(HeightToNormalMethod::id))?;
let uv_padding = choice_param(p, "uvPadding", "UV padding", UvPaddingMode::parse, &UvPaddingMode::ALL.map(UvPaddingMode::id))?;
s.edit("Texture set settings", |s| {
if let Some(n) = nf {
s.doc.project.normal_format = n;
if let Some(format) = normal_format {
s.doc.project.normal_format = format;
}
let set = s.doc.project.texture_set_mut(ts)?;
if let Some(d) = strp(p, "description") {
set.description = d.chars().take(4096).collect();
if let Some(description) = strp(p, "description") {
set.description = description.chars().take(MAX_DESCRIPTION_CHARS).collect();
}
if let Some(h) = f32p(p, "heightStrength") {
set.height_strength = h.clamp(0.0, 100.0);
if let Some(strength) = f32p(p, "heightStrength") {
set.height_strength = strength.clamp(0.0, MAX_HEIGHT_STRENGTH);
}
if let Some(mixing) = normal_mixing {
set.normal_mixing = mixing;
}
if let Some(mixing) = ao_mixing {
set.ao_mixing = mixing;
}
if let Some(method) = height_to_normal {
set.height_to_normal = method;
}
if let Some(mode) = uv_padding {
set.uv_padding = mode;
}
Ok(())
})?;
Ok(Value::Null)
}
/// The optional setting `key` of `textureSet.settings`, one of `ids`
fn choice_param<T>(p: &Value, key: &str, what: &str, parse: fn(&str) -> Option<T>, ids: &[&str]) -> Result<Option<T>> {
let unknown = |value: &Value| bad("textureSet.settings", format!("unknown {what} {value} ({})", ids.join(" or ")));
match p.get(key) {
None | Some(Value::Null) => Ok(None),
Some(value @ Value::String(id)) => parse(id).map(Some).ok_or_else(|| unknown(value)),
Some(other) => Err(unknown(other)),
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn channels_add_and_remove_together_in_one_undo_step_on_every_set() {
let mut s = Session::new_project("t", texturecraft_geom::primitives::material_ball(), "builtin:material_ball", None, 128).unwrap();
let has = |s: &Session, ts: usize, c: Channel| s.doc.project.texture_sets[ts].has_channel(c);
assert!(has(&s, 1, Channel::Height) && !has(&s, 1, Channel::User3));
let edit = json!({"add": ["emissive", "User3"], "remove": ["height"], "allSets": true});
crate::execute(&mut s, "textureSet.channels", &edit).unwrap();
for ts in 0..2 {
assert!(has(&s, ts, Channel::Emissive) && has(&s, ts, Channel::User3) && !has(&s, ts, Channel::Height), "set {ts}");
}
crate::execute(&mut s, "edit.undo", &json!({})).unwrap();
for ts in 0..2 {
assert!(!has(&s, ts, Channel::Emissive) && !has(&s, ts, Channel::User3) && has(&s, ts, Channel::Height), "set {ts}");
}
// Without allSets only the chosen set changes
crate::execute(&mut s, "textureSet.channels", &json!({"ts": 1, "add": ["ior"]})).unwrap();
assert!(has(&s, 1, Channel::Ior) && !has(&s, 0, Channel::Ior));
assert!(crate::execute(&mut s, "textureSet.channels", &json!({"remove": ["baseColor"]})).is_err());
assert!(crate::execute(&mut s, "textureSet.channels", &json!({"add": ["ior"], "remove": ["ior"]})).is_err());
assert!(crate::execute(&mut s, "textureSet.channels", &json!({"add": ["nope"]})).is_err());
}
#[test]
fn channels_applied_to_every_set_keep_the_channels_a_layer_switched_off() {
let mut s = Session::new_project("t", texturecraft_geom::primitives::material_ball(), "builtin:material_ball", None, 128).unwrap();
crate::execute(&mut s, "layer.add.fill", &json!({})).unwrap();
let layer = s.selected_layer().unwrap();
// Switched off, as layer.blend {enabled: false} leaves it
s.doc.project.layer_mut(layer).unwrap().channels.remove(&Channel::Roughness);
let layer_has_roughness = |s: &Session| s.doc.project.layer(layer).is_ok_and(|l| l.channels.contains_key(&Channel::Roughness));
assert!(!layer_has_roughness(&s));
// Apply to all Texture Sets sends every ticked channel, the ones the sets already have too
let ticked: Vec<&str> = s.doc.project.texture_sets[0].channel_list().iter().map(|c| c.id()).chain(["ior"]).collect();
crate::execute(&mut s, "textureSet.channels", &json!({"add": ticked, "allSets": true})).unwrap();
assert!(s.doc.project.texture_sets.iter().all(|set| set.has_channel(Channel::Ior)));
assert!(!layer_has_roughness(&s), "the layer's roughness stays off");
}
#[test]
fn invalid_set_selectors_cannot_edit_the_active_set() {
let mut session = crate::sample_session(128, 64).unwrap();
let before = session.doc.project.texture_sets[session.ts()].clone();
for ts in [json!("0"), json!(-1), json!(1_u64 << 32)] {
let params = json!({"ts": ts, "description": "wrong set"});
assert!(crate::execute(&mut session, "textureSet.settings", &params).is_err(), "{ts}");
assert_eq!(session.doc.project.texture_sets[session.ts()], before);
assert!(crate::execute(&mut session, "textureSet.select", &params).is_err(), "{ts}");
}
let invalid_scope = json!({"add": ["user7"], "allSets": "true"});
assert!(crate::execute(&mut session, "textureSet.channels", &invalid_scope).is_err());
assert_eq!(session.doc.project.texture_sets[session.ts()], before);
}
#[test]
fn malformed_size_and_setting_values_are_refused_and_change_nothing() {
let mut s = Session::new_project("t", texturecraft_geom::primitives::material_ball(), "builtin:material_ball", None, 128).unwrap();
crate::execute(&mut s, "textureSet.resolution", &json!({"ts": 0, "resolution": 256, "height": 128})).unwrap();
let before = s.doc.project.texture_sets[0].clone();
assert!(crate::execute(&mut s, "textureSet.resolution", &json!({"ts": 0, "resolution": 512, "height": "256"})).is_err());
for (key, value) in [("normalMixing", json!(1)), ("aoMixing", json!(true)), ("heightToNormal", json!(["sharp"])), ("uvPadding", json!(2))] {
let mut params = json!({"ts": 0});
params[key] = value.clone();
assert!(crate::execute(&mut s, "textureSet.settings", &params).is_err(), "{key}: {value}");
}
assert_eq!(s.doc.project.texture_sets[0], before);
}
#[test]
fn a_sets_size_formats_and_settings_survive_save_and_reopen() {
let mut s = Session::new_project("t", texturecraft_geom::primitives::material_ball(), "builtin:material_ball", None, 128).unwrap();
crate::execute(&mut s, "textureSet.resolution", &json!({"ts": 1, "resolution": 256, "height": 128})).unwrap();
crate::execute(&mut s, "textureSet.channel.format", &json!({"ts": 1, "channel": "roughness", "format": "L8"})).unwrap();
crate::execute(&mut s, "textureSet.channels", &json!({"ts": 1, "add": ["user7", "coatTangent"]})).unwrap();
let settings =
json!({"ts": 1, "normalMixing": "replace", "aoMixing": "none", "heightToNormal": "sharp", "uvPadding": "2d", "description": "Ünïcode 説明"});
crate::execute(&mut s, "textureSet.settings", &settings).unwrap();
let inspect = |s: &mut Session, ts: usize| crate::execute(s, "textureSet.inspect", &json!({"ts": ts})).unwrap();
let (first, second) = (inspect(&mut s, 0), inspect(&mut s, 1));
let mut back = Session::from_project_bytes(&s.to_project_bytes().unwrap()).unwrap();
for (ts, before) in [(0, first), (1, second)] {
let after = inspect(&mut back, ts);
for key in ["resolution", "height", "size", "channels", "normalMixing", "aoMixing", "heightToNormal", "uvPadding", "description"] {
assert_eq!(after[key], before[key], "set {ts} {key}");
}
}
assert_ne!(inspect(&mut back, 0)["uvPadding"], inspect(&mut back, 1)["uvPadding"], "each set keeps its own settings");
}
#[test]
fn rename_reset_restores_the_mesh_material_name() {
let mut s = Session::new_project("t", texturecraft_geom::primitives::material_ball(), "builtin:material_ball", None, 128).unwrap();
let original = crate::execute(&mut s, "textureSet.inspect", &json!({"ts": 1})).unwrap()["name"].clone();
crate::execute(&mut s, "textureSet.rename", &json!({"ts": 1, "name": "Renamed"})).unwrap();
let inspect = crate::execute(&mut s, "textureSet.inspect", &json!({"ts": 1})).unwrap();
assert_eq!((&inspect["name"], &inspect["originalName"]), (&json!("Renamed"), &original));
crate::execute(&mut s, "textureSet.rename", &json!({"ts": 1, "reset": true})).unwrap();
assert_eq!(crate::execute(&mut s, "textureSet.inspect", &json!({"ts": 1})).unwrap()["name"], original);
assert!(crate::execute(&mut s, "textureSet.rename", &json!({"ts": 1})).is_err());
}
#[test]
fn a_too_long_name_is_refused_for_its_length_not_as_missing() {
let mut s = Session::new_project("t", texturecraft_geom::primitives::material_ball(), "builtin:material_ball", None, 128).unwrap();
let long = "n".repeat(MAX_NAME_CHARS + 1);
let error = crate::execute(&mut s, "textureSet.rename", &json!({"ts": 1, "name": long})).unwrap_err().to_string();
assert!(error.contains("at most") && !error.contains("required"), "{error}");
assert!(crate::execute(&mut s, "textureSet.rename", &json!({"ts": 1, "name": "n".repeat(MAX_NAME_CHARS)})).is_ok());
}
#[test]
fn visibility_shows_hides_inverts_and_solos() {
// The material ball has two texture sets.
@@ -314,4 +609,144 @@ mod tests {
assert_eq!(run(json!({"mode": "showAll"})).unwrap(), json!([true, true]));
assert!(run(json!({"mode": "sideways"})).is_err() && run(json!({"mode": "solo", "ts": 9})).is_err());
}
#[test]
fn normal_mixing_replace_keeps_height_out_of_the_normal_and_undoes() {
let mut s = Session::new_project("t", texturecraft_geom::primitives::material_ball(), "builtin:material_ball", None, 128).unwrap();
let mixing = |s: &Session| crate::inspect::texture_set(s, 0)["normalMixing"].clone();
assert_eq!(mixing(&s), json!("combine"));
crate::execute(&mut s, "textureSet.settings", &json!({"ts": 0, "normalMixing": "replace"})).unwrap();
assert_eq!(mixing(&s), json!("replace"));
assert!(!s.doc.project.texture_sets[0].height_in_normal() && s.doc.project.texture_sets[1].height_in_normal());
assert!(crate::execute(&mut s, "textureSet.settings", &json!({"normalMixing": "blend"})).is_err());
crate::execute(&mut s, "edit.undo", &Value::Null).unwrap();
assert_eq!(mixing(&s), json!("combine"));
}
#[test]
fn height_to_normal_method_is_set_by_command_and_undoes() {
let mut s = Session::new_project("t", texturecraft_geom::primitives::material_ball(), "builtin:material_ball", None, 128).unwrap();
let method = |s: &Session, ts: usize| crate::inspect::texture_set(s, ts)["heightToNormal"].clone();
assert_eq!(method(&s, 0), json!("smooth"));
crate::execute(&mut s, "textureSet.settings", &json!({"ts": 0, "heightToNormal": "sharp"})).unwrap();
assert_eq!((method(&s, 0), method(&s, 1)), (json!("sharp"), json!("smooth")));
assert!(crate::execute(&mut s, "textureSet.settings", &json!({"heightToNormal": "blurry"})).is_err());
crate::execute(&mut s, "edit.undo", &Value::Null).unwrap();
assert_eq!(method(&s, 0), json!("smooth"));
}
#[test]
fn uv_padding_rebuilds_the_viewport_padding_and_undoes() {
// The ball's second set has texels just past its seams at this size
let mut s = Session::new_project("t", texturecraft_geom::primitives::material_ball(), "builtin:material_ball", None, 512).unwrap();
let mode = |s: &Session| crate::inspect::texture_set(s, 1)["uvPadding"].clone();
let crosses_seams = |s: &Session| !s.caches[1].padding.crossed.is_empty();
assert_eq!((mode(&s), crosses_seams(&s)), (json!("3d"), true));
s.update();
crate::execute(&mut s, "textureSet.settings", &json!({"ts": 1, "uvPadding": "2d"})).unwrap();
assert_eq!((mode(&s), crosses_seams(&s)), (json!("2d"), false));
assert!(!s.caches[1].dirty.is_empty(), "the set recomposites with its new padding");
assert!(crate::execute(&mut s, "textureSet.settings", &json!({"uvPadding": "4d"})).is_err());
crate::execute(&mut s, "edit.undo", &Value::Null).unwrap();
assert_eq!((mode(&s), crosses_seams(&s)), (json!("3d"), true));
}
#[test]
fn channel_format_changes_what_the_viewport_holds_and_undoes() {
let mut s = Session::new_project("t", texturecraft_geom::primitives::material_ball(), "builtin:material_ball", None, 128).unwrap();
let format = |s: &Session| {
let channels = crate::inspect::texture_set(s, 0)["channels"].clone();
channels.as_array().and_then(|list| list.iter().find(|entry| entry["channel"] == "roughness")).map(|entry| entry["format"].clone())
};
let roughness = |s: &mut Session| {
s.update();
let img = &s.caches[0].composite.channels[&Channel::Roughness];
let tile = s.caches[0].covered_tiles[0];
img.tile(tile.0, tile.1).map(<[u16]>::to_vec).unwrap_or_default()
};
crate::execute(&mut s, "textureSet.channel.format", &json!({"channel": "roughness", "format": "L16"})).unwrap();
// A roughness off the 8-bit grid, so 8 bits visibly round it
crate::execute(&mut s, "layer.add.fill", &json!({"roughness": 0.3013})).unwrap();
let sixteen = roughness(&mut s);
assert_eq!(format(&s), Some(json!("L16")));
crate::execute(&mut s, "textureSet.channel.format", &json!({"channel": "Roughness", "format": "l8"})).unwrap();
let eight = roughness(&mut s);
assert_eq!(format(&s), Some(json!("L8")));
assert_ne!(eight, sixteen, "the composite holds 8 bits");
let eight_bit_step = u16::MAX / u16::from(u8::MAX);
assert!(eight.iter().all(|v| v % eight_bit_step == 0), "every texel is on an 8-bit step");
let float = crate::execute(&mut s, "textureSet.channel.format", &json!({"channel": "height", "format": "L32F"})).unwrap();
assert!(float["note"].is_string(), "a float format says it holds 16 bits");
crate::execute(&mut s, "edit.undo", &Value::Null).unwrap();
assert!(crate::execute(&mut s, "textureSet.channel.format", &json!({"channel": "roughness", "format": "L4"})).is_err());
assert!(crate::execute(&mut s, "textureSet.channel.format", &json!({"channel": "emissive", "format": "L8"})).is_err());
crate::execute(&mut s, "edit.undo", &Value::Null).unwrap();
assert_eq!((format(&s), roughness(&mut s)), (Some(json!("L16")), sixteen));
}
#[test]
fn channels_added_after_a_format_is_set_keep_16_bits() {
let mut s = Session::new_project("t", texturecraft_geom::primitives::material_ball(), "builtin:material_ball", None, 128).unwrap();
let format = |s: &Session, id: &str| {
let channels = crate::inspect::texture_set(s, 0)["channels"].clone();
channels.as_array().and_then(|list| list.iter().find(|entry| entry["channel"] == id)).map(|entry| entry["format"].clone())
};
crate::execute(&mut s, "textureSet.channel.format", &json!({"ts": 0, "channel": "roughness", "format": "L8"})).unwrap();
crate::execute(&mut s, "textureSet.channel.add", &json!({"ts": 0, "channel": "user3"})).unwrap();
crate::execute(&mut s, "textureSet.channels", &json!({"ts": 0, "add": ["user4"]})).unwrap();
assert_eq!((format(&s, "user3"), format(&s, "user4")), (Some(json!("L16")), Some(json!("L16"))));
assert_eq!(format(&s, "roughness"), Some(json!("L8")), "the set format stays");
}
#[test]
fn ao_mixing_resends_the_set_to_the_viewport_and_undoes() {
let mut s = Session::new_project("t", texturecraft_geom::primitives::material_ball(), "builtin:material_ball", None, 128).unwrap();
s.update();
let _ = (s.take_uploads(0), s.take_uploads(1));
crate::execute(&mut s, "textureSet.settings", &json!({"ts": 0, "aoMixing": "none"})).unwrap();
assert_eq!(crate::inspect::texture_set(&s, 0)["aoMixing"], json!("none"));
assert!(!s.take_uploads(0).is_empty() && s.take_uploads(1).is_empty(), "only the changed set is resent");
assert!(crate::execute(&mut s, "textureSet.settings", &json!({"aoMixing": "screen"})).is_err());
crate::execute(&mut s, "edit.undo", &Value::Null).unwrap();
s.update();
assert_eq!(crate::inspect::texture_set(&s, 0)["aoMixing"], json!("multiply"));
assert!(!s.take_uploads(0).is_empty(), "undo resends the set too");
}
#[test]
fn channels_our_shader_ignores_are_added_marked_and_exported() {
let mut s = Session::new_project("t", texturecraft_geom::primitives::material_ball(), "builtin:material_ball", None, 128).unwrap();
for channel in ["user3", "Displacement", "coat tangent"] {
crate::execute(&mut s, "textureSet.channel.add", &json!({"ts": 0, "channel": channel})).unwrap();
}
let channels = crate::inspect::texture_set(&s, 0)["channels"].clone();
let shaded = |id: &str| channels.as_array().and_then(|list| list.iter().find(|c| c["channel"] == id)).map(|c| c["shaded"].clone());
assert_eq!((shaded("user3"), shaded("displacement"), shaded("coatTangent")), (Some(json!(false)), Some(json!(false)), Some(json!(false))));
assert_eq!(shaded("baseColor"), Some(json!(true)));
let plan = crate::execute(&mut s, "export.plan", &json!({"preset": "Separate maps"})).unwrap();
let files: Vec<(Value, String)> =
plan.as_array().into_iter().flatten().map(|f| (f["ts"].clone(), f["file"].as_str().unwrap_or_default().to_ascii_lowercase())).collect();
for map in ["user3", "displacement", "coattangent"] {
let from = |ts: usize| files.iter().any(|(t, file)| *t == json!(ts) && file.contains(map));
assert!(from(0) && !from(1), "{map} exported only from the set that has it: {files:?}");
}
s.update();
let composite = &s.caches[0].composite;
assert!(composite.channels.contains_key(&Channel::User3) && composite.channels.contains_key(&Channel::CoatTangent));
}
}
+1 -1
View File
@@ -81,7 +81,7 @@ impl Session {
let set = inputs.project.texture_sets.get(ts)?;
let mut output = Composite { block_scales: inputs.block_scales.clone(), ..Composite::with_size(&set.channel_list(), cache.size.0, cache.size.1) };
composite_tiles(inputs, &mut output, tiles);
pad_tiles(&mut output, &cache.dilation, tiles);
pad_tiles(&mut output, &cache.padding, tiles);
Some(Cow::Owned(output))
})
}
+24
View File
@@ -32,6 +32,8 @@ pub struct ProjectTemplate {
pub normal_format: NormalFormat,
/// Channels of every texture set, with their formats.
pub channels: Vec<(Channel, ChannelFormat)>,
/// Whether the channels hold their formats' precision ([`texturecraft_core::TextureSet::format_precision`]); older templates keep 16 bits
pub format_precision: bool,
/// Shader: PBR specular/glossiness instead of metallic/roughness.
pub spec_gloss: bool,
pub parallax: bool,
@@ -49,6 +51,7 @@ impl Default for ProjectTemplate {
resolution: 2048,
normal_format: NormalFormat::OpenGl,
channels: with_formats(&Channel::DEFAULT_SET),
format_precision: false,
spec_gloss: d.spec_gloss,
parallax: d.parallax,
ior: d.ior,
@@ -208,6 +211,7 @@ impl Session {
for set_index in 0..project.texture_sets.len() {
if let Some(set) = project.texture_sets.get_mut(set_index) {
set.channels = template.channels.clone();
set.format_precision = template.format_precision;
}
for (id, _) in project.walk(set_index) {
@@ -304,6 +308,7 @@ fn save(session: &mut Session, params: &Value) -> Result<Value> {
resolution: set.resolution,
normal_format: project.normal_format,
channels: set.channels.clone(),
format_precision: set.format_precision,
spec_gloss: display.spec_gloss,
parallax: display.parallax,
ior: display.ior,
@@ -443,6 +448,25 @@ mod tests {
assert!(execute(&mut s, "project.new", &json!({"template": "nope"})).is_err());
}
#[test]
fn a_template_keeps_the_channel_formats_picked_in_the_set_it_was_saved_from() {
let dir = std::env::temp_dir().join(format!("tc_template_formats_{}", std::process::id()));
let _ = std::fs::remove_dir_all(&dir);
let mut s = Session::new_project("t", texturecraft_geom::primitives::material_ball(), "builtin:material_ball", None, 128).unwrap();
s.load_templates(dir.clone());
execute(&mut s, "textureSet.channel.format", &json!({"channel": "roughness", "format": "L8"})).unwrap();
execute(&mut s, "project.template.save", &json!({"name": "Eight bit roughness"})).unwrap();
let mut fresh = Session::new_project("f", texturecraft_geom::primitives::material_ball(), "builtin:material_ball", None, 128).unwrap();
fresh.load_templates(dir.clone());
execute(&mut fresh, "project.new", &json!({"template": "Eight bit roughness"})).unwrap();
let held = |session: &Session, channel: Channel| session.doc.project.texture_sets[0].formats().into_iter().find(|(c, _)| *c == channel).map(|(_, f)| f);
assert_eq!(held(&fresh, Channel::Roughness), held(&s, Channel::Roughness));
assert_eq!(held(&fresh, Channel::Metallic), held(&s, Channel::Metallic), "the other channels keep 16 bits");
let _ = std::fs::remove_dir_all(&dir);
}
#[test]
fn save_current_settings_as_template_and_reload() {
let dir = std::env::temp_dir().join(format!("tc_templates_{}", std::process::id()));
+35 -3
View File
@@ -24,7 +24,38 @@ pub fn specs() -> Vec<CommandSpec> {
}
/// Fonts bundled with the app (egui's), used when nothing is installed or in the browser.
#[cfg(not(target_arch = "wasm32"))]
const BUILT_IN: [(&str, &[u8]); 2] = [("Ubuntu Light", epaint_default_fonts::UBUNTU_LIGHT), ("Hack", epaint_default_fonts::HACK_REGULAR)];
/// The built-in fonts' names, in [`provide_built_in_fonts`]'s order.
#[cfg(target_arch = "wasm32")]
const BUILT_IN_NAMES: [&str; 2] = ["Ubuntu Light", "Hack"];
#[cfg(target_arch = "wasm32")]
static BUILT_IN_SOURCE: std::sync::OnceLock<fn() -> [&'static [u8]; 2]> = std::sync::OnceLock::new();
/// The web build's built-in fonts, Ubuntu Light and Hack, from `source`. The browser app already carries egui's faces
/// (deflated, for its download budget), so it says where to get them instead of the engine embedding a second, raw
/// copy. `source` runs once, when text first needs a built-in font. Only the first call counts.
#[cfg(target_arch = "wasm32")]
pub fn provide_built_in_fonts(source: fn() -> [&'static [u8]; 2]) {
let _ = BUILT_IN_SOURCE.set(source);
}
/// The built-in fonts: names and bytes. On the web the bytes are empty without [`provide_built_in_fonts`].
#[cfg(target_arch = "wasm32")]
fn built_in() -> [(&'static str, &'static [u8]); 2] {
static BYTES: std::sync::OnceLock<[&'static [u8]; 2]> = std::sync::OnceLock::new();
let bytes = match BUILT_IN_SOURCE.get() {
Some(source) => *BYTES.get_or_init(*source),
None => [&[] as &[u8], &[]],
};
[(BUILT_IN_NAMES[0], bytes[0]), (BUILT_IN_NAMES[1], bytes[1])]
}
#[cfg(not(target_arch = "wasm32"))]
fn built_in() -> [(&'static str, &'static [u8]); 2] {
BUILT_IN
}
/// Families tried, in order, when no font is asked for.
#[cfg(not(target_arch = "wasm32"))]
const DEFAULT_FAMILIES: [&str; 6] = ["Arial", "Segoe UI", "Helvetica", "Liberation Sans", "DejaVu Sans", "Noto Sans"];
@@ -54,7 +85,7 @@ fn fonts() -> Value {
let families: Vec<(String, Vec<String>)> = Vec::new();
json!({
"installed": families.into_iter().map(|(family, styles)| json!({"family": family, "styles": styles})).collect::<Vec<_>>(),
"builtIn": BUILT_IN.map(|(name, _)| name),
"builtIn": built_in().map(|(name, _)| name),
})
}
@@ -62,7 +93,8 @@ fn fonts() -> Value {
/// or the first default family installed, else the built-in font.
fn font_bytes(family: Option<&str>, style: Option<&str>) -> Result<(std::borrow::Cow<'static, [u8]>, u32)> {
let is = |a: &str, b: &str| a.eq_ignore_ascii_case(b);
if let Some((_, bytes)) = BUILT_IN.iter().find(|(name, _)| family.is_some_and(|f| is(f, name))) {
let built_in = built_in();
if let Some((_, bytes)) = built_in.iter().find(|(name, _)| family.is_some_and(|f| is(f, name))) {
return Ok((std::borrow::Cow::Borrowed(bytes), 0));
}
#[cfg(not(target_arch = "wasm32"))]
@@ -91,7 +123,7 @@ fn font_bytes(family: Option<&str>, style: Option<&str>) -> Result<(std::borrow:
let _ = style;
match family {
Some(f) => Err(bad("resource.text", format!("no font family `{f}` (see text.fonts)"))),
None => Ok((std::borrow::Cow::Borrowed(BUILT_IN[0].1), 0)),
None => Ok((std::borrow::Cow::Borrowed(built_in[0].1), 0)),
}
}
+31 -13
View File
@@ -12,6 +12,12 @@ use crate::fill_mode::FillMode;
use crate::session::{CloneFrom, CloneSource, StackTarget, Tool};
use crate::{Result, Session, cmd};
/// Brush size the UI's full size slider stands for
const MAX_BRUSH_SIZE: f32 = 0.25;
/// Full value of the UI's 0–100 brush scales
const PERCENT: f32 = 100.0;
pub fn specs() -> Vec<CommandSpec> {
vec![
cmd!("tool.paint", "Paint", ["Tools"], Some("1"), "{}", always, |s, _| set_tool(s, Tool::Paint)),
@@ -36,7 +42,7 @@ pub fn specs() -> Vec<CommandSpec> {
"Brush settings",
[],
None,
"{size?: 0..100, flow?: 0..100, opacity?: 0..100, spacing?: 1..1000, hardness?: 0..100, angle?, followPath?, alignment?: tangent|camera, lazy?, jitterSize?, jitterAngle?, jitterFlow?, jitterPosition?, alpha?: procedural name | {image: resource name} | {library: id (alpha.list)}, alphaSizeX?: 5..100 and alphaSizeY?: 5..100 (percent of the stamp the alpha fills), alphaRoundness?: 0..100 (Round alpha only: 100 circle, 0 square), alphaContrast?: 1..8, alphaInvert?, backfaceCulling?, symmetryOn? (the toolbar toggle; off keeps the settings), symmetryX?, symmetryY?, symmetryZ?, symmetryRadial?: 0..32 copies around symmetryAxis?: x|y|z (default y), symmetryOffset?: [x, y, z] (world units from the mesh center, where the mirror planes and radial axis cross), symmetryAngleSpan?: 0..360 degrees the radial copies spread over, minSize?, smudgeStrength?: 0..100, cloneSource?: composite|layer (what the Clone tool copies), cloneAligned? (default true: the first stroke fixes the offset to the source for the following strokes; false: every stroke starts sampling at the source point), particles?: {enabled?, count?: 1..16, lifetime?: 1..128 steps, gravity?: 0..2}}",
"{size?: 0..100, flow?: 0..100, opacity?: 0..100, spacing?: 1..1000, hardness?: 0..100, angle?, followPath?, alignment?: tangent|camera, lazy?, jitterSize?, jitterAngle?, jitterFlow?, jitterPosition?, alpha?: procedural name | {image: resource name} | {library: id (alpha.list)}, alphaSizeX?: 5..100 and alphaSizeY?: 5..100 (percent of the stamp the alpha fills), alphaRoundness?: 0..100 (Round alpha only: 100 circle, 0 square), alphaContrast?: 1..8, alphaInvert?, backfaceCulling?, angleFade?: [from, to] degrees 0..90 (culled faces fade out between them), screenSpace? (the size follows the view), stampDepth?: 0.05..4, symmetryOn? (the toolbar toggle; off keeps the settings), symmetryX?, symmetryY?, symmetryZ?, symmetryRadial?: 0..32 copies around symmetryAxis?: x|y|z (default y), symmetryOffset?: [x, y, z] (world units from the mesh center, where the mirror planes and radial axis cross), symmetryAngleSpan?: 0..360 degrees the radial copies spread over, minSize?, sizePressure? (default true: pen pressure shrinks the size towards minSize), smudgeStrength?: 0..100, cloneSource?: composite|layer (what the Clone tool copies), cloneAligned? (default true: the first stroke fixes the offset to the source for the following strokes; false: every stroke starts sampling at the source point), particles?: {enabled?, count?: 1..16, lifetime?: 1..128 steps, gravity?: 0..2}}",
always,
brush
),
@@ -64,7 +70,7 @@ pub fn specs() -> Vec<CommandSpec> {
),
cmd!(
"tool.stencil",
"Projection stencil",
"Stencil",
[],
None,
"{image?: resource name, center?: [x,y] NDC, scale?: 0.01..10, rotation?: degrees, tile?, opacity?, clear?: bool}",
@@ -132,14 +138,17 @@ fn select(s: &mut Session, p: &Value) -> Result<Value> {
/// Brush values use the UI's 0–100 scales, so agents and the sliders speak the same numbers
fn brush(session: &mut Session, params: &Value) -> Result<Value> {
let mut settings = session.tool.brush.clone();
let percent = |key: &str| f32p(params, key).map(|value| value / 100.0);
let percent = |key: &str| f32p(params, key).map(|value| value / PERCENT);
if let Some(value) = percent("size") {
settings.size = value * 0.25;
settings.size = value * MAX_BRUSH_SIZE;
}
if let Some(value) = percent("minSize") {
settings.min_size = value;
}
if let Some(value) = boolp(params, "sizePressure") {
settings.size_pressure = value;
}
if let Some(value) = percent("flow") {
settings.flow = value;
@@ -174,11 +183,11 @@ fn brush(session: &mut Session, params: &Value) -> Result<Value> {
for (key, slot) in [("jitterSize", &mut settings.jitter_size), ("jitterAngle", &mut settings.jitter_angle), ("jitterFlow", &mut settings.jitter_flow)] {
if let Some(value) = f32p(params, key) {
*slot = value / 100.0;
*slot = value / PERCENT;
}
}
if let Some(value) = f32p(params, "jitterPosition") {
settings.jitter_position = value / 100.0;
settings.jitter_position = value / PERCENT;
}
let alpha = params.get("alpha");
@@ -215,6 +224,13 @@ fn brush(session: &mut Session, params: &Value) -> Result<Value> {
if let Some(value) = boolp(params, "backfaceCulling") {
settings.backface_culling = value;
}
if params.get("angleFade").is_some() {
let [from, to] = pair(params, "angleFade").ok_or_else(|| bad("tool.brush", "`angleFade` must be [from, to] in degrees"))?;
settings.angle_fade = (from, to);
}
if let Some(value) = f32p(params, "stampDepth") {
settings.depth = value;
}
if let Some(value) = boolp(params, "symmetryOn") {
settings.symmetry.enabled = value;
@@ -282,30 +298,32 @@ fn brush(session: &mut Session, params: &Value) -> Result<Value> {
}
}
if let Some(value) = f32p(params, "smudgeStrength") {
session.tool.smudge_strength = (value / 100.0).clamp(0.0, 1.0);
session.tool.smudge_strength = (value / PERCENT).clamp(0.0, 1.0);
}
session.revision = session.revision.wrapping_add(1);
Ok(brush_json(session))
}
/// The brush settings `tool.brush` reports, on the UI's 0–100 scales
pub(crate) fn brush_json(session: &Session) -> Value {
let settings = &session.tool.brush;
json!({
"size": settings.size / 0.25 * 100.0, "minSize": settings.min_size * 100.0, "flow": settings.flow * 100.0, "opacity": settings.opacity * 100.0,
"spacing": settings.spacing * 100.0, "hardness": settings.hardness * 100.0, "angle": settings.angle, "followPath": settings.follow_path,
"size": settings.size / MAX_BRUSH_SIZE * PERCENT, "minSize": settings.min_size * PERCENT, "sizePressure": settings.size_pressure, "flow": settings.flow * PERCENT, "opacity": settings.opacity * PERCENT,
"spacing": settings.spacing * PERCENT, "hardness": settings.hardness * PERCENT, "angle": settings.angle, "followPath": settings.follow_path,
"alignment": format!("{:?}", settings.alignment).to_lowercase(), "lazy": settings.lazy,
"alpha": match (&settings.alpha_image, &settings.alpha_library) {
(Some(name), _) => json!({ "image": name }),
(None, Some(id)) => json!({ "library": id }),
(None, None) => json!(settings.alpha.label()),
},
"alphaSizeX": settings.alpha_params.size_x * 100.0, "alphaSizeY": settings.alpha_params.size_y * 100.0,
"alphaRoundness": settings.alpha_params.roundness * 100.0, "alphaContrast": settings.alpha_params.contrast, "alphaInvert": settings.alpha_params.invert,
"backfaceCulling": settings.backface_culling, "symmetry": [settings.symmetry.x, settings.symmetry.y, settings.symmetry.z],
"alphaSizeX": settings.alpha_params.size_x * PERCENT, "alphaSizeY": settings.alpha_params.size_y * PERCENT,
"alphaRoundness": settings.alpha_params.roundness * PERCENT, "alphaContrast": settings.alpha_params.contrast, "alphaInvert": settings.alpha_params.invert,
"backfaceCulling": settings.backface_culling, "angleFade": [settings.angle_fade.0, settings.angle_fade.1], "screenSpace": settings.screen_space,
"stampDepth": settings.depth, "symmetry": [settings.symmetry.x, settings.symmetry.y, settings.symmetry.z],
"radialSymmetry": { "copies": settings.symmetry.radial, "axis": (["x", "y", "z"].get(settings.symmetry.axis as usize)) },
"symmetryOffset": settings.symmetry.offset, "symmetryOn": settings.symmetry.enabled, "symmetryAngleSpan": settings.symmetry.angle_span,
"material": session.tool.material, "smudgeStrength": session.tool.smudge_strength * 100.0, "particles": settings.particles,
"material": session.tool.material, "smudgeStrength": session.tool.smudge_strength * PERCENT, "particles": settings.particles,
"cloneSource": if session.tool.clone_from == CloneFrom::Layer { "layer" } else { "composite" },
"cloneAligned": session.tool.clone_aligned,
})
+37 -2
View File
@@ -50,6 +50,10 @@ fn tile_resolution(session: &mut Session, params: &Value) -> Result<Value> {
return Err(bad(COMMAND, format!("texture set \"{}\" has no UV tile {tile} (tiles: {:?})", texture_set.name, texture_set.uv_tiles)));
}
if texture_set.resolution_height.is_some() && resolution != texture_set.resolution {
return Err(bad(COMMAND, format!("UV tiles of a non-square texture set (\"{}\") can't have their own size", texture_set.name)));
}
let removes_override = resolution == texture_set.resolution && texture_set.tile_resolutions.contains_key(&tile);
if texture_set.tile_resolution(tile) == resolution && !removes_override {
return Ok(json!({ "ts": texture_set_index, "tile": tile, "resolution": resolution, "size": texture_set.size() }));
@@ -299,6 +303,11 @@ mod tests {
}
}
/// Width and height of a PNG file, read from its header
fn png_size(bytes: &[u8]) -> (u32, u32) {
image::ImageReader::with_format(std::io::Cursor::new(bytes), image::ImageFormat::Png).into_dimensions().unwrap()
}
/// Mean painted alpha over the covered texels of the set's current layout.
fn painted_fraction(s: &Session) -> f64 {
let id = s.doc.project.texture_sets[0].stack[0];
@@ -374,8 +383,6 @@ mod tests {
execute(&mut s, "textureSet.tile.resolution", &json!({"tile": 1002, "resolution": 128})).unwrap();
let opts = crate::file_cmds::export_options(&s, &json!({"preset": "Document channels + Normal + AO", "format": "png"}), "t").unwrap();
let files = s.export_files(&[0], &opts).unwrap();
// PNG: width and height are the big-endian words after the IHDR tag.
let png_size = |b: &[u8]| (u32::from_be_bytes(b[16..20].try_into().unwrap()), u32::from_be_bytes(b[20..24].try_into().unwrap()));
assert!(files.len() >= 4);
for f in &files {
let want = if f.name.contains("1002") { 128 } else { 256 };
@@ -383,6 +390,34 @@ mod tests {
}
}
#[test]
fn non_square_sets_keep_their_paint_export_wide_tiles_and_refuse_tile_sizes() {
let mut s = udim_session();
paint_all(&mut s, 50000);
execute(&mut s, "textureSet.resolution", &json!({"resolution": 256, "height": 128})).unwrap();
s.update();
let (w, h) = s.doc.project.texture_sets[0].size();
assert!(w > 2 * h, "two tiles side by side, each wider than tall: {:?}", (w, h));
assert_eq!((s.caches[0].gbuf.width, s.caches[0].gbuf.height), (w, h));
assert!(painted_fraction(&s) > 0.97);
let inspect = execute(&mut s, "textureSet.inspect", &json!({})).unwrap();
assert!(inspect["height"].as_u64() < inspect["resolution"].as_u64());
let opts = crate::file_cmds::export_options(&s, &json!({"preset": "Document channels + Normal + AO", "format": "png"}), "t").unwrap();
for f in &s.export_files(&[0], &opts).unwrap() {
let (fw, fh) = png_size(&f.bytes);
assert!(fw > fh, "{} is {fw}x{fh}", f.name);
}
assert!(execute(&mut s, "textureSet.tile.resolution", &json!({"tile": 1002, "resolution": 128})).is_err());
s.undo().unwrap();
assert_eq!(s.doc.project.texture_sets[0].size(), (512, 256));
// A set whose tiles have their own sizes stays square
execute(&mut s, "textureSet.tile.resolution", &json!({"tile": 1002, "resolution": 128})).unwrap();
assert!(execute(&mut s, "textureSet.resolution", &json!({"resolution": 256, "height": 128})).is_err());
}
/// Paint channel `c` of the first layer over every covered texel as `f(u)`, `u` the texel's
/// position across its own UV tile (0..1), so every tile shows the same pattern in UV space.
fn paint_across_tiles(s: &mut Session, c: Channel, f: impl Fn(f32) -> Vec<u16>) {
+18 -3
View File
@@ -42,7 +42,7 @@ pub fn specs() -> Vec<CommandSpec> {
"Set view mode",
[],
None,
"{mode: material|uvChecker|normalHeightMesh (the normal the shading uses: mesh normal, Height channel slope and Normal channel; 2D view: the tangent-space normal)|image (an image resource shown as it is on the mesh and in the 2D view)|mask|<channel id>|map:<mesh map id>, image? (the resource, for image), layer? (for mask)}",
"{mode: material|uvChecker|normalHeightMesh (the normal the shading uses: mesh normal, Height channel slope and Normal channel; 2D view: the tangent-space normal)|image (an image resource shown as it is on the mesh and in the 2D view)|mask|<shaded channel id>|map:<mesh map id>, image? (the resource, for image), layer? (for mask)}",
always,
view
),
@@ -161,7 +161,7 @@ fn set_view(s: &mut Session, v: ViewMode) -> Result<Value> {
/// C and Shift+C: the set's channels, then "Normal+height+mesh", then round again
fn cycle_channel(s: &mut Session, d: i64) -> Result<Value> {
let mut views: Vec<ViewMode> = s.doc.project.texture_set(s.ts()).map(|t| t.channel_list()).unwrap_or_default().into_iter().map(ViewMode::Channel).collect();
let mut views: Vec<_> = s.doc.project.texture_sets.get(s.ts()).into_iter().flat_map(|set| set.viewport_channels()).map(ViewMode::Channel).collect();
if views.is_empty() {
return set_view(s, ViewMode::Material);
}
@@ -217,7 +217,14 @@ fn view(s: &mut Session, p: &Value) -> Result<Value> {
}
_ => match m.strip_prefix("map:") {
Some(id) => ViewMode::MeshMap(BakedMap::parse(id).ok_or_else(|| bad("viewport.view", format!("unknown mesh map `{id}`")))?),
None => ViewMode::Channel(Channel::parse(m).ok_or_else(|| bad("viewport.view", format!("unknown view mode `{m}`")))?),
None => {
let channel = Channel::parse(m).ok_or_else(|| bad("viewport.view", format!("unknown view mode `{m}`")))?;
if !channel.is_shaded() {
return Err(bad("viewport.view", format!("{} is stored for export and has no viewport view", channel.label())));
}
ViewMode::Channel(channel)
}
},
};
set_view(s, v)
@@ -467,14 +474,22 @@ mod tests {
assert!(channels.len() > 2);
assert_eq!(s.view, ViewMode::Material);
execute(&mut s, "textureSet.channel.add", &json!({"channel": "user31"})).unwrap();
let result = execute(&mut s, "viewport.view", &json!({"mode": "user31"}));
assert!(result.is_err(), "the viewport cannot display an export-only channel");
assert_eq!(s.view, ViewMode::Material);
// From the material C starts at the first channel
let mut seen = Vec::new();
for _ in 0..channels.len() + 2 {
seen.push(pressed(&mut s, "viewport.nextChannel"));
}
let mut expected = channels.clone();
expected.push(ViewMode::NormalHeightMesh);
expected.push(channels[0]);
assert_eq!(seen, expected, "channels, then Normal+height+mesh, then round again");
// Shift+C walks it backwards, and from the material starts at the last entry