Merge upstream/main

This commit is contained in:
vangel76 committed 2026-11-17 22:23:12 +01:00
commit 398d764fc2
27 files changed
+1191 -277

No files matched your search

+83 -5
View File
@@ -71,7 +71,23 @@ fn join(dir: &str, name: &str) -> String {
impl Headless {
pub fn new(session: Session, fs: Filesystem) -> Headless {
// Bakes run here (CLI, MCP) cast their rays on the GPU when there is one.
let home = std::env::var("USERPROFILE").or_else(|_| std::env::var("HOME")).unwrap_or_else(|_| ".".into());
let brush_dir = std::path::Path::new(&home).join("Documents").join("TextureCraft").join("brushes");
Self::new_with_brush_dir(session, fs, brush_dir)
}
fn new_with_brush_dir(mut session: Session, fs: Filesystem, brush_dir: std::path::PathBuf) -> Headless {
if matches!(fs, Filesystem::TrustedLocal) && session.brush_presets.dir.is_none() {
let warnings = session.load_brush_presets(brush_dir);
session.log.extend(warnings.into_iter().map(|warning| format!("Brush preset skipped: {warning}")));
} else if !matches!(fs, Filesystem::TrustedLocal) {
session.brush_presets.dir = None;
for preset in &mut session.brush_presets.list {
preset.file = None;
}
}
// CLI and MCP bakes use GPU rays when available
texturecraft_engine::bake::install_gpu_tracer(std::sync::Arc::new(texturecraft_render::gpu_bake::GpuBaker::new()));
Headless { session, fs, gpu: None }
}
@@ -129,10 +145,9 @@ impl Headless {
}
}
/// Replace the session, keeping the viewport size scripted strokes use.
fn replace(&mut self, mut next: Session) -> Value {
next.viewport = self.session.viewport;
self.session = next;
/// Replace the project, keeping the viewport size and user libraries.
fn replace(&mut self, next: Session) -> Value {
self.session.switch_to(next);
self.inspect()
}
@@ -388,3 +403,66 @@ pub fn batch_reply(results: Vec<Value>, failed: Option<(usize, &str, String)>) -
"failed": failed.map(|(index, id, error)| json!({ "index": index, "id": id, "error": error })),
})
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn fresh_headless_session_loads_saved_brushes() {
let brush_dir = std::env::temp_dir().join(format!("tc-headless-brush-{}", std::process::id()));
let _ = std::fs::remove_dir_all(&brush_dir);
let mut first_client = Headless::new_with_brush_dir(Headless::default_session().unwrap(), Filesystem::TrustedLocal, brush_dir.clone());
first_client.command_run("brush.preset.store", json!({"name": "Ink"})).unwrap();
let mut restarted_client = Headless::new_with_brush_dir(Headless::default_session().unwrap(), Filesystem::TrustedLocal, brush_dir.clone());
let listed = restarted_client.command_run("brush.preset.list", Value::Null).unwrap();
assert!(listed.as_array().unwrap().iter().any(|item| item["label"] == "Ink"));
restarted_client.command_run("brush.preset.apply", json!({"preset": "Ink"})).unwrap();
let _ = std::fs::remove_dir_all(&brush_dir);
}
#[test]
fn headless_project_switch_keeps_saved_brushes() {
let brush_dir = std::env::temp_dir().join(format!("tc-headless-switch-{}", std::process::id()));
let _ = std::fs::remove_dir_all(&brush_dir);
let mut client = Headless::new_with_brush_dir(Headless::default_session().unwrap(), Filesystem::TrustedLocal, brush_dir.clone());
client.command_run("brush.preset.store", json!({"name": "Ink"})).unwrap();
client.replace(Headless::default_session().unwrap());
let listed = client.command_run("brush.preset.list", Value::Null).unwrap();
assert!(listed.as_array().unwrap().iter().any(|item| item["label"] == "Ink"));
let _ = std::fs::remove_dir_all(&brush_dir);
}
#[test]
fn untrusted_headless_keeps_brushes_in_memory_only() {
let brush_dir = std::env::temp_dir().join(format!("tc-headless-denied-{}", std::process::id()));
let _ = std::fs::remove_dir_all(&brush_dir);
let mut trusted_client = Headless::new_with_brush_dir(Headless::default_session().unwrap(), Filesystem::TrustedLocal, brush_dir.clone());
trusted_client.command_run("brush.preset.store", json!({"name": "Ink"})).unwrap();
let mut untrusted_client = Headless::new_with_brush_dir(Headless::default_session().unwrap(), Filesystem::Denied, brush_dir.clone());
assert!(untrusted_client.session.brush_presets.dir.is_none());
assert!(untrusted_client.session.brush_presets.list.is_empty());
let listed = untrusted_client.command_run("brush.preset.list", Value::Null).unwrap();
assert!(!listed.as_array().unwrap().iter().any(|item| item["label"] == "Ink"));
untrusted_client.command_run("brush.preset.store", json!({"name": "Session only"})).unwrap();
assert!(untrusted_client.session.brush_presets.find("Session only").is_some());
assert!(!brush_dir.join("Session_only.tcbrush").exists());
let mut preloaded_session = Headless::default_session().unwrap();
preloaded_session.load_brush_presets(brush_dir.clone());
let mut preloaded_client = Headless::new_with_brush_dir(preloaded_session, Filesystem::Denied, brush_dir.clone());
assert!(preloaded_client.session.brush_presets.dir.is_none());
assert!(preloaded_client.session.brush_presets.list.iter().all(|preset| preset.file.is_none()));
preloaded_client.command_run("brush.preset.store", json!({"name": "Still private"})).unwrap();
assert!(!brush_dir.join("Still_private.tcbrush").exists());
preloaded_client.command_run("brush.preset.delete", json!({"name": "Ink"})).unwrap();
assert!(brush_dir.join("Ink.tcbrush").exists());
let _ = std::fs::remove_dir_all(&brush_dir);
}
}
+506 -28
View File
@@ -1,13 +1,15 @@
//! Brush presets: the built-in ones, and the user's own saved as `.tcbrush` files (the brush
//! settings as JSON). Applying or loading one changes the stroke and keeps the brush's size.
//! settings as JSON). Built-ins keep size; user presets restore size and channels.
use serde_json::{Value, json};
#[cfg(test)]
use texturecraft_core::Channel;
use texturecraft_paint::BrushSettings;
#[cfg(not(target_arch = "wasm32"))]
use texturecraft_paint::presets::with_stroke_of;
use texturecraft_paint::presets::{PRESETS, find_preset};
use crate::commands::{CommandSpec, always, bad, strp};
use crate::commands::{CommandSpec, always, bad, boolp, strp};
use crate::tool_cmds::brush_json;
use crate::{Result, Session, cmd};
@@ -17,63 +19,300 @@ pub const BRUSH_EXT: &str = "tcbrush";
#[cfg(not(target_arch = "wasm32"))]
const MAX_BYTES: u64 = 1 << 20;
/// Most user presets kept (and read from the folder).
const MAX_USER: usize = 512;
/// Longest preset name.
const MAX_NAME: usize = 60;
/// Category the user's presets are listed under.
pub const USER_CATEGORY: &str = "My brushes";
mod user_brush;
mod user_brushes;
pub use user_brush::UserBrush;
pub use user_brushes::UserBrushes;
impl Session {
/// Use `dir` as the user brush folder: read its `*.tcbrush` files (replacing the list) and
/// mirror later changes there. Returns a warning per file that was skipped. Files holding a
/// bare brush (what `brush.preset.save` writes) are named after the file.
#[cfg(not(target_arch = "wasm32"))]
pub fn load_brush_presets(&mut self, dir: std::path::PathBuf) -> Vec<String> {
use std::io::Read as _;
let mut warnings = Vec::new();
let mut files = std::collections::BinaryHeap::new();
match std::fs::read_dir(&dir) {
// No folder yet: no presets
Err(error) if error.kind() == std::io::ErrorKind::NotFound => {}
Err(error) => warnings.push(format!("{}: cannot read the brush folder: {error}", dir.display())),
Ok(entries) => {
for entry in entries {
match entry {
Ok(entry) => {
let path = entry.path();
if !path.extension().is_some_and(|extension| extension.eq_ignore_ascii_case(BRUSH_EXT)) {
continue;
}
if files.len() < MAX_USER {
files.push(path);
} else if files.peek().is_some_and(|last| path < *last) {
files.pop();
files.push(path);
}
}
Err(error) => warnings.push(format!("{}: a file could not be read: {error}", dir.display())),
}
}
}
}
let mut library = UserBrushes { list: Vec::new(), dir: Some(dir) };
for path in files.into_sorted_vec() {
let mut bytes = Vec::new();
let read = std::fs::File::open(&path).and_then(|file| file.take(MAX_BYTES + 1).read_to_end(&mut bytes));
if let Err(error) = read {
warnings.push(format!("{}: {error}", path.display()));
continue;
}
if bytes.len() as u64 > MAX_BYTES {
warnings.push(format!("{}: too large for a brush preset", path.display()));
continue;
}
let stem = path.file_stem().and_then(|stem| stem.to_str()).unwrap_or("brush");
let parsed = serde_json::from_slice::<UserBrush>(&bytes).or_else(|_| {
serde_json::from_slice::<BrushSettings>(&bytes).map(|brush| UserBrush { name: stem.to_string(), brush, channels: None, file: None })
});
match parsed {
Ok(mut preset) => {
preset.name = preset.name.trim().chars().take(MAX_NAME).collect();
preset.brush = preset.brush.sanitized();
preset.file = Some(path.clone());
if preset.name.is_empty() || preset.name.chars().any(char::is_control) || library.taken(&preset.name, None) {
warnings.push(format!("{}: the name \"{}\" is empty or taken", path.display(), preset.name));
} else {
library.list.push(preset);
}
}
Err(error) => warnings.push(format!("{}: not a brush preset: {error}", path.display())),
}
}
self.brush_presets = library;
warnings
}
}
pub fn specs() -> Vec<CommandSpec> {
vec![
cmd!("brush.preset.list", "List brush presets", [], None, "{} — the built-in presets: id, label, category", always, |_, _| Ok(list())),
cmd!(
"brush.preset.list",
"List brush presets",
[],
None,
"{} — the built-in presets and the user's own: id, label, category, builtin",
always,
|session, _| Ok(list(session))
),
cmd!(
"brush.preset.apply",
"Apply brush preset",
[],
None,
"{preset: id or label (brush.preset.list)} — sets the stroke (alpha, spacing, flow, hardness, jitters…), keeps the size",
"{preset: id or label (brush.preset.list)} — a built-in sets the stroke (alpha, spacing, flow, hardness, jitters…) and keeps the size; one of the user's sets the whole brush, size included, and the painted channels",
always,
apply
),
cmd!(
"brush.preset.store",
"Save current brush as a preset",
[],
None,
"{name, overwrite?: true = replace the user preset of that name} — the current brush and painted channels; desktop and trusted CLI mirror to the data folder, browser and untrusted headless keep them until reload → {name}",
always,
store
),
cmd!(
"brush.preset.rename",
"Rename a brush preset",
[],
None,
"{name, to} — one of the user's presets (built-ins are read-only) → {name}",
always,
rename
),
cmd!("brush.preset.delete", "Delete a brush preset", [], None, "{name} — one of the user's presets (built-ins are read-only)", always, delete),
cmd!("brush.preset.save", "Save brush preset", [], None, "{path} — the current brush as a .tcbrush file", always, save),
cmd!("brush.preset.load", "Load brush preset", [], None, "{path} — a .tcbrush file's stroke on the brush, keeping the size", always, load),
]
}
fn list() -> Value {
json!(PRESETS.iter().map(|p| json!({"id": p.id, "label": p.label, "category": p.category})).collect::<Vec<_>>())
fn list(session: &Session) -> Value {
let builtin_presets = PRESETS.iter().map(|preset| json!({"id": preset.id, "label": preset.label, "category": preset.category, "builtin": true}));
let user_presets =
session.brush_presets.list.iter().map(|preset| json!({"id": preset.name, "label": preset.name, "category": USER_CATEGORY, "builtin": false}));
json!(builtin_presets.chain(user_presets).collect::<Vec<_>>())
}
fn apply(s: &mut Session, p: &Value) -> Result<Value> {
let name = strp(p, "preset").ok_or_else(|| bad("brush.preset.apply", "`preset` is required"))?;
let preset = find_preset(name).ok_or_else(|| bad("brush.preset.apply", format!("unknown brush preset `{name}` (see brush.preset.list)")))?;
set(s, preset.applied(&s.tool.brush))
fn apply(session: &mut Session, params: &Value) -> Result<Value> {
const CMD: &str = "brush.preset.apply";
let name = strp(params, "preset").ok_or_else(|| bad(CMD, "`preset` is required"))?;
if let Some(preset) = find_preset(name) {
return set(session, preset.applied(&session.tool.brush));
}
let user_preset = session.brush_presets.find(name).and_then(|index| session.brush_presets.list.get(index)).cloned();
let user_preset = user_preset.ok_or_else(|| bad(CMD, format!("unknown brush preset `{name}` (see brush.preset.list)")))?;
let mut brush = user_preset.brush.sanitized();
// Clear an image alpha when its project image is unavailable
if brush.alpha_image.as_ref().is_some_and(|image_name| !session.images.contains_key(image_name)) {
brush.alpha_image = None;
}
if let Some(channels) = user_preset.channels {
session.tool.enabled = channels;
}
set(session, brush)
}
fn set(s: &mut Session, brush: BrushSettings) -> Result<Value> {
s.tool.brush = brush;
s.revision = s.revision.wrapping_add(1);
Ok(brush_json(s))
fn name_param(params: &Value, key: &str, command: &str) -> Result<String> {
let name = strp(params, key).map(str::trim).filter(|name| !name.is_empty()).ok_or_else(|| bad(command, format!("`{key}` is required")))?;
if name.chars().count() > MAX_NAME || name.chars().any(char::is_control) {
return Err(bad(command, format!("`{key}` must be 1–{MAX_NAME} characters without control characters")));
}
Ok(name.to_string())
}
fn store(session: &mut Session, params: &Value) -> Result<Value> {
const CMD: &str = "brush.preset.store";
let name = name_param(params, "name", CMD)?;
if find_preset(&name).is_some() {
return Err(bad(CMD, format!("\"{name}\" is a built-in preset and can't be replaced")));
}
let library = &session.brush_presets;
let existing_index = library.find(&name);
if existing_index.is_some() && boolp(params, "overwrite") != Some(true) {
return Err(bad(CMD, format!("a brush preset named \"{name}\" exists already (pass overwrite: true to replace it)")));
}
if library.taken(&name, existing_index) {
return Err(bad(CMD, format!("\"{name}\" is too close to another preset's name")));
}
if existing_index.is_none() && library.list.len() >= MAX_USER {
return Err(bad(CMD, format!("at most {MAX_USER} user brush presets")));
}
// Keep the stored spelling when replacing a preset
let existing = existing_index.and_then(|index| library.list.get(index));
let name = existing.map_or(name, |preset| preset.name.clone());
let old_file = existing.and_then(|preset| preset.file.clone());
let mut stored_preset = UserBrush { name: name.clone(), brush: session.tool.brush.sanitized(), channels: Some(session.tool.enabled.clone()), file: None };
stored_preset.file = library.write(&stored_preset, old_file.as_deref()).map_err(|error| bad(CMD, error))?;
match existing_index.and_then(|index| session.brush_presets.list.get_mut(index)) {
Some(slot) => *slot = stored_preset,
None => session.brush_presets.list.push(stored_preset),
}
Ok(json!({ "name": name }))
}
fn rename(session: &mut Session, params: &Value) -> Result<Value> {
const CMD: &str = "brush.preset.rename";
let current_name = name_param(params, "name", CMD)?;
let new_name = name_param(params, "to", CMD)?;
if find_preset(&current_name).is_some() {
return Err(bad(CMD, format!("\"{current_name}\" is a built-in preset and can't be renamed")));
}
let library = &session.brush_presets;
let preset_index = library.find(&current_name).ok_or_else(|| bad(CMD, format!("no user brush preset `{current_name}`")))?;
if find_preset(&new_name).is_some() || library.taken(&new_name, Some(preset_index)) {
return Err(bad(CMD, format!("a brush preset named \"{new_name}\" exists already")));
}
let Some(mut renamed_preset) = library.list.get(preset_index).cloned() else {
return Err(bad(CMD, format!("no user brush preset `{current_name}`")));
};
let old_file = renamed_preset.file.clone().or_else(|| library.file_of(&renamed_preset.name));
renamed_preset.name = new_name.clone();
renamed_preset.file = library.write(&renamed_preset, old_file.as_deref()).map_err(|error| bad(CMD, error))?;
if let Some(slot) = session.brush_presets.list.get_mut(preset_index) {
*slot = renamed_preset;
}
Ok(json!({ "name": new_name }))
}
fn delete(session: &mut Session, params: &Value) -> Result<Value> {
const CMD: &str = "brush.preset.delete";
let name = name_param(params, "name", CMD)?;
if find_preset(&name).is_some() {
return Err(bad(CMD, format!("\"{name}\" is a built-in preset and can't be deleted")));
}
let preset_index = session.brush_presets.find(&name).ok_or_else(|| bad(CMD, format!("no user brush preset `{name}`")))?;
let Some(preset) = session.brush_presets.list.get(preset_index) else {
return Err(bad(CMD, format!("no user brush preset `{name}`")));
};
// The file goes first: a preset whose file stays would come back at the next start
session.brush_presets.delete(preset).map_err(|error| bad(CMD, error))?;
session.brush_presets.list.remove(preset_index);
Ok(Value::Null)
}
fn set(session: &mut Session, brush: BrushSettings) -> Result<Value> {
session.tool.brush = brush;
session.revision = session.revision.wrapping_add(1);
Ok(brush_json(session))
}
#[cfg(not(target_arch = "wasm32"))]
fn save(s: &mut Session, p: &Value) -> Result<Value> {
let path = strp(p, "path").ok_or_else(|| bad("brush.preset.save", "`path` is required"))?;
let bytes = serde_json::to_vec_pretty(&s.tool.brush).map_err(|e| bad("brush.preset.save", e.to_string()))?;
std::fs::write(path, bytes).map_err(|e| bad("brush.preset.save", format!("cannot write {path}: {e}")))?;
fn save(session: &mut Session, params: &Value) -> Result<Value> {
let path = strp(params, "path").ok_or_else(|| bad("brush.preset.save", "`path` is required"))?;
let bytes = serde_json::to_vec_pretty(&session.tool.brush).map_err(|error| bad("brush.preset.save", error.to_string()))?;
std::fs::write(path, bytes).map_err(|error| bad("brush.preset.save", format!("cannot write {path}: {error}")))?;
Ok(json!({ "path": path }))
}
#[cfg(not(target_arch = "wasm32"))]
fn load(s: &mut Session, p: &Value) -> Result<Value> {
fn load(session: &mut Session, params: &Value) -> Result<Value> {
use std::io::Read as _;
let cmd = "brush.preset.load";
let path = strp(p, "path").ok_or_else(|| bad(cmd, "`path` is required"))?;
let command = "brush.preset.load";
let path = strp(params, "path").ok_or_else(|| bad(command, "`path` is required"))?;
let mut bytes = Vec::new();
std::fs::File::open(path).and_then(|f| f.take(MAX_BYTES + 1).read_to_end(&mut bytes)).map_err(|e| bad(cmd, format!("cannot read {path}: {e}")))?;
std::fs::File::open(path)
.and_then(|file| file.take(MAX_BYTES + 1).read_to_end(&mut bytes))
.map_err(|error| bad(command, format!("cannot read {path}: {error}")))?;
if bytes.len() as u64 > MAX_BYTES {
return Err(bad(cmd, format!("{path} is too large for a brush preset")));
return Err(bad(command, format!("{path} is too large for a brush preset")));
}
let mut from: BrushSettings = serde_json::from_slice(&bytes).map_err(|e| bad(cmd, format!("{path} is not a brush preset: {e}")))?;
// An image alpha belongs to the project that saved it.
if from.alpha_image.as_ref().is_some_and(|n| !s.images.contains_key(n)) {
from.alpha_image = None;
let mut loaded_brush = serde_json::from_slice::<UserBrush>(&bytes)
.map(|preset| preset.brush)
.or_else(|_| serde_json::from_slice::<BrushSettings>(&bytes))
.map_err(|error| bad(command, format!("{path} is not a brush preset: {error}")))?;
// Clear an image alpha when its project image is unavailable
if loaded_brush.alpha_image.as_ref().is_some_and(|image_name| !session.images.contains_key(image_name)) {
loaded_brush.alpha_image = None;
}
set(s, with_stroke_of(&s.tool.brush, &from))
set(session, with_stroke_of(&session.tool.brush, &loaded_brush))
}
#[cfg(target_arch = "wasm32")]
@@ -85,3 +324,242 @@ fn save(_: &mut Session, _: &Value) -> Result<Value> {
fn load(_: &mut Session, _: &Value) -> Result<Value> {
Err(bad("brush.preset.load", "file paths are not available in the browser"))
}
#[cfg(test)]
mod tests {
use super::*;
use texturecraft_geom::primitives;
fn session() -> Session {
Session::new_project("t", primitives::material_ball(), "builtin:material_ball", None, 128).unwrap()
}
fn run(test_session: &mut Session, id: &str, params: Value) -> Result<Value> {
crate::execute(test_session, id, &params)
}
fn names(test_session: &Session) -> Vec<&str> {
test_session.brush_presets.list.iter().map(|preset| preset.name.as_str()).collect()
}
#[test]
fn store_apply_overwrite_rename_and_delete() {
let mut test_session = session();
run(&mut test_session, "tool.brush", json!({"size": 40, "hardness": 20, "flow": 35, "spacing": 12, "jitterSize": 50})).unwrap();
test_session.tool.enabled = [Channel::Roughness].into_iter().collect();
assert_eq!(run(&mut test_session, "brush.preset.store", json!({"name": " Mine "})).unwrap()["name"], "Mine");
let saved = test_session.tool.brush.clone();
// User presets restore size and painted channels
run(&mut test_session, "brush.preset.apply", json!({"preset": "basic_soft"})).unwrap();
run(&mut test_session, "tool.brush", json!({"size": 5})).unwrap();
test_session.tool.enabled = [Channel::BaseColor].into_iter().collect();
run(&mut test_session, "brush.preset.apply", json!({"preset": "mine"})).unwrap();
assert_eq!(test_session.tool.brush, saved);
assert_eq!(test_session.tool.enabled, [Channel::Roughness].into_iter().collect());
// List user presets after built-ins
let listed = run(&mut test_session, "brush.preset.list", json!({})).unwrap();
let last = listed.as_array().unwrap().last().unwrap().clone();
assert_eq!((last["label"].as_str(), last["builtin"].as_bool(), last["category"].as_str()), (Some("Mine"), Some(false), Some(USER_CATEGORY)));
assert_eq!(listed[0]["builtin"], true);
// Replacements require overwrite and built-ins stay read-only
assert!(run(&mut test_session, "brush.preset.store", json!({"name": "MINE"})).is_err());
run(&mut test_session, "tool.brush", json!({"size": 70})).unwrap();
assert_eq!(run(&mut test_session, "brush.preset.store", json!({"name": "MINE", "overwrite": true})).unwrap()["name"], "Mine");
assert_eq!(names(&test_session), ["Mine"], "overwriting does not add a second one");
assert!((test_session.brush_presets.list[0].brush.size - saved.size).abs() > 1e-4);
for builtin in ["Chalk", "basic-hard"] {
assert!(run(&mut test_session, "brush.preset.store", json!({"name": builtin, "overwrite": true})).is_err());
assert!(run(&mut test_session, "brush.preset.rename", json!({"name": builtin, "to": "x"})).is_err());
assert!(run(&mut test_session, "brush.preset.delete", json!({"name": builtin})).is_err());
}
// Renaming preserves content and removes the old name
run(&mut test_session, "brush.preset.store", json!({"name": "Second"})).unwrap();
assert!(run(&mut test_session, "brush.preset.rename", json!({"name": "Mine", "to": "second"})).is_err());
assert!(run(&mut test_session, "brush.preset.rename", json!({"name": "Mine", "to": "Airbrush"})).is_err());
assert!(run(&mut test_session, "brush.preset.rename", json!({"name": "nope", "to": "x"})).is_err());
assert_eq!(run(&mut test_session, "brush.preset.rename", json!({"name": "mine", "to": "Renamed"})).unwrap()["name"], "Renamed");
assert_eq!(names(&test_session), ["Renamed", "Second"]);
assert!(run(&mut test_session, "brush.preset.apply", json!({"preset": "Mine"})).is_err());
// Presets survive project replacement
run(&mut test_session, "project.new", json!({"resolution": 128})).unwrap();
assert_eq!(test_session.brush_presets.list.len(), 2);
run(&mut test_session, "brush.preset.delete", json!({"name": "renamed"})).unwrap();
assert_eq!(names(&test_session), ["Second"]);
assert!(run(&mut test_session, "brush.preset.delete", json!({"name": "renamed"})).is_err());
}
#[test]
fn hostile_names_are_refused() {
let mut test_session = session();
for name in [json!(""), json!(" "), json!("x".repeat(MAX_NAME + 1)), json!("a\nb"), json!(7), Value::Null] {
assert!(run(&mut test_session, "brush.preset.store", json!({"name": name})).is_err());
}
run(&mut test_session, "brush.preset.store", json!({"name": "a/b"})).unwrap();
assert!(run(&mut test_session, "brush.preset.store", json!({"name": "a?b"})).is_err(), "same file name as `a/b`");
assert_eq!(names(&test_session), ["a/b"]);
}
#[cfg(not(target_arch = "wasm32"))]
#[test]
fn presets_persist_in_the_folder() {
let dir = std::env::temp_dir().join(format!("tc-brush-lib-{}", std::process::id()));
let _ = std::fs::remove_dir_all(&dir);
let mut test_session = session();
assert!(test_session.load_brush_presets(dir.clone()).is_empty(), "a missing folder is an empty library");
run(&mut test_session, "tool.brush", json!({"size": 33, "hardness": 80})).unwrap();
run(&mut test_session, "brush.preset.store", json!({"name": "Ink pen"})).unwrap();
run(&mut test_session, "brush.preset.store", json!({"name": "Scratch", "overwrite": true})).unwrap();
run(&mut test_session, "brush.preset.rename", json!({"name": "Scratch", "to": "Scratchy"})).unwrap();
assert!(dir.join("Ink_pen.tcbrush").is_file() && dir.join("Scratchy.tcbrush").is_file());
assert!(!dir.join("Scratch.tcbrush").exists(), "a rename moves the file");
run(&mut test_session, "brush.preset.delete", json!({"name": "Scratchy"})).unwrap();
assert!(!dir.join("Scratchy.tcbrush").exists());
// Legacy files and invalid files share the brush folder
run(&mut test_session, "brush.preset.save", json!({"path": dir.join("Old style.tcbrush").to_str().unwrap()})).unwrap();
std::fs::write(dir.join("broken.tcbrush"), b"{ nope").unwrap();
std::fs::write(dir.join("Chalk.tcbrush"), serde_json::to_vec(&BrushSettings::default()).unwrap()).unwrap();
let mut fresh = session();
let warnings = fresh.load_brush_presets(dir.clone());
assert_eq!(warnings.len(), 2, "{warnings:?}");
assert_eq!(names(&fresh), ["Ink pen", "Old style"]);
assert!((fresh.brush_presets.list[0].brush.size - test_session.tool.brush.size).abs() < 1e-6);
assert!(fresh.brush_presets.list[0].channels.is_some() && fresh.brush_presets.list[1].channels.is_none());
let _ = std::fs::remove_dir_all(&dir);
}
#[cfg(not(target_arch = "wasm32"))]
#[test]
fn named_and_bare_files_load_the_saved_stroke_without_changing_setup() {
let directory = std::env::temp_dir().join(format!("tc-brush-load-formats-{}", std::process::id()));
let _ = std::fs::remove_dir_all(&directory);
let mut source = session();
source.load_brush_presets(directory.clone());
source.tool.brush = BrushSettings { size: 0.08, flow: 0.3, hardness: 0.7, ..BrushSettings::default() };
source.tool.enabled = [Channel::Roughness].into_iter().collect();
run(&mut source, "brush.preset.store", json!({"name": "Ink"})).unwrap();
let bare_path = directory.join("bare.tcbrush");
run(&mut source, "brush.preset.save", json!({"path": bare_path})).unwrap();
for path in [bare_path, directory.join("Ink.tcbrush")] {
let mut destination = session();
destination.tool.brush.size = 0.15;
destination.tool.enabled = [Channel::BaseColor].into_iter().collect();
run(&mut destination, "brush.preset.load", json!({"path": path})).unwrap();
assert_eq!(destination.tool.brush.flow, source.tool.brush.flow);
assert_eq!(destination.tool.brush.hardness, source.tool.brush.hardness);
assert_eq!(destination.tool.brush.size, 0.15);
assert_eq!(destination.tool.enabled, [Channel::BaseColor].into_iter().collect());
}
let _ = std::fs::remove_dir_all(directory);
}
/// The files in a brush folder, sorted.
fn files(dir: &std::path::Path) -> Vec<String> {
let mut file_names: Vec<String> = std::fs::read_dir(dir).unwrap().map(|entry| entry.unwrap().file_name().to_string_lossy().into_owned()).collect();
file_names.sort();
file_names
}
#[test]
fn older_bare_files_are_renamed_replaced_and_deleted_in_place() {
let dir = std::env::temp_dir().join(format!("tc-brush-legacy-{}", std::process::id()));
let _ = std::fs::remove_dir_all(&dir);
std::fs::create_dir_all(&dir).unwrap();
let mut test_session = session();
// A bare brush whose file name is not what the name would give ("Old_style.tcbrush")
run(&mut test_session, "brush.preset.save", json!({"path": dir.join("Old style.tcbrush").to_str().unwrap()})).unwrap();
run(&mut test_session, "brush.preset.save", json!({"path": dir.join("Second one.tcbrush").to_str().unwrap()})).unwrap();
assert!(test_session.load_brush_presets(dir.clone()).is_empty());
run(&mut test_session, "brush.preset.delete", json!({"name": "Old style"})).unwrap();
assert_eq!(files(&dir), ["Second one.tcbrush"], "the file it was read from is deleted");
run(&mut test_session, "brush.preset.rename", json!({"name": "Second one", "to": "Renamed"})).unwrap();
assert_eq!(files(&dir), ["Renamed.tcbrush"], "a rename moves the file it was read from");
run(&mut test_session, "brush.preset.store", json!({"name": "Renamed", "overwrite": true})).unwrap();
assert_eq!(files(&dir), ["Renamed.tcbrush"]);
let mut fresh = session();
assert!(fresh.load_brush_presets(dir.clone()).is_empty(), "nothing comes back or clashes on the next start");
assert_eq!(names(&fresh), ["Renamed"]);
let _ = std::fs::remove_dir_all(&dir);
}
#[test]
fn a_rename_that_only_changes_case_keeps_one_file() {
let dir = std::env::temp_dir().join(format!("tc-brush-case-{}", std::process::id()));
let _ = std::fs::remove_dir_all(&dir);
let mut test_session = session();
assert!(test_session.load_brush_presets(dir.clone()).is_empty());
run(&mut test_session, "brush.preset.store", json!({"name": "mine"})).unwrap();
run(&mut test_session, "brush.preset.rename", json!({"name": "mine", "to": "Mine"})).unwrap();
assert_eq!(files(&dir), ["Mine.tcbrush"]);
let mut fresh = session();
assert!(fresh.load_brush_presets(dir.clone()).is_empty());
assert_eq!(names(&fresh), ["Mine"]);
let _ = std::fs::remove_dir_all(&dir);
}
#[test]
fn a_filename_owned_by_another_preset_cannot_be_overwritten() {
let dir = std::env::temp_dir().join(format!("tc-brush-owner-{}", std::process::id()));
let _ = std::fs::remove_dir_all(&dir);
std::fs::create_dir_all(&dir).unwrap();
let original = UserBrush { name: "Ink".into(), brush: BrushSettings::default(), channels: None, file: None };
let original_bytes = serde_json::to_vec(&original).unwrap();
let path = dir.join("Pencil.tcbrush");
std::fs::write(&path, &original_bytes).unwrap();
let mut session = session();
assert!(session.load_brush_presets(dir.clone()).is_empty());
assert!(run(&mut session, "brush.preset.store", json!({"name": "Pencil"})).is_err());
assert_eq!(std::fs::read(&path).unwrap(), original_bytes);
assert_eq!(names(&session), ["Ink"]);
let _ = std::fs::remove_dir_all(&dir);
}
#[test]
fn a_brush_folder_that_cannot_be_read_is_reported() {
// A file where the folder should be: reading it as a folder fails with an error other than NotFound
let path = std::env::temp_dir().join(format!("tc-brush-not-a-dir-{}", std::process::id()));
std::fs::write(&path, b"not a folder").unwrap();
let mut test_session = session();
let warnings = test_session.load_brush_presets(path.clone());
assert_eq!(warnings.len(), 1, "{warnings:?}");
assert!(test_session.brush_presets.list.is_empty());
let _ = std::fs::remove_file(&path);
}
#[test]
fn loaded_names_with_control_characters_are_skipped() {
let dir = std::env::temp_dir().join(format!("tc-brush-name-{}", std::process::id()));
let _ = std::fs::remove_dir_all(&dir);
std::fs::create_dir_all(&dir).unwrap();
let preset = UserBrush { name: "bad\nname".into(), brush: BrushSettings::default(), channels: None, file: None };
std::fs::write(dir.join("bad.tcbrush"), serde_json::to_vec(&preset).unwrap()).unwrap();
let mut session = session();
let warnings = session.load_brush_presets(dir.clone());
assert_eq!(warnings.len(), 1);
assert!(session.brush_presets.list.is_empty());
let _ = std::fs::remove_dir_all(&dir);
}
}
@@ -0,0 +1,19 @@
use std::collections::BTreeSet;
use serde::{Deserialize, Serialize};
use texturecraft_core::Channel;
use texturecraft_paint::BrushSettings;
/// A brush the user saved: the whole brush (size included) and the channels it paints.
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub struct UserBrush {
pub name: String,
pub brush: BrushSettings,
/// Channels painted when it was saved (None: leave the channels alone).
#[serde(default)]
pub channels: Option<BTreeSet<Channel>>,
/// The file it was read from or last written to (None: not on disk yet). Deleting and
/// renaming act on this file, which for an older bare `.tcbrush` is not the name's file.
#[serde(skip)]
pub file: Option<std::path::PathBuf>,
}
@@ -0,0 +1,144 @@
use texturecraft_formats::export::sanitize_file_stem;
use texturecraft_paint::presets::find_preset;
#[cfg(not(target_arch = "wasm32"))]
use super::BRUSH_EXT;
use super::UserBrush;
/// The user's brush presets, mirrored as `<name>.tcbrush` files in a folder on the desktop.
#[derive(Clone, Debug, Default)]
pub struct UserBrushes {
pub list: Vec<UserBrush>,
/// The folder mirroring `list`; None keeps the presets in memory only.
pub dir: Option<std::path::PathBuf>,
}
fn same_name(first_name: &str, second_name: &str) -> bool {
first_name.trim().eq_ignore_ascii_case(second_name.trim())
}
/// Two names with the same file stem would share a file.
fn file_key(name: &str) -> String {
sanitize_file_stem(name.trim()).to_ascii_lowercase()
}
impl UserBrushes {
pub fn find(&self, name: &str) -> Option<usize> {
self.list.iter().position(|preset| same_name(&preset.name, name))
}
/// `name` belongs to a built-in or to a user brush other than `skip_index` (or shares its file).
pub(super) fn taken(&self, name: &str, skip_index: Option<usize>) -> bool {
if find_preset(name).is_some() {
return true;
}
let candidate_file_key = file_key(name);
self.list
.iter()
.enumerate()
.any(|(index, preset)| Some(index) != skip_index && (same_name(&preset.name, name) || file_key(&preset.name) == candidate_file_key))
}
#[cfg(not(target_arch = "wasm32"))]
fn file(&self, name: &str) -> Option<std::path::PathBuf> {
self.dir.as_ref().map(|directory| directory.join(format!("{}.{BRUSH_EXT}", sanitize_file_stem(name.trim()))))
}
/// The file a preset named `name` that was never written would have.
#[cfg(not(target_arch = "wasm32"))]
pub(super) fn file_of(&self, name: &str) -> Option<std::path::PathBuf> {
self.file(name)
}
#[cfg(target_arch = "wasm32")]
pub(super) fn file_of(&self, _: &str) -> Option<std::path::PathBuf> {
None
}
/// Mirror `brush` to the folder under its name's file and return that file; `old_file` is
/// the file it had before (an overwrite or a rename), which goes once the new one is written.
#[cfg(not(target_arch = "wasm32"))]
pub(super) fn write(&self, brush: &UserBrush, old_file: Option<&std::path::Path>) -> std::result::Result<Option<std::path::PathBuf>, String> {
let (Some(dir), Some(path)) = (&self.dir, self.file(&brush.name)) else {
return Ok(None);
};
let bytes = serde_json::to_vec_pretty(brush).map_err(|error| error.to_string())?;
std::fs::create_dir_all(dir).map_err(|error| format!("cannot create {}: {error}", dir.display()))?;
if self.list.iter().any(|other| {
other.file.as_ref().is_some_and(|source| {
Some(source.as_path()) != old_file && source.file_name().zip(path.file_name()).is_some_and(|(existing, new)| existing.eq_ignore_ascii_case(new))
})
}) {
return Err(format!("{} belongs to another brush preset", path.display()));
}
match std::fs::symlink_metadata(&path) {
Ok(_)
if old_file != Some(path.as_path())
&& !old_file.is_some_and(|old| old.canonicalize().ok().zip(path.canonicalize().ok()).is_some_and(|(old, new)| old == new)) =>
{
return Err(format!("{} already exists", path.display()));
}
Err(error) if error.kind() != std::io::ErrorKind::NotFound => {
return Err(format!("cannot check {}: {error}", path.display()));
}
_ => {}
}
let old_file = old_file.filter(|old| *old != path);
// Rename first because case-only paths may alias on the same file
let case_only = old_file.is_some_and(|old| old.to_string_lossy().eq_ignore_ascii_case(&path.to_string_lossy()));
if let Some(old_path) = old_file.filter(|_| case_only) {
std::fs::rename(old_path, &path).map_err(|error| format!("cannot rename {}: {error}", old_path.display()))?;
}
if let Err(error) = texturecraft_formats::write_atomic(&path, &bytes) {
if let Some(old_path) = old_file.filter(|_| case_only) {
let _ = std::fs::rename(&path, old_path);
}
return Err(format!("cannot write {}: {error}", path.display()));
}
if let Some(old_path) = old_file.filter(|_| !case_only)
&& let Err(error) = remove_file(old_path)
{
let _ = remove_file(&path);
return Err(error);
}
Ok(Some(path))
}
#[cfg(target_arch = "wasm32")]
pub(super) fn write(&self, _: &UserBrush, _: Option<&std::path::Path>) -> std::result::Result<Option<std::path::PathBuf>, String> {
Ok(None)
}
/// Remove `brush`'s file (the one it was read from, else its name's file).
#[cfg(not(target_arch = "wasm32"))]
pub(super) fn delete(&self, brush: &UserBrush) -> std::result::Result<(), String> {
match brush.file.clone().or_else(|| self.file(&brush.name)) {
Some(path) => remove_file(&path),
None => Ok(()),
}
}
#[cfg(target_arch = "wasm32")]
pub(super) fn delete(&self, _: &UserBrush) -> std::result::Result<(), String> {
Ok(())
}
}
/// Remove `path`; a file that is already gone is fine, any other error is reported.
#[cfg(not(target_arch = "wasm32"))]
fn remove_file(path: &std::path::Path) -> std::result::Result<(), String> {
match std::fs::remove_file(path) {
Err(error) if error.kind() != std::io::ErrorKind::NotFound => Err(format!("cannot remove {}: {error}", path.display())),
_ => Ok(()),
}
}
+12 -6
View File
@@ -379,6 +379,8 @@ pub struct Session {
pub(crate) polygon_fill_drag: Option<crate::polygon_fill_drag::PolygonFillDrag>,
/// The user's export presets (kept when another project opens).
pub export_presets: crate::preset_cmds::UserPresets,
/// The user's brush presets (kept when another project opens).
pub brush_presets: crate::brush_preset_cmds::UserBrushes,
/// The user's project templates (kept when another project opens).
pub templates: crate::template_cmds::UserTemplates,
}
@@ -386,15 +388,17 @@ pub struct Session {
impl Session {
/// A session for `project` on `mesh` (its sets must reference mesh materials), with UV-tiled sets' UVs mapped into their atlas ([`Session::source_mesh`])
pub fn new(doc: Document, mesh: Mesh, mesh_source: Option<(String, Vec<u8>)>) -> Result<Session> {
mesh.validate().map_err(|e| EngineError::Other(e.to_string()))?;
mesh.validate().map_err(|error| EngineError::Other(error.to_string()))?;
let source = Arc::new(mesh);
let mesh = tiled_mesh(&source, &doc.project);
let bvh = Bvh::new(&mesh);
let mut camera = OrbitCamera { yaw: 0.6, pitch: 0.25, ..OrbitCamera::default() };
let (lo, hi) = mesh.bounds();
camera.frame(lo, hi);
let caches = doc.project.texture_sets.iter().map(|ts| SetCache::new(&mesh, ts)).collect();
let selected = doc.project.texture_sets.iter().enumerate().filter_map(|(i, ts)| ts.stack.last().map(|id| (i, *id))).collect();
let (bounds_min, bounds_max) = mesh.bounds();
camera.frame(bounds_min, bounds_max);
let caches = doc.project.texture_sets.iter().map(|texture_set| SetCache::new(&mesh, texture_set)).collect();
let selected = doc.project.texture_sets.iter().enumerate().filter_map(|(index, texture_set)| texture_set.stack.last().map(|id| (index, *id))).collect();
Ok(Session {
doc,
mesh_id: next_mesh_id(),
@@ -432,6 +436,7 @@ impl Session {
depth_cache: None,
polygon_fill_drag: None,
export_presets: Default::default(),
brush_presets: Default::default(),
templates: Default::default(),
})
}
@@ -445,13 +450,14 @@ impl Session {
}
/// Replace this session with `next` (another project), keeping the viewport size and the
/// user's export presets and project templates.
/// user's brush presets, export presets and project templates.
pub fn switch_to(&mut self, mut next: Session) {
// Invalidate caches even when both projects were loaded with the same revision
next.revision = self.revision.wrapping_add(1);
next.viewport = self.viewport;
next.export_presets = std::mem::take(&mut self.export_presets);
next.brush_presets = std::mem::take(&mut self.brush_presets);
next.templates = std::mem::take(&mut self.templates);
*self = next;
}
-138
View File
@@ -1,138 +0,0 @@
//! Saving the current brush as a preset (Properties › Brush › Preset); presets show on the shelf's Brushes tab
use egui::Ui;
use serde_json::json;
use std::path::Path;
use texturecraft_engine::brush_preset_cmds::BRUSH_EXT;
use crate::TextureCraftApp;
use crate::i18n::tr;
/// The preset name field's width in points
const NAME_WIDTH: f32 = 110.0;
/// A name field and a button that saves the current brush under that name
pub(crate) fn row(app: &mut TextureCraftApp, ui: &mut Ui) {
let dir = crate::user_dir("brushes");
let name_id = ui.make_persistent_id("brush_preset_name");
let confirm_id = ui.make_persistent_id("brush_preset_overwrite");
let mut new_name: String = ui.data_mut(|data| data.get_temp(name_id)).unwrap_or_default();
let mut pending_path: Option<std::path::PathBuf> = ui.data_mut(|data| data.get_temp(confirm_id));
ui.horizontal(|ui| {
ui.add(egui::TextEdit::singleline(&mut new_name).hint_text(tr("Brush name")).desired_width(NAME_WIDTH));
if ui.add_enabled(!new_name.trim().is_empty(), egui::Button::new(tr("Save current brush"))).clicked() {
let path = dir.join(format!("{}.{BRUSH_EXT}", preset_file_stem(new_name.trim())));
match std::fs::symlink_metadata(&path) {
Ok(_) => pending_path = Some(path),
Err(error) if error.kind() == std::io::ErrorKind::NotFound => {
if save_brush(app, &dir, &path) {
new_name.clear();
}
}
Err(_) => pending_path = Some(path),
}
}
});
if let Some(path) = pending_path.clone() {
let mut replace = false;
let mut cancel = false;
egui::Window::new(tr("Replace"))
.id(ui.make_persistent_id("brush_preset_replace_dialog"))
.collapsible(false)
.resizable(false)
.anchor(egui::Align2::CENTER_CENTER, egui::Vec2::ZERO)
.show(ui.ctx(), |ui| {
ui.label(path.file_name().and_then(|name| name.to_str()).unwrap_or_default());
ui.horizontal(|ui| {
replace = ui.button(tr("Replace")).clicked();
cancel = ui.button(tr("Cancel")).clicked();
});
});
if replace {
if save_brush(app, &dir, &path) {
new_name.clear();
}
pending_path = None;
} else if cancel {
pending_path = None;
}
}
ui.data_mut(|data| {
data.insert_temp(name_id, new_name);
data.insert_temp(confirm_id, pending_path);
});
}
/// Preserve Unicode names and encode filename punctuation without collisions
fn preset_file_stem(name: &str) -> String {
let mut stem = String::new();
// Six digits cover every Unicode scalar and separate adjacent escapes
for character in name.chars() {
if character.is_alphanumeric() || character == '-' || character == '_' || character == ' ' {
stem.push(character);
} else {
stem.push_str(&format!("~{:06X}", character as u32));
}
}
let uppercase = stem.to_ascii_uppercase();
if matches!(
uppercase.as_str(),
"CON"
| "PRN"
| "AUX"
| "NUL"
| "COM1"
| "COM2"
| "COM3"
| "COM4"
| "COM5"
| "COM6"
| "COM7"
| "COM8"
| "COM9"
| "LPT1"
| "LPT2"
| "LPT3"
| "LPT4"
| "LPT5"
| "LPT6"
| "LPT7"
| "LPT8"
| "LPT9"
) {
stem.insert_str(0, "brush-");
}
stem
}
/// Save a preset and invalidate cached tiles only when the write succeeds
fn save_brush(app: &mut TextureCraftApp, dir: &Path, path: &Path) -> bool {
// A folder that cannot be made is reported by the save command
let _ = std::fs::create_dir_all(dir);
if app.run("brush.preset.save", json!({"path": path.display().to_string()})).is_none() {
return false;
}
app.brushes = None;
app.thumbs.forget_saved_files();
true
}
#[cfg(test)]
mod tests {
use super::preset_file_stem;
#[test]
fn distinct_unicode_brush_names_have_distinct_safe_file_stems() {
assert_ne!(preset_file_stem("水彩"), preset_file_stem("油画"));
assert_ne!(preset_file_stem("a/b"), preset_file_stem("a~00002Fb"));
assert_eq!(preset_file_stem("水彩"), "水彩");
assert!(!preset_file_stem("a/b").contains('/'));
assert_eq!(preset_file_stem("CON"), "brush-CON");
}
}
+34 -26
View File
@@ -72,12 +72,12 @@ pub(crate) fn encode_png(w: u32, h: u32, rgba: Vec<u8>) -> Option<(u32, u32, Vec
Some((w, h, png))
}
pub fn handle(app: &mut TextureCraftApp, ctx: &egui::Context, method: &str, p: &Value) -> Value {
pub fn handle(app: &mut TextureCraftApp, ctx: &egui::Context, method: &str, params: &Value) -> Value {
app.ui.prefs.apply_resource_limits();
match method {
"ping" => ok(json!("pong")),
"ui.resize" => {
let size = |k: &str| p.get(k).and_then(Value::as_f64).filter(|v| v.is_finite()).map(|v| v.clamp(640.0, 7680.0) as f32);
let size = |key: &str| params.get(key).and_then(Value::as_f64).filter(|value| value.is_finite()).map(|value| value.clamp(640.0, 7680.0) as f32);
match (size("width"), size("height")) {
(Some(w), Some(h)) => {
ctx.send_viewport_cmd(egui::ViewportCommand::Maximized(false));
@@ -88,38 +88,44 @@ pub fn handle(app: &mut TextureCraftApp, ctx: &egui::Context, method: &str, p: &
}
}
"debug.frames" => ok(app.profiler.report()),
"debug.paintTest" => match crate::profile::start_paint_test(app, p) {
"debug.paintTest" => match crate::profile::start_paint_test(app, params) {
Ok(()) => ok(Value::Null),
Err(e) => err(e),
Err(error) => err(error),
},
"command.run" => {
let Some(id) = p.get("id").and_then(Value::as_str) else { return err("`id` is required") };
let params = p.get("params").cloned().unwrap_or(Value::Null);
match texturecraft_engine::execute(&mut app.session, id, &params) {
Ok(v) => ok(v),
Err(e) => err(e),
let Some(id) = params.get("id").and_then(Value::as_str) else { return err("`id` is required") };
let command_params = params.get("params").cloned().unwrap_or(Value::Null);
match texturecraft_engine::execute(&mut app.session, id, &command_params) {
Ok(value) => {
if matches!(id, "brush.preset.store" | "brush.preset.rename" | "brush.preset.delete") {
app.thumbs.forget_saved_files();
}
ok(value)
}
Err(error) => err(error),
}
}
"command.list" => ok(texturecraft_engine::commands::list(&app.session, p.get("filter").and_then(Value::as_str))),
"command.list" => ok(texturecraft_engine::commands::list(&app.session, params.get("filter").and_then(Value::as_str))),
"session.inspect" => ok(texturecraft_engine::inspect::session(&app.session)),
"ui.inspect" => {
let r = app.viewport_rect;
let viewport = app.viewport_rect;
ok(json!({
"state": app.ui,
"viewport": [r.min.x, r.min.y, r.width(), r.height()],
"viewport": [viewport.min.x, viewport.min.y, viewport.width(), viewport.height()],
"fps": app.fps,
"uiMs": app.ui_ms,
"titleBar": app.title_bar.name(),
"baking": app.bake_progress(),
"bakeStatus": app.bake_status(),
"bakePreview": texturecraft_engine::bake_preview::preview_json(&app.session),
"toasts": app.toasts.iter().map(|t| json!({"text": t.text, "error": t.error})).collect::<Vec<_>>(),
"toasts": app.toasts.iter().map(|toast| json!({"text": toast.text, "error": toast.error})).collect::<Vec<_>>(),
}))
}
"ui.bake.start" => {
// Bake in the background like the Bake button: the 3D view shows the maps as they finish
let count = app.session.doc.project.texture_sets.len();
let sets: Vec<usize> = match p.get("ts") {
let sets: Vec<usize> = match params.get("ts") {
Some(value) => match serde_json::from_value::<Vec<usize>>(if value.is_array() { value.clone() } else { json!([value]) }) {
Ok(list) if list.iter().all(|&index| index < count) => list,
_ => return err(format!("`ts` must be texture set indices below {count}")),
@@ -154,39 +160,41 @@ pub fn handle(app: &mut TextureCraftApp, ctx: &egui::Context, method: &str, p: &
"ui.menu.list" => ok(json!(
crate::menus::CATALOG
.iter()
.filter(|i| i.label != "-")
.map(|i| json!({
"menu": i.menu, "submenu": i.sub, "label": i.label, "id": i.id, "shortcut": crate::keymap::shortcut_of(&app.ui.keymap, i.id),
"implemented": crate::menus::implemented(i.id), "enabled": crate::menus::enabled(app, i.id),
.filter(|item| item.label != "-")
.map(|item| json!({
"menu": item.menu, "submenu": item.sub, "label": item.label, "id": item.id, "shortcut": crate::keymap::shortcut_of(&app.ui.keymap, item.id),
"implemented": crate::menus::implemented(item.id), "enabled": crate::menus::enabled(app, item.id),
}))
.collect::<Vec<_>>()
)),
"ui.menu.invoke" => {
let Some(id) = p.get("id").and_then(Value::as_str) else { return err("`id` is required") };
let Some(id) = params.get("id").and_then(Value::as_str) else { return err("`id` is required") };
if !crate::menus::implemented(id) {
return err(format!("menu item `{id}` is not implemented"));
}
crate::menus::invoke(app, ctx, id);
ok(Value::Null)
}
"ui.set" => {
let mut cur = serde_json::to_value(&app.ui).unwrap_or(Value::Null);
if let (Some(obj), Some(patch)) = (cur.as_object_mut(), p.as_object()) {
for (k, v) in patch {
obj.insert(k.clone(), v.clone());
let mut current_state = serde_json::to_value(&app.ui).unwrap_or(Value::Null);
if let (Some(object), Some(patch)) = (current_state.as_object_mut(), params.as_object()) {
for (key, value) in patch {
object.insert(key.clone(), value.clone());
}
}
match serde_json::from_value(cur) {
match serde_json::from_value(current_state) {
Ok(ui) => {
app.ui = ui;
app.ui.prefs.apply_resource_limits();
ok(Value::Null)
}
Err(e) => err(format!("invalid UI state: {e}")),
Err(error) => err(format!("invalid UI state: {error}")),
}
}
"viewport.screenshot" => {
let view = if p.get("view").and_then(Value::as_str) == Some("2d") { crate::viewport::VIEW_2D } else { crate::viewport::VIEW_3D };
let view = if params.get("view").and_then(Value::as_str) == Some("2d") { crate::viewport::VIEW_2D } else { crate::viewport::VIEW_3D };
match screenshot(app, view) {
Some((w, h, png)) => ok(json!({ "width": w, "height": h, "png": base64::engine::general_purpose::STANDARD.encode(png) })),
None => err("no rendered view to capture yet"),
+33 -5
View File
@@ -1748,6 +1748,34 @@ fn path_section(app: &mut TextureCraftApp, ui: &mut Ui) {
ui.label(RichText::new(hint).size(10.5).color(tk.text_dim));
}
/// Popover for built-in and saved brush presets
fn brush_presets_popover(app: &mut TextureCraftApp, ui: &mut Ui) {
let response = ui.button(format!("{} {}", ic::PAINT_BRUSH_BROAD, tr("Brush presets")));
let popup_id = ui.make_persistent_id("brush_presets_popup");
if response.clicked() {
egui::Popup::toggle_id(ui.ctx(), popup_id);
}
egui::Popup::from_response(&response).id(popup_id).open_memory(None).close_behavior(egui::PopupCloseBehavior::CloseOnClickOutside).show(|ui| {
ui.set_min_width(230.0);
egui::ScrollArea::vertical().max_height(380.0).show(ui, |ui| {
let mut category = "";
for preset in texturecraft_engine::paint::presets::PRESETS.iter() {
if preset.category != category {
category = preset.category;
ui.label(caption(category));
}
if ui.selectable_label(false, preset.label).on_hover_text(tr("Use this brush (keeps its size)")).clicked() {
app.run("brush.preset.apply", json!({"preset": preset.id}));
}
}
ui.separator();
crate::shelf::user_brushes(app, ui, "");
});
});
}
/// Width of the label column in polygon fill's properties
const POLYGON_FILL_LABEL_WIDTH: f32 = 108.0;
@@ -1850,9 +1878,13 @@ fn polygon_fill_paints_mask(app: &TextureCraftApp) -> Result<bool, String> {
const HINT_TEXT_SIZE: f32 = 10.5;
fn brush_section(app: &mut TextureCraftApp, ui: &mut Ui) {
ui.horizontal(|ui| {
ui.label(caption(tr("Brush")));
brush_presets_popover(app, ui);
});
let brush = &mut app.session.tool.brush;
let defaults = BrushSettings::default();
ui.label(caption(tr("Brush")));
let hint = tr("Ctrl+right-drag in a view sets the size and hardness, Ctrl+left-drag the flow and angle.");
ui.label(RichText::new(hint).size(HINT_TEXT_SIZE).color(Tokens::get(ui.ctx()).text_dim));
@@ -1970,10 +2002,6 @@ fn brush_section(app: &mut TextureCraftApp, ui: &mut Ui) {
}
*brush = brush.sanitized();
// Presets are files, which the browser doesn't have
#[cfg(not(target_arch = "wasm32"))]
section(ui, "sec_brush_preset", tr("Preset"), false, |ui| crate::brush_preset_save::row(app, ui));
}
/// One alpha in the picker: a 52×64 tile with the shape drawn by `paint` and a label.
+5
View File
@@ -1045,6 +1045,11 @@ pub const TABLE: &[(&str, &str)] = &[
("Value Bounds Max", "الحد الأقصى للقيمة"),
("Value Bounds Min", "الحد الأدنى للقيمة"),
("Vertex Color", "لون الرأس"),
("Brush presets", "إعدادات الفرشاة المسبقة"),
("Use this brush (with its size)", "استخدام هذه الفرشاة (مع حجمها)"),
("Rename this brush", "إعادة تسمية هذه الفرشاة"),
("Replace with the current brush", "استبدال بالفرشاة الحالية"),
("Delete this brush", "حذف هذه الفرشاة"),
("Add to the material library", "إضافة إلى مكتبة المواد"),
("Added {name} to the library", "تمت إضافة {name} إلى المكتبة"),
("Automatic", "تلقائي"),
+5
View File
@@ -1085,6 +1085,11 @@ pub const TABLE: &[(&str, &str)] = &[
("Value Bounds Max", "Maximaler Grenzwert"),
("Value Bounds Min", "Minimaler Grenzwert"),
("Vertex Color", "Scheitelpunktfarbe"),
("Brush presets", "Pinselvorgaben"),
("Use this brush (with its size)", "Diesen Pinsel verwenden (mit Größe)"),
("Rename this brush", "Diesen Pinsel umbenennen"),
("Replace with the current brush", "Durch den aktuellen Pinsel ersetzen"),
("Delete this brush", "Diesen Pinsel löschen"),
("Add to the material library", "Zur Materialbibliothek hinzufügen"),
("Added {name} to the library", "{name} zur Bibliothek hinzugefügt"),
("Automatic", "Automatisch"),
+5
View File
@@ -1073,6 +1073,11 @@ pub const TABLE: &[(&str, &str)] = &[
("Value Bounds Max", "Límite máximo"),
("Value Bounds Min", "Límite mínimo"),
("Vertex Color", "Color de vértice"),
("Brush presets", "Ajustes de pincel"),
("Use this brush (with its size)", "Usar este pincel (con su tamaño)"),
("Rename this brush", "Renombrar este pincel"),
("Replace with the current brush", "Reemplazar con el pincel actual"),
("Delete this brush", "Eliminar este pincel"),
("Add to the material library", "Añadir a la biblioteca de materiales"),
("Added {name} to the library", "{name} añadido a la biblioteca"),
("Automatic", "Automático"),
+5
View File
@@ -1097,6 +1097,11 @@ pub const TABLE: &[(&str, &str)] = &[
("Value Bounds Max", "Borne maximale"),
("Value Bounds Min", "Borne minimale"),
("Vertex Color", "Couleur des sommets"),
("Brush presets", "Préréglages de pinceau"),
("Use this brush (with its size)", "Utiliser ce pinceau (avec sa taille)"),
("Rename this brush", "Renommer ce pinceau"),
("Replace with the current brush", "Remplacer par le pinceau actuel"),
("Delete this brush", "Supprimer ce pinceau"),
("Add to the material library", "Ajouter à la bibliothèque de matériaux"),
("Added {name} to the library", "{name} ajouté à la bibliothèque"),
("Automatic", "Automatique"),
+5
View File
@@ -1079,6 +1079,11 @@ pub const TABLE: &[(&str, &str)] = &[
("Value Bounds Max", "Limite massimo"),
("Value Bounds Min", "Limite minimo"),
("Vertex Color", "Colore dei vertici"),
("Brush presets", "Preset pennello"),
("Use this brush (with its size)", "Usa questo pennello (con la sua dimensione)"),
("Rename this brush", "Rinomina questo pennello"),
("Replace with the current brush", "Sostituisci con il pennello attuale"),
("Delete this brush", "Elimina questo pennello"),
("Add to the material library", "Aggiungi alla libreria dei materiali"),
("Added {name} to the library", "{name} aggiunto alla libreria"),
("Automatic", "Automatico"),
+5
View File
@@ -1067,6 +1067,11 @@ pub const TABLE: &[(&str, &str)] = &[
("Value Bounds Max", "値の上限"),
("Value Bounds Min", "値の下限"),
("Vertex Color", "頂点カラー"),
("Brush presets", "ブラシプリセット"),
("Use this brush (with its size)", "このブラシを使う(サイズも)"),
("Rename this brush", "このブラシの名前を変更"),
("Replace with the current brush", "現在のブラシで置き換え"),
("Delete this brush", "このブラシを削除"),
("Add to the material library", "マテリアルライブラリに追加"),
("Added {name} to the library", "{name} をライブラリに追加しました"),
("Automatic", "自動"),
+5
View File
@@ -1055,6 +1055,11 @@ pub const TABLE: &[(&str, &str)] = &[
("Value Bounds Max", "값 상한"),
("Value Bounds Min", "값 하한"),
("Vertex Color", "정점 색상"),
("Brush presets", "브러시 프리셋"),
("Use this brush (with its size)", "이 브러시 사용 (크기 포함)"),
("Rename this brush", "이 브러시 이름 바꾸기"),
("Replace with the current brush", "현재 브러시로 바꾸기"),
("Delete this brush", "이 브러시 삭제"),
("Add to the material library", "머티리얼 라이브러리에 추가"),
("Added {name} to the library", "{name}을(를) 라이브러리에 추가했습니다"),
("Automatic", "자동"),
+5
View File
@@ -1070,6 +1070,11 @@ pub const TABLE: &[(&str, &str)] = &[
("Value Bounds Max", "Limite máximo"),
("Value Bounds Min", "Limite mínimo"),
("Vertex Color", "Cor do vértice"),
("Brush presets", "Predefinições de pincel"),
("Use this brush (with its size)", "Usar este pincel (com o tamanho)"),
("Rename this brush", "Renomear este pincel"),
("Replace with the current brush", "Substituir pelo pincel atual"),
("Delete this brush", "Excluir este pincel"),
("Add to the material library", "Adicionar à biblioteca de materiais"),
("Added {name} to the library", "{name} adicionado à biblioteca"),
("Automatic", "Automático"),
+5
View File
@@ -1010,6 +1010,11 @@ pub const TABLE: &[(&str, &str)] = &[
("Value Bounds Max", "值上限"),
("Value Bounds Min", "值下限"),
("Vertex Color", "顶点颜色"),
("Brush presets", "笔刷预设"),
("Use this brush (with its size)", "使用此笔刷(含大小)"),
("Rename this brush", "重命名此笔刷"),
("Replace with the current brush", "用当前笔刷替换"),
("Delete this brush", "删除此笔刷"),
("Add to the material library", "添加到材质库"),
("Added {name} to the library", "已将 {name} 添加到库"),
("Automatic", "自动"),
+17 -10
View File
@@ -10,8 +10,6 @@
mod bake_job;
pub mod bake_mode;
mod bake_scene;
#[cfg(not(target_arch = "wasm32"))]
mod brush_preset_save;
mod color_selection_editor;
pub mod control;
mod decal_drop;
@@ -153,8 +151,6 @@ pub struct TextureCraftApp {
pub fps: f32,
/// User smart materials found in the library folder (refreshed on demand).
pub library: Option<Vec<std::path::PathBuf>>,
/// User brush presets found in the brushes folder (refreshed on demand).
pub brushes: Option<Vec<std::path::PathBuf>>,
/// Rendering mode's path tracer.
pub render: render_mode::RenderView,
/// Smoothed CPU time spent building the UI per frame (ms).
@@ -247,7 +243,6 @@ impl TextureCraftApp {
ui_ms: 0.0,
profiler: profile::Profiler::default(),
library: None,
brushes: None,
render: render_mode::RenderView::default(),
last_paint_point: None,
last_paint_uv: None,
@@ -290,6 +285,11 @@ impl TextureCraftApp {
let skipped = app.session.load_templates(user_dir("templates"));
app.session.log.extend(skipped.into_iter().map(|warning| format!("Project template skipped: {warning}")));
// Load presets before control commands can access the session
for warning in app.session.load_brush_presets(user_dir("brushes")) {
app.toast(warning, true);
}
}
app
@@ -302,24 +302,31 @@ impl TextureCraftApp {
// Going to a saved camera glides there; the control channel and CLI jump straight away
let glide_from = (id.starts_with("camera.select") || id.starts_with("camera.bookmark")).then_some(self.session.camera);
match texturecraft_engine::execute(&mut self.session, id, &params) {
Ok(v) => {
Ok(value) => {
if matches!(id, "brush.preset.store" | "brush.preset.rename" | "brush.preset.delete") {
self.thumbs.forget_saved_files();
}
// A pending dialog must not import its old source into the replacement project
if matches!(id, "file.open" | "file.close" | "project.new" | "project.sample") {
self.pbr_import = None;
}
// The empty state has no baking or rendering to show
if id == "file.close" {
self.ui.mode = state::Mode::Painting;
self.ui.windows.export = false;
}
if let Some(from) = glide_from.filter(|f| *f != self.session.camera) {
if let Some(from) = glide_from.filter(|camera| *camera != self.session.camera) {
self.camera_glide = Some(CameraGlide { from, to: self.session.camera, start: self.last_time });
self.session.camera = from;
}
Some(v)
Some(value)
}
Err(e) => {
self.toast(e.to_string(), true);
Err(error) => {
self.toast(error.to_string(), true);
None
}
}
+97 -31
View File
@@ -234,7 +234,6 @@ pub fn body(app: &mut TextureCraftApp, ui: &mut Ui) {
let ctx = ui.ctx().clone();
let filter = app.ui.shelf_filter.to_lowercase();
scan_library(app);
scan_brushes(app);
let all = ShelfEntry::all(app);
let paths = crate::shelf_folders::with_every_library(crate::shelf_folders::paths(&all));
@@ -267,6 +266,9 @@ pub fn body(app: &mut TextureCraftApp, ui: &mut Ui) {
let tab = app.ui.shelf_tab;
let shown_tab = TABS.get(tab).map(|(shown, _, _)| *shown);
let show_user_brushes = crate::shelf_tabs::shows(tab, Tab::Brushes)
&& folder.len() <= 2
&& folder.iter().zip([crate::shelf_entry::USER, "Brushes"]).all(|(selected, part)| selected == part);
let mut entries: Vec<ShelfEntry> = matching.into_iter().filter(|entry| crate::shelf_tabs::shows(tab, entry.tab())).collect();
entries.sort_by_cached_key(|entry| entry.label().to_lowercase());
@@ -286,14 +288,15 @@ pub fn body(app: &mut TextureCraftApp, ui: &mut Ui) {
// Saved smart materials are files in the user's library, without folders of their own
let saved_materials = in_user_library && shown_tab.is_none_or(|shown| shown == Tab::Smart);
grid(app, ui, &ctx, &entries, grid_rect.height(), saved_materials, &filter);
grid(app, ui, &entries, grid_rect.height(), saved_materials, show_user_brushes, &filter);
});
ui.scope_builder(egui::UiBuilder::new().max_rect(toolbar_rect), |ui| crate::shelf_toolbar::show(app, ui));
drag_preview(&ctx);
}
/// The tiles of `entries` in a scroll area `height` high, then the saved smart materials when `saved_materials`
fn grid(app: &mut TextureCraftApp, ui: &mut Ui, ctx: &egui::Context, entries: &[ShelfEntry], height: f32, saved_materials: bool, filter: &str) {
/// The tiles of `entries` in a scroll area `height` high, then user assets when selected
fn grid(app: &mut TextureCraftApp, ui: &mut Ui, entries: &[ShelfEntry], height: f32, saved_materials: bool, show_user_brushes: bool, filter: &str) {
let ctx = ui.ctx().clone();
let view = app.ui.shelf_view;
let selected: Option<(String, String)> = ctx.data(|data| data.get_temp(egui::Id::unique(SELECTED_TILE)));
egui::ScrollArea::vertical()
@@ -302,15 +305,20 @@ fn grid(app: &mut TextureCraftApp, ui: &mut Ui, ctx: &egui::Context, entries: &[
.scroll_bar_visibility(egui::scroll_area::ScrollBarVisibility::AlwaysVisible)
.max_height(height)
.show(ui, |ui| {
tiles(ui, |ui| {
for entry in entries {
let is_selected = selected.as_ref().is_some_and(|(kind, id)| entry.identity() == (kind.as_str(), id.as_str()));
entry_tile(app, ui, ctx, entry, view, is_selected);
ui.with_layout(egui::Layout::top_down(egui::Align::Min), |ui| {
tiles(ui, |ui| {
for entry in entries {
let is_selected = selected.as_ref().is_some_and(|(kind, id)| entry.identity() == (kind.as_str(), id.as_str()));
entry_tile(app, ui, &ctx, entry, view, is_selected);
}
});
if show_user_brushes {
user_brushes(app, ui, filter);
}
if saved_materials {
library(app, ui, filter);
}
});
if saved_materials {
library(app, ui, filter);
}
});
}
@@ -440,25 +448,6 @@ fn library(app: &mut TextureCraftApp, ui: &mut Ui, filter: &str) {
#[cfg(target_arch = "wasm32")]
fn library(_: &mut TextureCraftApp, _: &mut Ui, _: &str) {}
/// Read the user's saved brush presets (desktop brushes folder) unless they are already listed
#[cfg(not(target_arch = "wasm32"))]
fn scan_brushes(app: &mut TextureCraftApp) {
use texturecraft_engine::brush_preset_cmds::BRUSH_EXT;
if app.brushes.is_some() {
return;
}
let mut files: Vec<std::path::PathBuf> = std::fs::read_dir(crate::user_dir("brushes"))
.map(|dir| dir.flatten().map(|entry| entry.path()).filter(|path| path.extension().is_some_and(|extension| extension == BRUSH_EXT)).collect())
.unwrap_or_default();
files.sort();
app.brushes = Some(files);
}
#[cfg(target_arch = "wasm32")]
fn scan_brushes(_: &mut TextureCraftApp) {}
/// The tile of `entry`, outlined when `selected`: a click applies it, an image resource has a context menu
fn entry_tile(app: &mut TextureCraftApp, ui: &mut Ui, ctx: &egui::Context, entry: &ShelfEntry, view: ShelfView, selected: bool) {
// An image removed this frame has nothing to show
@@ -476,7 +465,7 @@ fn entry_tile(app: &mut TextureCraftApp, ui: &mut Ui, ctx: &egui::Context, entry
&mut app.thumbs,
texture.as_ref(),
|thumbs| match entry {
ShelfEntry::SavedBrush(path) => Some(thumbs.saved_brush_preview(path, &session.images)),
ShelfEntry::SavedBrush { path: Some(path), .. } => Some(thumbs.saved_brush_preview(path, &session.images)),
_ => entry.preview(session),
},
entry.label(),
@@ -634,6 +623,83 @@ fn hover_preview(ui: &mut Ui, small: Option<&egui::TextureHandle>, big: Option<&
});
}
/// Manage the user brush library through engine commands
pub(crate) fn user_brushes(app: &mut TextureCraftApp, ui: &mut Ui, filter: &str) {
let names: Vec<String> = app.session.brush_presets.list.iter().map(|preset| preset.name.clone()).filter(|name| matches(filter, &[name])).collect();
if !filter.is_empty() && names.is_empty() {
return;
}
header(ui, tr("My brushes"));
let rename_id = ui.make_persistent_id("brush_preset_rename");
let mut renaming: Option<(String, String)> = ui.data_mut(|data| data.get_temp(rename_id));
for name in names {
ui.horizontal(|ui| {
if renaming.as_ref().is_some_and(|(old, _)| *old == name) {
let Some((old_name, new_name)) = renaming.as_mut() else { return };
let edit = ui.add(egui::TextEdit::singleline(new_name).desired_width(120.0));
let (confirmed, cancelled) =
(edit.lost_focus() && ui.input(|input| input.key_pressed(egui::Key::Enter)), ui.input(|input| input.key_pressed(egui::Key::Escape)));
if !edit.has_focus() && !confirmed && !cancelled {
edit.request_focus();
}
if confirmed {
// A failed rename is reported by the command; the row goes back to its name either way
app.run("brush.preset.rename", json!({"name": old_name, "to": new_name}));
}
if confirmed || cancelled {
renaming = None;
}
return;
}
let use_button =
ui.add(egui::Button::selectable(false, format!("{} {name}", ic::PAINT_BRUSH_BROAD))).on_hover_text(tr("Use this brush (with its size)"));
if use_button.clicked() {
app.run("brush.preset.apply", json!({"preset": name}));
}
ui.with_layout(egui::Layout::right_to_left(egui::Align::Center), |ui| {
if ui.small_button(ic::TRASH).on_hover_text(tr("Delete this brush")).clicked() {
app.run("brush.preset.delete", json!({"name": name}));
}
if ui.small_button(ic::ARROWS_CLOCKWISE).on_hover_text(tr("Replace with the current brush")).clicked() {
app.run("brush.preset.store", json!({"name": name, "overwrite": true}));
}
if ui.small_button(ic::PENCIL_SIMPLE).on_hover_text(tr("Rename this brush")).clicked() {
renaming = Some((name.clone(), name.clone()));
}
});
});
}
ui.data_mut(|data| match renaming {
Some(rename) => {
data.insert_temp(rename_id, rename);
}
None => {
data.remove_temp::<(String, String)>(rename_id);
}
});
ui.horizontal(|ui| {
let name_id = ui.make_persistent_id("brush_preset_name");
let mut new_name: String = ui.data_mut(|data| data.get_temp(name_id)).unwrap_or_default();
ui.add(egui::TextEdit::singleline(&mut new_name).hint_text(tr("Brush name")).desired_width(110.0));
if ui.add_enabled(!new_name.trim().is_empty(), egui::Button::new(tr("Save current brush"))).clicked()
&& app.run("brush.preset.store", json!({"name": new_name})).is_some()
{
new_name.clear();
}
ui.data_mut(|data| data.insert_temp(name_id, new_name));
});
ui.add_space(6.0);
}
#[cfg(test)]
mod tests {
use super::*;
+29 -16
View File
@@ -17,9 +17,6 @@ use crate::i18n::tr;
use crate::shelf::{Asset, Tab, apply};
use crate::shelf_preview::ShelfPreview;
/// The name of a saved brush whose file name isn't text
const SAVED_BRUSH_NAME: &str = "brush";
/// Probes per side of the grid that compares a procedural under two seeds, off the pattern's grid lines
const SEED_PROBES: usize = 4;
const SEED_PROBE_OFFSET: f32 = 0.13;
@@ -39,8 +36,12 @@ pub(crate) enum ShelfEntry {
SmartMask(&'static SmartMask),
Filter(&'static FilterDef),
Brush(&'static BrushPreset),
/// A brush preset file the user saved
SavedBrush(PathBuf),
/// A brush preset the user saved in this session or on disk
SavedBrush {
path: Option<PathBuf>,
name: String,
index: usize,
},
Alpha(&'static LibraryAlpha),
Procedural(ProceduralKind),
/// A built-in lighting environment, by name
@@ -61,7 +62,11 @@ impl ShelfEntry {
.chain(alphas::library().iter().map(ShelfEntry::Alpha))
.chain(ProceduralKind::ALL.into_iter().map(ShelfEntry::Procedural))
.chain(ENVIRONMENTS.into_iter().map(ShelfEntry::Environment));
let saved = app.brushes.iter().flatten().cloned().map(ShelfEntry::SavedBrush);
let saved = app.session.brush_presets.list.iter().enumerate().map(|(index, preset)| ShelfEntry::SavedBrush {
path: preset.file.clone(),
name: preset.name.clone(),
index,
});
let images = app.session.doc.resources.keys().filter(|name| app.session.images.contains_key(*name)).cloned().map(ShelfEntry::Image);
built_in.chain(saved).chain(images).collect()
}
@@ -73,7 +78,7 @@ impl ShelfEntry {
ShelfEntry::Material(_) => Tab::Materials,
ShelfEntry::SmartMask(_) => Tab::Masks,
ShelfEntry::Filter(_) => Tab::Filters,
ShelfEntry::Brush(_) | ShelfEntry::SavedBrush(_) => Tab::Brushes,
ShelfEntry::Brush(_) | ShelfEntry::SavedBrush { .. } => Tab::Brushes,
ShelfEntry::Alpha(_) => Tab::Alphas,
ShelfEntry::Procedural(_) => Tab::Textures,
ShelfEntry::Environment(_) => Tab::Environments,
@@ -88,7 +93,7 @@ impl ShelfEntry {
ShelfEntry::SmartMask(mask) => ("mask", mask.id),
ShelfEntry::Filter(filter) => ("filter", filter.id),
ShelfEntry::Brush(preset) => ("brush", preset.id),
ShelfEntry::SavedBrush(path) => ("saved-brush", path.to_str().unwrap_or_default()),
ShelfEntry::SavedBrush { path, name, .. } => ("saved-brush", path.as_ref().and_then(|path| path.to_str()).unwrap_or(name)),
ShelfEntry::Alpha(alpha) => ("alpha", &alpha.id),
ShelfEntry::Procedural(kind) => ("procedural", kind.label()),
ShelfEntry::Environment(name) => ("environment", name),
@@ -104,7 +109,7 @@ impl ShelfEntry {
ShelfEntry::SmartMask(_) => (STARTER, "Smart masks", None),
ShelfEntry::Filter(filter) => (STARTER, "Filters", Some(filter.group)),
ShelfEntry::Brush(preset) => (STARTER, "Brushes", Some(preset.category)),
ShelfEntry::SavedBrush(_) => (USER, "Brushes", None),
ShelfEntry::SavedBrush { .. } => (USER, "Brushes", None),
ShelfEntry::Alpha(alpha) => (STARTER, "Alphas", Some(alpha.category)),
ShelfEntry::Procedural(_) => (STARTER, "Procedurals", None),
ShelfEntry::Environment(_) => (STARTER, "Environments", None),
@@ -123,7 +128,7 @@ impl ShelfEntry {
pub(crate) fn label(&self) -> &str {
match self {
ShelfEntry::Material(material) => material.label,
ShelfEntry::SavedBrush(path) => path.file_stem().and_then(|stem| stem.to_str()).unwrap_or(SAVED_BRUSH_NAME),
ShelfEntry::SavedBrush { name, .. } => name,
ShelfEntry::SmartMask(mask) => mask.label,
ShelfEntry::Filter(filter) => tr(filter.label),
ShelfEntry::Brush(preset) => preset.label,
@@ -138,7 +143,7 @@ impl ShelfEntry {
pub(crate) fn matches(&self, filter: &str) -> bool {
let texts: &[&str] = match self {
ShelfEntry::Material(material) => &[material.label, material.category, material.id],
ShelfEntry::SavedBrush(_) => &[self.label()],
ShelfEntry::SavedBrush { .. } => &[self.label()],
ShelfEntry::SmartMask(mask) => &[mask.label, mask.id],
ShelfEntry::Filter(filter) => &[filter.label, filter.group, filter.id, tr(filter.label), tr(filter.group)],
ShelfEntry::Brush(preset) => &[preset.label, preset.category, preset.id],
@@ -157,7 +162,11 @@ impl ShelfEntry {
ShelfEntry::SmartMask(mask) => app.thumbs.smart_mask(ctx, mask.id),
ShelfEntry::Filter(filter) => app.thumbs.filter(ctx, filter.id),
ShelfEntry::Brush(preset) => app.thumbs.brush_preset(ctx, preset),
ShelfEntry::SavedBrush(path) => app.thumbs.saved_brush(ctx, path, &app.session.images),
ShelfEntry::SavedBrush { path: Some(path), .. } => app.thumbs.saved_brush(ctx, path, &app.session.images),
ShelfEntry::SavedBrush { path: None, name, index } => {
let brush = &app.session.brush_presets.list.get(*index)?.brush;
app.thumbs.session_brush(ctx, name, brush, &app.session.images)
}
ShelfEntry::Alpha(alpha) => app.thumbs.alpha(ctx, alpha),
ShelfEntry::Procedural(kind) => app.thumbs.procedural(ctx, *kind),
ShelfEntry::Environment(name) => app.thumbs.environment(ctx, name),
@@ -175,7 +184,11 @@ impl ShelfEntry {
ShelfEntry::SmartMask(mask) => ShelfPreview::SmartMask(mask.id),
ShelfEntry::Filter(filter) => ShelfPreview::Filter(filter.id),
ShelfEntry::Brush(preset) => ShelfPreview::Brush(preset),
ShelfEntry::SavedBrush(path) => ShelfPreview::saved_brush(path, &session.images),
ShelfEntry::SavedBrush { path: Some(path), .. } => ShelfPreview::saved_brush(path, &session.images),
ShelfEntry::SavedBrush { path: None, name, index } => {
let brush = &session.brush_presets.list.get(*index)?.brush;
ShelfPreview::session_brush(name, brush, &session.images)
}
ShelfEntry::Alpha(alpha) => ShelfPreview::Alpha(alpha),
ShelfEntry::Procedural(kind) => ShelfPreview::Procedural(*kind),
ShelfEntry::Environment(name) => ShelfPreview::Environment(name),
@@ -191,7 +204,7 @@ impl ShelfEntry {
ShelfEntry::Filter(filter) => Some(Asset::Filter(filter.id)),
ShelfEntry::Alpha(alpha) => Some(Asset::Alpha(&alpha.id)),
ShelfEntry::Image(name) => Some(Asset::Texture(name.clone())),
ShelfEntry::Brush(_) | ShelfEntry::SavedBrush(_) | ShelfEntry::Procedural(_) | ShelfEntry::Environment(_) => None,
ShelfEntry::Brush(_) | ShelfEntry::SavedBrush { .. } | ShelfEntry::Procedural(_) | ShelfEntry::Environment(_) => None,
}
}
@@ -221,8 +234,8 @@ impl ShelfEntry {
ShelfEntry::Brush(preset) => {
app.run("brush.preset.apply", json!({"preset": preset.id}));
}
ShelfEntry::SavedBrush(path) => {
app.run("brush.preset.load", json!({"path": path.display().to_string()}));
ShelfEntry::SavedBrush { name, .. } => {
app.run("brush.preset.apply", json!({"preset": name}));
}
ShelfEntry::Procedural(kind) => {
app.run("layer.add.fill", json!({"name": kind.label()}));
+33 -1
View File
@@ -52,6 +52,12 @@ impl ShelfPreview {
ShelfPreview::SavedBrush { path: path.to_path_buf(), settings, image }
}
/// Preview a brush saved only in the current session
pub fn session_brush(name: &str, brush: &BrushSettings, images: &ImageStore) -> Self {
let image = brush.alpha_image.as_ref().and_then(|image_name| images.get(image_name)).cloned();
ShelfPreview::SavedBrush { path: session_brush_path(name), settings: Some(brush.clone()), image }
}
/// Smart materials preview on the orb, plain materials on a sphere
pub fn material(id: &'static str) -> ShelfPreview {
match materials::find(id) {
@@ -91,6 +97,7 @@ impl ShelfPreview {
if settings.alpha_image.is_some() && image.is_none() {
return None;
}
Some(stroke_preview(settings, size, image.as_deref()))
}
ShelfPreview::Image(_, image) => Some(image_preview(image, size)),
@@ -99,6 +106,11 @@ impl ShelfPreview {
}
}
/// A cache key for a preset without a file
pub(crate) fn session_brush_path(name: &str) -> PathBuf {
PathBuf::from(format!("memory:{name}"))
}
/// A saved brush preset's settings; None when the file can't be read (or in the browser, which has no files)
#[cfg(not(target_arch = "wasm32"))]
pub(crate) fn read_saved_brush(path: &std::path::Path) -> Option<BrushSettings> {
@@ -110,7 +122,11 @@ pub(crate) fn read_saved_brush(path: &std::path::Path) -> Option<BrushSettings>
return None;
}
serde_json::from_slice::<BrushSettings>(&bytes).ok().map(|settings| settings.sanitized())
serde_json::from_slice::<texturecraft_engine::brush_preset_cmds::UserBrush>(&bytes)
.map(|preset| preset.brush)
.or_else(|_| serde_json::from_slice::<BrushSettings>(&bytes))
.ok()
.map(|settings| settings.sanitized())
}
#[cfg(target_arch = "wasm32")]
@@ -127,6 +143,22 @@ mod tests {
use super::*;
#[cfg(not(target_arch = "wasm32"))]
#[test]
fn named_brush_files_render_their_saved_settings() {
use texturecraft_engine::brush_preset_cmds::UserBrush;
let path = std::env::temp_dir().join(format!("tc-named-preview-{}.tcbrush", std::process::id()));
let mut brush = BrushSettings::default();
brush.size = 0.07;
let preset = UserBrush { name: "Ink".into(), brush: brush.clone(), channels: None, file: None };
std::fs::write(&path, serde_json::to_vec(&preset).unwrap()).unwrap();
let loaded = read_saved_brush(&path).unwrap();
assert_eq!(loaded.size, brush.size);
let _ = std::fs::remove_file(path);
}
/// The hover preview's size at 100 % scale
const BIG_PX: usize = 256;
+6 -1
View File
@@ -45,6 +45,11 @@ pub(crate) fn reset_query(app: &mut TextureCraftApp) {
/// Read the user's saved assets from disk again and redraw their thumbnails
fn refresh(app: &mut TextureCraftApp) {
app.library = None;
app.brushes = None;
#[cfg(not(target_arch = "wasm32"))]
for warning in app.session.load_brush_presets(crate::user_dir("brushes")) {
app.toast(warning, true);
}
app.thumbs.forget_saved_files();
}
+47
View File
@@ -267,15 +267,37 @@ impl Thumbs {
/// A saved brush preset's stroke along an S curve; None while it renders, empty when the file is unreadable
pub fn saved_brush(&mut self, ctx: &egui::Context, path: &Path, images: &ImageStore) -> Option<TextureHandle> {
self.saved_brush_with_settings(ctx, path, None, images)
}
/// Render a preset held only in this session through the saved-brush cache
pub fn session_brush(&mut self, ctx: &egui::Context, name: &str, brush: &BrushSettings, images: &ImageStore) -> Option<TextureHandle> {
let path = crate::shelf_preview::session_brush_path(name);
self.saved_brush_with_settings(ctx, &path, Some(brush), images)
}
/// Seed in-memory settings only when a thumbnail can use the frame budget
fn saved_brush_with_settings(
&mut self,
ctx: &egui::Context,
path: &Path,
initial_settings: Option<&BrushSettings>,
images: &ImageStore,
) -> Option<TextureHandle> {
let key = format!("saved-brush:{}", path.display());
let cached_preview = self.saved_brush_previews.contains_key(path).then(|| self.saved_brush_preview(path, images));
if let Some(texture) = self.shelf.get(&key) {
return Some(texture.clone());
}
if !self.spend_budget(ctx, 1) {
return None;
}
if let Some(settings) = initial_settings {
self.saved_brush_previews.entry(path.to_path_buf()).or_insert_with(|| (Some(settings.clone()), None, 0));
}
let preview = cached_preview.unwrap_or_else(|| self.saved_brush_preview(path, images));
let image = preview.image(SWATCH_PX).unwrap_or_else(|| ColorImage::filled([SWATCH_PX, SWATCH_PX], Color32::TRANSPARENT));
let texture = ctx.load_texture(format!("thumb_{key}"), image, TextureOptions::LINEAR);
@@ -465,6 +487,31 @@ mod tests {
assert!(matches!(thumbs.saved_brush_preview(&path, &images), ShelfPreview::SavedBrush { settings: None, .. }), "refresh reads the file again");
}
#[test]
fn session_brush_preview_uses_memory_and_releases_it_on_refresh() {
let context = egui::Context::default();
let mut thumbs = Thumbs::default();
let brush = BrushSettings { size: 0.07, ..BrushSettings::default() };
let path = crate::shelf_preview::session_brush_path("Session brush");
assert!(thumbs.session_brush(&context, "Session brush", &brush, &ImageStore::new()).is_some());
assert!(matches!(thumbs.saved_brush_previews.get(&path), Some((Some(settings), _, _)) if settings.size == brush.size));
thumbs.forget_saved_files();
assert!(thumbs.saved_brush_previews.is_empty());
}
#[test]
fn session_brush_waits_for_thumbnail_budget_before_cloning_settings() {
let context = egui::Context::default();
let mut thumbs = Thumbs::default();
thumbs.budget = (context.cumulative_pass_nr(), PER_FRAME);
assert!(thumbs.session_brush(&context, "First deferred", &BrushSettings::default(), &ImageStore::new()).is_none());
assert!(thumbs.session_brush(&context, "Second deferred", &BrushSettings::default(), &ImageStore::new()).is_none());
assert!(thumbs.saved_brush_previews.is_empty());
}
#[test]
fn saved_brush_cache_releases_old_images_on_change_and_refresh() {
const IMAGE_SIDE: u32 = 512;
+43 -9
View File
@@ -2,6 +2,7 @@
use egui_kittest::Harness;
use egui_kittest::kittest::{NodeT, Queryable};
use texturecraft_engine::brush_preset_cmds::UserBrush;
use texturecraft_engine::core::ProceduralKind;
use texturecraft_engine::core::project::ENVIRONMENTS;
use texturecraft_engine::materials::{MATERIALS, SmartMaterial};
@@ -148,14 +149,14 @@ fn reset_query_shows_every_asset_again() {
#[test]
fn refresh_reads_the_saved_brushes_again() {
let mut harness = shelf(REFERENCE_WINDOW);
let stale = vec![std::path::PathBuf::from("gone.tcbrush")];
harness.state_mut().brushes = Some(stale.clone());
let stale = UserBrush { name: "Stale brush marker".into(), brush: Default::default(), channels: None, file: None };
harness.state_mut().session.brush_presets.list.push(stale);
harness.run_steps(1);
button(&harness, "Refresh").click();
harness.run_steps(3);
assert_ne!(harness.state().brushes, Some(stale), "the brushes folder was read again");
assert!(harness.state().session.brush_presets.find("Stale brush marker").is_none(), "the brushes folder was read again");
assert!(harness.query_by_label("Import resources...").is_some(), "the toolbar has the import button");
}
@@ -270,17 +271,50 @@ fn a_saved_brush_is_a_tile_that_loads_the_preset() {
let mut harness = shelf(REFERENCE_WINDOW);
let mut saved = harness.state().session.tool.brush.clone();
saved.spacing += SAVED_SPACING_CHANGE;
let path = std::env::temp_dir().join(format!("shelf-panel-{}.tcbrush", std::process::id()));
std::fs::write(&path, serde_json::to_vec(&saved).unwrap()).unwrap();
harness.state_mut().brushes = Some(vec![path.clone()]);
harness.state_mut().session.brush_presets.list.push(UserBrush { name: "Session brush".into(), brush: saved.clone(), channels: None, file: None });
harness.state_mut().ui.shelf_tab = BRUSHES_TYPE;
harness.run_steps(3);
harness.get_by_label(path.file_stem().unwrap().to_str().unwrap()).click();
harness.get_by_label("Session brush").click();
harness.run_steps(2);
std::fs::remove_file(&path).unwrap();
assert_eq!(harness.state().session.tool.brush.spacing, saved.spacing, "the click loads the saved stroke");
assert_eq!(harness.state().session.tool.brush.spacing, saved.spacing, "the click applies the in-memory saved stroke");
}
#[test]
fn brush_management_follows_the_shelf_type_folder_and_search() {
let mut harness = shelf(REFERENCE_WINDOW);
harness.state_mut().session.brush_presets.list.push(UserBrush { name: "Session brush".into(), brush: Default::default(), channels: None, file: None });
harness.state_mut().ui.shelf_tab = BRUSHES_TYPE;
harness.run_steps(3);
assert!(harness.query_by_label("Save current brush").is_some());
assert!(harness.query_by_label("My brushes").is_some());
let save_rect = harness.get_by_label("Save current brush").rect();
assert!(save_rect.right() <= button(&harness, "Thumbnail size").rect().right(), "the controls stay inside the Assets panel: {save_rect:?}");
if let Some(dir) = std::env::var_os("TC_UI_SNAPSHOTS") {
std::fs::create_dir_all(&dir).unwrap();
harness.get_by_label("Save current brush").scroll_to_me();
harness.run_steps(2);
harness.render().unwrap().save(std::path::PathBuf::from(dir).join("brush-management-shelf.png")).unwrap();
}
harness.state_mut().ui.shelf_filter = "no matching brush".into();
harness.run_steps(2);
assert!(harness.query_by_label("Save current brush").is_none());
harness.state_mut().ui.shelf_filter.clear();
harness.state_mut().ui.shelf_path = vec!["starter".into(), "Brushes".into()];
harness.run_steps(2);
assert!(harness.query_by_label("Save current brush").is_none());
harness.state_mut().ui.shelf_path = vec!["user".into(), "Brushes".into()];
harness.run_steps(2);
assert!(harness.query_by_label("Save current brush").is_some());
harness.state_mut().ui.shelf_tab = MATERIALS_TYPE;
harness.run_steps(2);
assert!(harness.query_by_label("Save current brush").is_none());
}
#[test]
+29
View File
@@ -31,6 +31,35 @@ fn save(h: &mut Harness<'_, TextureCraftApp>, dir: &Path, name: &str) {
eprintln!("wrote {}", path.display());
}
/// Check the saved-brush controls without a GPU adapter
#[test]
#[ignore]
fn brush_presets_popover_snapshot() {
let Some(output_dir) = std::env::var_os("TC_UI_SNAPSHOTS").map(PathBuf::from) else { return };
std::fs::create_dir_all(&output_dir).unwrap();
let session = texturecraft_engine::sample_session(128, 32).unwrap();
let mut harness =
Harness::builder().with_size(egui::vec2(1280.0, 800.0)).with_pixels_per_point(1.0).build_eframe(|context| TextureCraftApp::new(context, session));
let brush = harness.state().session.tool.brush.clone();
harness.state_mut().session.brush_presets.list.clear();
harness.state_mut().ui.prefs.language = "en".into();
harness.state_mut().session.brush_presets.list.push(texturecraft_engine::brush_preset_cmds::UserBrush {
name: "Snapshot brush".into(),
brush,
channels: None,
file: None,
});
assert_eq!(harness.state().session.brush_presets.list.len(), 1);
harness.run_steps(6);
harness.get_by_label_contains("Brush presets").click();
save(&mut harness, &output_dir, "brush-presets-popover-with-user");
harness.get_by_label("Save current brush").scroll_to_me();
save(&mut harness, &output_dir, "brush-presets-controls-with-user");
assert!(harness.query_by_label_contains("Snapshot brush").is_some());
}
#[test]
#[ignore]
fn pbr_import_dialog_keeps_choices_after_error() {
+12
View File
@@ -308,6 +308,18 @@ File access follows `--read-root` / `--write-root` as for MCP.
| `textures.export` | `{dir, preset?, ts?, format?, padding?, size?, bitDepth?, dilation?, normalFormat?}` |
| `render` | `{view?, width?, height?, yaw?, pitch?}` → `{width, height, png}` |
Brush preset operations are engine commands. Send each through `command.run` with the shown
`id` and `params`, for example `{"id":1,"method":"command.run","params":{"id":"brush.preset.list","params":{}}}`.
| `command.run` id | `params` and result |
|---|---|
| `brush.preset.list` | `{}` → `[{id, label, category, builtin}]`: the built-in brush presets, then the user's |
| `brush.preset.apply` | `{preset}`: a built-in sets the stroke and keeps the size; a user preset sets the whole brush (size too) and the painted channels |
| `brush.preset.store` | `{name, overwrite?}`: saves the current brush and painted channels as a user preset (desktop and trusted local CLI: a `.tcbrush` file in the data folder's `brushes` folder; browser and untrusted headless MCP/RPC: current session only); an existing name needs `overwrite: true`, built-in names are read-only |
| `brush.preset.rename` | `{name, to}` |
| `brush.preset.delete` | `{name}` |
| `brush.preset.save` / `brush.preset.load` | `{path}`: save the brush as a loose `.tcbrush` file; load a loose or named preset's stroke, keeping the current size and painted channels |
```sh
printf '%s\n' '{"id":1,"method":"command.run","params":{"id":"project.new","params":{"mesh":"torus"}}}' \
'{"id":2,"method":"render","params":{"width":512,"height":512}}' | texturecraft-cli serve
+2 -1
View File
@@ -13,7 +13,8 @@ Everything TextureCraft does today, by area. What's still missing is in [`ROADMA
and angle.
**67 procedural brush alphas** in their own shelf tab, or any imported image as the alpha.
**18 brush presets** (basic, wear and grunge, details) in the shelf's Brushes tab set the
stroke and keep the size; save your own brushes there too.
stroke and keep the size. The Brush section's **Brush presets** popover (and the shelf) also keeps
your own: save the current brush, click to use it, rename, replace or delete it.
- **Tools:** paint, eraser, **projection** with image stencils (hold S to move, turn and scale the
stencil), polygon fill (triangle, UV island or the whole mesh), **path** and **lasso fill**, a
**particle brush**, **smudge**, **clone** (V + click sets the source), material picker, Shift+click