mirror of
https://github.com/storytold/texturecraft.git
synced 2026-11-28 00:59:29 +01:00
Brush presets: your own named brushes in the data folder
Save the current brush (size included) and the painted channels as a named preset kept as a .tcbrush file in the data folder's brushes folder. Use, rename, replace and delete them from a Brush presets popover in the brush options and from the shelf's My brushes list. New commands: brush.preset.store, brush.preset.rename, brush.preset.delete; brush.preset.list and brush.preset.apply now cover the user's presets too. Older bare .tcbrush files are picked up under their file name.
This commit is contained in:
1 parent
51085093c3
commit
28c4702ec8
16 files changed
+519
-55
No files matched your search
@@ -1,11 +1,16 @@
|
||||
//! 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.
|
||||
|
||||
use std::collections::BTreeSet;
|
||||
|
||||
use serde::{Deserialize, Serialize};
|
||||
use serde_json::{Value, json};
|
||||
use texturecraft_core::Channel;
|
||||
use texturecraft_formats::export::sanitize_file_stem;
|
||||
use texturecraft_paint::BrushSettings;
|
||||
use texturecraft_paint::presets::{PRESETS, find_preset, with_stroke_of};
|
||||
|
||||
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};
|
||||
|
||||
@@ -15,31 +20,268 @@ 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";
|
||||
|
||||
/// 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 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(a: &str, b: &str) -> bool {
|
||||
a.trim().eq_ignore_ascii_case(b.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(|p| same_name(&p.name, name))
|
||||
}
|
||||
|
||||
/// `name` belongs to a built-in or to a user brush other than `skip` (or shares its file).
|
||||
fn taken(&self, name: &str, skip: Option<usize>) -> bool {
|
||||
find_preset(name).is_some()
|
||||
|| self.list.iter().enumerate().any(|(i, p)| Some(i) != skip && (same_name(&p.name, name) || file_key(&p.name) == file_key(name)))
|
||||
}
|
||||
|
||||
#[cfg(not(target_arch = "wasm32"))]
|
||||
fn file(&self, name: &str) -> Option<std::path::PathBuf> {
|
||||
self.dir.as_ref().map(|d| d.join(format!("{}.{BRUSH_EXT}", sanitize_file_stem(name.trim()))))
|
||||
}
|
||||
|
||||
/// Mirror `brush` to the folder; `replaced` is the name it had before (its file goes).
|
||||
#[cfg(not(target_arch = "wasm32"))]
|
||||
fn write(&self, brush: &UserBrush, replaced: Option<&str>) -> std::result::Result<(), String> {
|
||||
let (Some(dir), Some(path)) = (&self.dir, self.file(&brush.name)) else { return Ok(()) };
|
||||
let json = serde_json::to_vec_pretty(brush).map_err(|e| e.to_string())?;
|
||||
std::fs::create_dir_all(dir).map_err(|e| format!("cannot create {}: {e}", dir.display()))?;
|
||||
texturecraft_formats::write_atomic(&path, &json).map_err(|e| format!("cannot write {}: {e}", path.display()))?;
|
||||
if let Some(old) = replaced.filter(|old| file_key(old) != file_key(&brush.name)) {
|
||||
self.delete(old);
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
#[cfg(target_arch = "wasm32")]
|
||||
fn write(&self, _: &UserBrush, _: Option<&str>) -> std::result::Result<(), String> {
|
||||
Ok(())
|
||||
}
|
||||
|
||||
#[cfg(not(target_arch = "wasm32"))]
|
||||
fn delete(&self, name: &str) {
|
||||
if let Some(path) = self.file(name) {
|
||||
// A file that is already gone is fine.
|
||||
let _ = std::fs::remove_file(path);
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(target_arch = "wasm32")]
|
||||
fn delete(&self, _: &str) {}
|
||||
}
|
||||
|
||||
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: Vec<std::path::PathBuf> = std::fs::read_dir(&dir)
|
||||
.map(|rd| rd.flatten().map(|e| e.path()).filter(|p| p.extension().is_some_and(|e| e.eq_ignore_ascii_case(BRUSH_EXT))).collect())
|
||||
.unwrap_or_default();
|
||||
files.sort();
|
||||
let mut lib = UserBrushes { list: Vec::new(), dir: Some(dir) };
|
||||
for path in files.into_iter().take(MAX_USER) {
|
||||
let mut bytes = Vec::new();
|
||||
let read = std::fs::File::open(&path).and_then(|f| f.take(MAX_BYTES + 1).read_to_end(&mut bytes));
|
||||
if let Err(e) = read {
|
||||
warnings.push(format!("{}: {e}", 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(|s| s.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 }));
|
||||
match parsed {
|
||||
Ok(mut b) => {
|
||||
b.name = b.name.trim().chars().take(MAX_NAME).collect();
|
||||
b.brush = b.brush.sanitized();
|
||||
if b.name.is_empty() || lib.taken(&b.name, None) {
|
||||
warnings.push(format!("{}: the name \"{}\" is empty or taken", path.display(), b.name));
|
||||
} else {
|
||||
lib.list.push(b);
|
||||
}
|
||||
}
|
||||
Err(e) => warnings.push(format!("{}: not a brush preset: {e}", path.display())),
|
||||
}
|
||||
}
|
||||
self.brush_presets = lib;
|
||||
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,
|
||||
|s, _| Ok(list(s))
|
||||
),
|
||||
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, kept in the data folder → {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(s: &Session) -> Value {
|
||||
let builtin = PRESETS.iter().map(|p| json!({"id": p.id, "label": p.label, "category": p.category, "builtin": true}));
|
||||
let user = s.brush_presets.list.iter().map(|p| json!({"id": p.name, "label": p.name, "category": USER_CATEGORY, "builtin": false}));
|
||||
json!(builtin.chain(user).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))
|
||||
const CMD: &str = "brush.preset.apply";
|
||||
let name = strp(p, "preset").ok_or_else(|| bad(CMD, "`preset` is required"))?;
|
||||
if let Some(preset) = find_preset(name) {
|
||||
return set(s, preset.applied(&s.tool.brush));
|
||||
}
|
||||
let user = s.brush_presets.find(name).and_then(|i| s.brush_presets.list.get(i)).cloned();
|
||||
let user = user.ok_or_else(|| bad(CMD, format!("unknown brush preset `{name}` (see brush.preset.list)")))?;
|
||||
let mut brush = user.brush.sanitized();
|
||||
// An image alpha belongs to the project that saved it.
|
||||
if brush.alpha_image.as_ref().is_some_and(|n| !s.images.contains_key(n)) {
|
||||
brush.alpha_image = None;
|
||||
}
|
||||
if let Some(channels) = user.channels {
|
||||
s.tool.enabled = channels;
|
||||
}
|
||||
set(s, brush)
|
||||
}
|
||||
|
||||
fn name_param(p: &Value, key: &str, cmd: &str) -> Result<String> {
|
||||
let name = strp(p, key).map(str::trim).filter(|n| !n.is_empty()).ok_or_else(|| bad(cmd, format!("`{key}` is required")))?;
|
||||
if name.chars().count() > MAX_NAME || name.chars().any(char::is_control) {
|
||||
return Err(bad(cmd, format!("`{key}` must be 1–{MAX_NAME} characters without control characters")));
|
||||
}
|
||||
Ok(name.to_string())
|
||||
}
|
||||
|
||||
fn store(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
const CMD: &str = "brush.preset.store";
|
||||
let name = name_param(p, "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 lib = &s.brush_presets;
|
||||
let target = lib.find(&name);
|
||||
if target.is_some() && boolp(p, "overwrite") != Some(true) {
|
||||
return Err(bad(CMD, format!("a brush preset named \"{name}\" exists already (pass overwrite: true to replace it)")));
|
||||
}
|
||||
if lib.taken(&name, target) {
|
||||
return Err(bad(CMD, format!("\"{name}\" is too close to another preset's name")));
|
||||
}
|
||||
if target.is_none() && lib.list.len() >= MAX_USER {
|
||||
return Err(bad(CMD, format!("at most {MAX_USER} user brush presets")));
|
||||
}
|
||||
// Overwriting keeps the stored spelling of the name.
|
||||
let name = target.and_then(|i| lib.list.get(i)).map_or(name, |old| old.name.clone());
|
||||
let entry = UserBrush { name: name.clone(), brush: s.tool.brush.sanitized(), channels: Some(s.tool.enabled.clone()) };
|
||||
lib.write(&entry, None).map_err(|e| bad(CMD, e))?;
|
||||
match target.and_then(|i| s.brush_presets.list.get_mut(i)) {
|
||||
Some(slot) => *slot = entry,
|
||||
None => s.brush_presets.list.push(entry),
|
||||
}
|
||||
Ok(json!({ "name": name }))
|
||||
}
|
||||
|
||||
fn rename(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
const CMD: &str = "brush.preset.rename";
|
||||
let old = name_param(p, "name", CMD)?;
|
||||
let to = name_param(p, "to", CMD)?;
|
||||
if find_preset(&old).is_some() {
|
||||
return Err(bad(CMD, format!("\"{old}\" is a built-in preset and can't be renamed")));
|
||||
}
|
||||
let lib = &s.brush_presets;
|
||||
let i = lib.find(&old).ok_or_else(|| bad(CMD, format!("no user brush preset `{old}`")))?;
|
||||
if find_preset(&to).is_some() || lib.taken(&to, Some(i)) {
|
||||
return Err(bad(CMD, format!("a brush preset named \"{to}\" exists already")));
|
||||
}
|
||||
let Some(mut entry) = lib.list.get(i).cloned() else { return Err(bad(CMD, format!("no user brush preset `{old}`"))) };
|
||||
let previous = entry.name.clone();
|
||||
entry.name = to.clone();
|
||||
lib.write(&entry, Some(&previous)).map_err(|e| bad(CMD, e))?;
|
||||
if let Some(slot) = s.brush_presets.list.get_mut(i) {
|
||||
*slot = entry;
|
||||
}
|
||||
Ok(json!({ "name": to }))
|
||||
}
|
||||
|
||||
fn delete(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
const CMD: &str = "brush.preset.delete";
|
||||
let name = name_param(p, "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 i = s.brush_presets.find(&name).ok_or_else(|| bad(CMD, format!("no user brush preset `{name}`")))?;
|
||||
let removed = s.brush_presets.list.remove(i);
|
||||
s.brush_presets.delete(&removed.name);
|
||||
Ok(Value::Null)
|
||||
}
|
||||
|
||||
fn set(s: &mut Session, brush: BrushSettings) -> Result<Value> {
|
||||
@@ -83,3 +325,113 @@ 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(s: &mut Session, id: &str, p: Value) -> Result<Value> {
|
||||
crate::execute(s, id, &p)
|
||||
}
|
||||
|
||||
fn names(s: &Session) -> Vec<&str> {
|
||||
s.brush_presets.list.iter().map(|p| p.name.as_str()).collect()
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn store_apply_overwrite_rename_and_delete() {
|
||||
let mut s = session();
|
||||
run(&mut s, "tool.brush", json!({"size": 40, "hardness": 20, "flow": 35, "spacing": 12, "jitterSize": 50})).unwrap();
|
||||
s.tool.enabled = [Channel::Roughness].into_iter().collect();
|
||||
assert_eq!(run(&mut s, "brush.preset.store", json!({"name": " Mine "})).unwrap()["name"], "Mine");
|
||||
let saved = s.tool.brush.clone();
|
||||
|
||||
// Applying brings back the whole brush (size too) and the channels.
|
||||
run(&mut s, "brush.preset.apply", json!({"preset": "basic_soft"})).unwrap();
|
||||
run(&mut s, "tool.brush", json!({"size": 5})).unwrap();
|
||||
s.tool.enabled = [Channel::BaseColor].into_iter().collect();
|
||||
run(&mut s, "brush.preset.apply", json!({"preset": "mine"})).unwrap();
|
||||
assert_eq!(s.tool.brush, saved);
|
||||
assert_eq!(s.tool.enabled, [Channel::Roughness].into_iter().collect());
|
||||
|
||||
// Listed after the built-ins, flagged as the user's.
|
||||
let listed = run(&mut s, "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);
|
||||
|
||||
// The same name needs `overwrite`; a built-in name is never taken.
|
||||
assert!(run(&mut s, "brush.preset.store", json!({"name": "MINE"})).is_err());
|
||||
run(&mut s, "tool.brush", json!({"size": 70})).unwrap();
|
||||
assert_eq!(run(&mut s, "brush.preset.store", json!({"name": "MINE", "overwrite": true})).unwrap()["name"], "Mine");
|
||||
assert_eq!(names(&s), ["Mine"], "overwriting does not add a second one");
|
||||
assert!((s.brush_presets.list[0].brush.size - saved.size).abs() > 1e-4);
|
||||
for builtin in ["Chalk", "basic-hard"] {
|
||||
assert!(run(&mut s, "brush.preset.store", json!({"name": builtin, "overwrite": true})).is_err());
|
||||
assert!(run(&mut s, "brush.preset.rename", json!({"name": builtin, "to": "x"})).is_err());
|
||||
assert!(run(&mut s, "brush.preset.delete", json!({"name": builtin})).is_err());
|
||||
}
|
||||
|
||||
// Rename keeps the content, refuses clashes, and the old name is gone.
|
||||
run(&mut s, "brush.preset.store", json!({"name": "Second"})).unwrap();
|
||||
assert!(run(&mut s, "brush.preset.rename", json!({"name": "Mine", "to": "second"})).is_err());
|
||||
assert!(run(&mut s, "brush.preset.rename", json!({"name": "Mine", "to": "Airbrush"})).is_err());
|
||||
assert!(run(&mut s, "brush.preset.rename", json!({"name": "nope", "to": "x"})).is_err());
|
||||
assert_eq!(run(&mut s, "brush.preset.rename", json!({"name": "mine", "to": "Renamed"})).unwrap()["name"], "Renamed");
|
||||
assert_eq!(names(&s), ["Renamed", "Second"]);
|
||||
assert!(run(&mut s, "brush.preset.apply", json!({"preset": "Mine"})).is_err());
|
||||
|
||||
// Presets survive opening another project; delete removes them.
|
||||
run(&mut s, "project.new", json!({"resolution": 128})).unwrap();
|
||||
assert_eq!(s.brush_presets.list.len(), 2);
|
||||
run(&mut s, "brush.preset.delete", json!({"name": "renamed"})).unwrap();
|
||||
assert_eq!(names(&s), ["Second"]);
|
||||
assert!(run(&mut s, "brush.preset.delete", json!({"name": "renamed"})).is_err());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn hostile_names_are_refused() {
|
||||
let mut s = session();
|
||||
for name in [json!(""), json!(" "), json!("x".repeat(MAX_NAME + 1)), json!("a\nb"), json!(7), Value::Null] {
|
||||
assert!(run(&mut s, "brush.preset.store", json!({"name": name})).is_err());
|
||||
}
|
||||
run(&mut s, "brush.preset.store", json!({"name": "a/b"})).unwrap();
|
||||
assert!(run(&mut s, "brush.preset.store", json!({"name": "a?b"})).is_err(), "same file name as `a/b`");
|
||||
assert_eq!(names(&s), ["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 s = session();
|
||||
assert!(s.load_brush_presets(dir.clone()).is_empty(), "a missing folder is an empty library");
|
||||
run(&mut s, "tool.brush", json!({"size": 33, "hardness": 80})).unwrap();
|
||||
run(&mut s, "brush.preset.store", json!({"name": "Ink pen"})).unwrap();
|
||||
run(&mut s, "brush.preset.store", json!({"name": "Scratch", "overwrite": true})).unwrap();
|
||||
run(&mut s, "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 s, "brush.preset.delete", json!({"name": "Scratchy"})).unwrap();
|
||||
assert!(!dir.join("Scratchy.tcbrush").exists());
|
||||
|
||||
// A bare brush (`brush.preset.save`), a broken file and a built-in name in the folder.
|
||||
run(&mut s, "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 - s.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);
|
||||
}
|
||||
}
|
||||
@@ -358,6 +358,8 @@ pub struct Session {
|
||||
pub(crate) depth_cache: Option<DepthCache>,
|
||||
/// 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,
|
||||
}
|
||||
@@ -406,6 +408,7 @@ impl Session {
|
||||
log: Vec::new(),
|
||||
depth_cache: None,
|
||||
export_presets: Default::default(),
|
||||
brush_presets: Default::default(),
|
||||
templates: Default::default(),
|
||||
})
|
||||
}
|
||||
@@ -415,6 +418,7 @@ impl Session {
|
||||
pub fn switch_to(&mut self, mut next: Session) {
|
||||
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;
|
||||
}
|
||||
|
||||
@@ -1133,9 +1133,38 @@ fn path_section(app: &mut TextureCraftApp, ui: &mut Ui) {
|
||||
ui.label(RichText::new(hint).size(10.5).color(tk.text_dim));
|
||||
}
|
||||
|
||||
/// The "Brush presets" button: a popover with the built-in presets and the user's own.
|
||||
fn brush_presets_popover(app: &mut TextureCraftApp, ui: &mut Ui) {
|
||||
let resp = ui.button(format!("{} {}", ic::PAINT_BRUSH_BROAD, tr("Brush presets")));
|
||||
let popup = ui.make_persistent_id("brush_presets_popup");
|
||||
if resp.clicked() {
|
||||
egui::Popup::toggle_id(ui.ctx(), popup);
|
||||
}
|
||||
egui::Popup::from_response(&resp).id(popup).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 p in texturecraft_engine::paint::presets::PRESETS.iter() {
|
||||
if p.category != category {
|
||||
category = p.category;
|
||||
ui.label(caption(category));
|
||||
}
|
||||
if ui.selectable_label(false, p.label).on_hover_text(tr("Use this brush (keeps its size)")).clicked() {
|
||||
app.run("brush.preset.apply", json!({"preset": p.id}));
|
||||
}
|
||||
}
|
||||
ui.separator();
|
||||
crate::shelf::user_brushes(app, ui, "");
|
||||
});
|
||||
});
|
||||
}
|
||||
|
||||
fn brush_section(app: &mut TextureCraftApp, ui: &mut Ui) {
|
||||
ui.horizontal(|ui| {
|
||||
ui.label(caption(tr("Brush")));
|
||||
brush_presets_popover(app, ui);
|
||||
});
|
||||
let b = &mut app.session.tool.brush;
|
||||
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(10.5).color(Tokens::get(ui.ctx()).text_dim));
|
||||
section(ui, "sec_size", tr("Size"), true, |ui| {
|
||||
|
||||
@@ -1041,4 +1041,9 @@ 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", "حذف هذه الفرشاة"),
|
||||
];
|
||||
@@ -1090,4 +1090,9 @@ 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"),
|
||||
];
|
||||
@@ -1075,4 +1075,9 @@ 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"),
|
||||
];
|
||||
@@ -1099,4 +1099,9 @@ 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"),
|
||||
];
|
||||
@@ -1084,4 +1084,9 @@ 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"),
|
||||
];
|
||||
@@ -1069,4 +1069,9 @@ 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", "このブラシを削除"),
|
||||
];
|
||||
@@ -1054,4 +1054,9 @@ 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", "이 브러시 삭제"),
|
||||
];
|
||||
@@ -1072,4 +1072,9 @@ 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"),
|
||||
];
|
||||
@@ -1000,4 +1000,9 @@ 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", "删除此笔刷"),
|
||||
];
|
||||
@@ -90,8 +90,8 @@ 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>>,
|
||||
/// The user's brush presets were read from the brushes folder.
|
||||
pub brushes: bool,
|
||||
/// Rendering mode's path tracer.
|
||||
pub render: render_mode::RenderView,
|
||||
/// Smoothed CPU time spent building the UI per frame (ms).
|
||||
@@ -150,7 +150,7 @@ impl TextureCraftApp {
|
||||
ui_ms: 0.0,
|
||||
profiler: profile::Profiler::default(),
|
||||
library: None,
|
||||
brushes: None,
|
||||
brushes: false,
|
||||
render: render_mode::RenderView::default(),
|
||||
last_paint_point: None,
|
||||
placing_decal: None,
|
||||
|
||||
+69
-42
@@ -388,64 +388,91 @@ fn brushes(app: &mut TextureCraftApp, ui: &mut Ui, ctx: &egui::Context, filter:
|
||||
});
|
||||
}
|
||||
}
|
||||
my_brushes(app, ui, filter);
|
||||
user_brushes(app, ui, filter);
|
||||
}
|
||||
|
||||
/// The user's saved brush presets (desktop brushes folder) and saving the current brush there.
|
||||
#[cfg(not(target_arch = "wasm32"))]
|
||||
fn my_brushes(app: &mut TextureCraftApp, ui: &mut Ui, filter: &str) {
|
||||
use texturecraft_engine::brush_preset_cmds::BRUSH_EXT;
|
||||
let dir = crate::user_dir("brushes");
|
||||
if app.brushes.is_none() {
|
||||
let mut files: Vec<std::path::PathBuf> = std::fs::read_dir(&dir)
|
||||
.map(|d| d.flatten().map(|e| e.path()).filter(|p| p.extension().is_some_and(|x| x == BRUSH_EXT)).collect())
|
||||
.unwrap_or_default();
|
||||
files.sort();
|
||||
app.brushes = Some(files);
|
||||
}
|
||||
let files = app.brushes.clone().unwrap_or_default();
|
||||
let name = |f: &std::path::PathBuf| f.file_stem().and_then(|s| s.to_str()).unwrap_or("brush").to_string();
|
||||
let shown: Vec<_> = files.iter().filter(|f| matches(filter, &[&name(f)])).collect();
|
||||
if !filter.is_empty() && shown.is_empty() {
|
||||
/// Reads the user's brush presets from the data folder once (desktop; the web keeps them for
|
||||
/// the session).
|
||||
fn load_brushes(app: &mut TextureCraftApp) {
|
||||
if app.brushes {
|
||||
return;
|
||||
}
|
||||
ui.horizontal(|ui| {
|
||||
header(ui, tr("My brushes"));
|
||||
if ui.small_button(ic::ARROW_CLOCKWISE).on_hover_text(tr("Rescan the library folder")).clicked() {
|
||||
app.brushes = None;
|
||||
app.brushes = true;
|
||||
#[cfg(not(target_arch = "wasm32"))]
|
||||
for w in app.session.load_brush_presets(crate::user_dir("brushes")) {
|
||||
app.toast(w, true);
|
||||
}
|
||||
}
|
||||
|
||||
/// The user's brush presets: click to use one, and rename, replace it with the current brush or
|
||||
/// delete it; below, a field saves the current brush under a new name.
|
||||
pub(crate) fn user_brushes(app: &mut TextureCraftApp, ui: &mut Ui, filter: &str) {
|
||||
load_brushes(app);
|
||||
let names: Vec<String> = app.session.brush_presets.list.iter().map(|p| p.name.clone()).filter(|n| matches(filter, &[n])).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(|d| d.get_temp(rename_id));
|
||||
for name in names {
|
||||
ui.horizontal(|ui| {
|
||||
if renaming.as_ref().is_some_and(|(old, _)| *old == name) {
|
||||
let Some((old, buf)) = renaming.as_mut() else { return };
|
||||
let edit = ui.add(egui::TextEdit::singleline(buf).desired_width(120.0));
|
||||
let (done, cancel) = (edit.lost_focus() && ui.input(|i| i.key_pressed(egui::Key::Enter)), ui.input(|i| i.key_pressed(egui::Key::Escape)));
|
||||
if !edit.has_focus() && !done && !cancel {
|
||||
edit.request_focus();
|
||||
}
|
||||
if done {
|
||||
// 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, "to": buf}));
|
||||
}
|
||||
if done || cancel {
|
||||
renaming = None;
|
||||
}
|
||||
return;
|
||||
}
|
||||
let use_it =
|
||||
ui.add(egui::Button::selectable(false, format!("{} {name}", ic::PAINT_BRUSH_BROAD))).on_hover_text(tr("Use this brush (with its size)"));
|
||||
if use_it.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(|d| match renaming {
|
||||
Some(r) => {
|
||||
d.insert_temp(rename_id, r);
|
||||
}
|
||||
None => {
|
||||
d.remove_temp::<(String, String)>(rename_id);
|
||||
}
|
||||
});
|
||||
for f in shown {
|
||||
if ui
|
||||
.add(egui::Button::selectable(false, format!("{} {}", ic::PAINT_BRUSH_BROAD, name(f))))
|
||||
.on_hover_text(tr("Use this brush (keeps its size)"))
|
||||
.clicked()
|
||||
{
|
||||
app.run("brush.preset.load", json!({"path": f.display().to_string()}));
|
||||
}
|
||||
}
|
||||
ui.horizontal(|ui| {
|
||||
let id = ui.make_persistent_id("brush_preset_name");
|
||||
let mut new_name: String = ui.data_mut(|d| d.get_temp(id)).unwrap_or_default();
|
||||
ui.add(egui::TextEdit::singleline(&mut new_name).hint_text(tr("Brush name")).desired_width(110.0));
|
||||
let file = texturecraft_engine::formats::export::sanitize_file_stem(new_name.trim());
|
||||
if ui.add_enabled(!new_name.trim().is_empty(), egui::Button::new(tr("Save current brush"))).clicked() {
|
||||
let path = dir.join(format!("{file}.{BRUSH_EXT}"));
|
||||
// A folder that can't be made fails the save, which reports it.
|
||||
let _ = std::fs::create_dir_all(&dir);
|
||||
if app.run("brush.preset.save", json!({"path": path.display().to_string()})).is_some() {
|
||||
new_name.clear();
|
||||
app.brushes = None;
|
||||
}
|
||||
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(|d| d.insert_temp(id, new_name));
|
||||
});
|
||||
ui.add_space(6.0);
|
||||
}
|
||||
|
||||
#[cfg(target_arch = "wasm32")]
|
||||
fn my_brushes(_: &mut TextureCraftApp, _: &mut Ui, _: &str) {}
|
||||
|
||||
/// The built-in alpha library, grouped by category; the brush's alpha is outlined.
|
||||
fn alpha_library(app: &mut TextureCraftApp, ui: &mut Ui, ctx: &egui::Context, filter: &str, name: &str) {
|
||||
let tk = Tokens::get(ctx);
|
||||
|
||||
@@ -215,6 +215,12 @@ File access follows `--read-root` / `--write-root` as for MCP.
|
||||
| `resource.import` | `{path}` |
|
||||
| `material.save` | `{path, layer?, name?}` |
|
||||
| `material.load` | `{path}` |
|
||||
| `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 (a `.tcbrush` file in the data folder's `brushes` folder); 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}`: the brush as a loose `.tcbrush` file, and back (the stroke only, size kept) |
|
||||
| `textures.export` | `{dir, preset?, ts?, format?, padding?, size?, bitDepth?, dilation?, normalFormat?}` |
|
||||
| `render` | `{view?, width?, height?, yaw?, pitch?}` → `{width, height, png}` |
|
||||
|
||||
|
||||
+2
-1
@@ -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), color picker, Shift+click
|
||||
|
||||
Reference in new issue
Block a user