Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
5 changes: 5 additions & 0 deletions crates/core/src/channel.rs
Original file line number Diff line number Diff line change
Expand Up @@ -573,6 +573,11 @@ impl Channel {
pub fn is_shaded(self) -> bool {
self.index() < Channel::SHADED_COUNT
}

/// Whether this is one of the 32 user channels (`User0`..`User31`)
pub fn is_user(self) -> bool {
(Channel::User0..=Channel::User31).contains(&self)
}
}

/// Storage format of a channel in a texture set (what export and the UI report).
Expand Down
70 changes: 70 additions & 0 deletions crates/core/src/project.rs
Original file line number Diff line number Diff line change
Expand Up @@ -94,6 +94,9 @@ pub struct TextureSet {
pub resolution_height: Option<u32>,
/// Channels and their storage formats; see [`TextureSet::formats`] for what they hold
pub channels: Vec<(Channel, ChannelFormat)>,
/// Custom display names of user channels (`User0`..`User31`); omitted when none are renamed
#[serde(default, skip_serializing_if = "BTreeMap::is_empty")]
pub channel_names: BTreeMap<Channel, String>,
/// Whether channels hold their formats' precision; until a format is set every channel keeps 16 bits, what TextureCraft always stored
#[serde(default)]
pub format_precision: bool,
Expand Down Expand Up @@ -220,6 +223,7 @@ impl TextureSet {
resolution,
resolution_height: None,
channels: Channel::DEFAULT_SET.iter().map(|c| (*c, ChannelFormat::default_for(*c))).collect(),
channel_names: BTreeMap::new(),
format_precision: false,
stack: Vec::new(),
normal_mixing: NormalMixing::Combine,
Expand Down Expand Up @@ -405,6 +409,41 @@ impl TextureSet {
true
}

/// Remove channel `c` and any custom name it had (false when the set lacks it)
pub fn remove_channel(&mut self, c: Channel) -> bool {
let before = self.channels.len();
self.channels.retain(|(x, _)| *x != c);
self.channel_names.remove(&c);
self.channels.len() != before
}

/// Custom display name of user channel `channel`, if renamed
pub fn custom_channel_name(&self, channel: Channel) -> Option<&str> {
channel.is_user().then(|| self.channel_names.get(&channel).map(String::as_str).filter(|name| !name.is_empty())).flatten()
}

/// Display name of `channel`: its custom name when renamed, else its default label
pub fn channel_name(&self, channel: Channel) -> &str {
self.custom_channel_name(channel).unwrap_or_else(|| channel.label())
}

/// Set or clear (`None`) the custom display name of user channel `channel`; false for non-user or absent channels
pub fn set_channel_name(&mut self, channel: Channel, name: Option<String>) -> bool {
if !channel.is_user() || !self.has_channel(channel) {
return false;
}

match name.filter(|name| !name.is_empty() && name != channel.label()) {
Some(name) => {
self.channel_names.insert(channel, name);
}
None => {
self.channel_names.remove(&channel);
}
}
true
}

/// Store channel `target` in `format` (false when the set lacks it); the other channels keep what they hold
pub fn set_channel_format(&mut self, target: Channel, format: ChannelFormat) -> bool {
if !self.has_channel(target) {
Expand Down Expand Up @@ -1350,6 +1389,37 @@ mod tests {
assert_eq!(p.texture_sets[0].resolution_height, None);
}

#[test]
fn user_channel_names_round_trip_omit_when_empty_and_drop_on_remove() {
let mut set = TextureSet::new("a", 0, 128);
assert!(serde_json::to_value(&set).unwrap().get("channel_names").is_none(), "unchanged sets omit channel_names");
assert!(!set.set_channel_name(Channel::BaseColor, Some("Albedo".into())), "non-user channels are refused");
assert!(!set.set_channel_name(Channel::User0, Some("Wear".into())), "absent user channels are refused");

assert!(set.add_channel(Channel::User0));
assert_eq!(set.channel_name(Channel::User0), "User0");
assert!(set.set_channel_name(Channel::User0, Some("Wear".into())));
assert_eq!(set.channel_name(Channel::User0), "Wear");

let json = serde_json::to_string(&set).unwrap();
let back: TextureSet = serde_json::from_str(&json).unwrap();
assert_eq!(back.channel_name(Channel::User0), "Wear");

// Setting back to the default label or removing drops the entry
assert!(set.set_channel_name(Channel::User0, Some("User0".into())));
assert!(set.channel_names.is_empty());
assert!(set.set_channel_name(Channel::User0, Some("Dirt".into())));
assert!(set.remove_channel(Channel::User0));
assert!(set.channel_names.is_empty());
assert_eq!(set.channel_name(Channel::User0), "User0");

// Old projects without channel_names deserialize cleanly
let mut old = serde_json::to_value(&back).unwrap();
old.as_object_mut().unwrap().remove("channel_names");
let loaded: TextureSet = serde_json::from_value(old).unwrap();
assert_eq!(loaded.channel_name(Channel::User0), "User0");
}

#[test]
fn validate_rejects_newer_formats_and_dangling_ids() {
let mut p = project();
Expand Down
6 changes: 5 additions & 1 deletion crates/engine/src/inspect.rs
Original file line number Diff line number Diff line change
Expand Up @@ -279,7 +279,11 @@ pub fn texture_set(session: &Session, index: usize) -> Value {
"blockResolution": texture_set.block_resolution(),
"uvTiles": texture_set.uv_tiles,
"tiles": tiles,
"channels": texture_set.formats().iter().map(|(channel, format)| json!({ "channel": channel.id(), "format": format.label(), "shaded": channel.is_shaded() })).collect::<Vec<_>>(),
"channels": texture_set
.formats()
.iter()
.map(|(channel, format)| json!({ "channel": channel.id(), "name": texture_set.channel_name(*channel), "format": format.label(), "shaded": channel.is_shaded() }))
.collect::<Vec<_>>(),
"layers": session.doc.project.walk(index).len(),
"parts": crate::set_cmds::parts(session, index),
"baked": crate::project_cmds::baked_json(session.doc.baked.get(&index)),
Expand Down
48 changes: 45 additions & 3 deletions crates/engine/src/set_cmds.rs
Original file line number Diff line number Diff line change
Expand Up @@ -22,7 +22,7 @@ pub fn specs() -> Vec<CommandSpec> {
"Inspect texture set",
[],
None,
"{ts?} → {index, name, originalName, description, resolution, height, size: [w, h], blockResolution, uvTiles: [UDIM numbers] (empty: no UV tiles), tiles: [{udim, block: [x, y], resolution, bakeEnabled}], channels: [{channel, format, shaded}], layers, parts, baked, visible, normalMixing, aoMixing, heightToNormal, uvPadding, active}",
"{ts?} → {index, name, originalName, description, resolution, height, size: [w, h], blockResolution, uvTiles: [UDIM numbers] (empty: no UV tiles), tiles: [{udim, block: [x, y], resolution, bakeEnabled}], channels: [{channel, name, format, shaded}], layers, parts, baked, visible, normalMixing, aoMixing, heightToNormal, uvPadding, active}",
always,
|s, p| Ok(crate::inspect::texture_set(s, ts_param(s, p, "textureSet.inspect")?))
),
Expand Down Expand Up @@ -58,6 +58,15 @@ pub fn specs() -> Vec<CommandSpec> {
always,
rename
),
cmd!(
"textureSet.renameChannel",
"Rename user channel",
[],
None,
"{ts?, channel, name} or {ts?, channel, reset: true} (empty name or reset restores the default label)",
always,
rename_channel
),
cmd!(
"textureSet.settings",
"Texture set settings",
Expand Down Expand Up @@ -366,7 +375,7 @@ fn channel(s: &mut Session, p: &Value, add: bool) -> Result<Value> {
if c == Channel::BaseColor {
return Err(bad("textureSet.channel.remove", "base color can't be removed"));
}
s.doc.project.texture_set_mut(ts)?.channels.retain(|(x, _)| *x != c);
s.doc.project.texture_set_mut(ts)?.remove_channel(c);
Ok(())
})?;
Ok(Value::Null)
Expand Down Expand Up @@ -414,7 +423,10 @@ fn channels(s: &mut Session, p: &Value) -> Result<Value> {
add_channel(s, ts, c)?;
}
}
s.doc.project.texture_set_mut(ts)?.channels.retain(|(c, _)| !remove.contains(c));
let set = s.doc.project.texture_set_mut(ts)?;
for &c in &remove {
set.remove_channel(c);
}
}
Ok(())
})?;
Expand Down Expand Up @@ -512,6 +524,36 @@ fn rename(s: &mut Session, p: &Value) -> Result<Value> {
Ok(Value::Null)
}

fn rename_channel(s: &mut Session, p: &Value) -> Result<Value> {
let cmd = "textureSet.renameChannel";
let ts = ts_param(s, p, cmd)?;
let channel = channel_param(cmd, p, "channel")?.ok_or_else(|| bad(cmd, "`channel` is required"))?;
if !channel.is_user() {
return Err(bad(cmd, format!("{} is not a user channel", channel.label())));
}

if !s.doc.project.texture_set(ts)?.has_channel(channel) {
return Err(bad(cmd, format!("the texture set has no {} channel", channel.label())));
}

let custom = if boolp(p, "reset") == Some(true) {
None
} else {
let name = strp(p, "name").ok_or_else(|| bad(cmd, "`name` or `reset: true` is required"))?.trim();
if name.chars().count() > MAX_NAME_CHARS {
return Err(bad(cmd, format!("`name` is at most {MAX_NAME_CHARS} characters")));
}

(!name.is_empty() && name != channel.label()).then(|| name.to_owned())
};

s.edit("Rename channel", |s| {
s.doc.project.texture_set_mut(ts)?.set_channel_name(channel, custom);
Ok(())
})?;
Ok(Value::Null)
}

impl Session {
/// The name set `ts` had when the mesh loaded: its material's name in the mesh
pub fn original_set_name(&self, ts: usize) -> Option<&str> {
Expand Down
1 change: 1 addition & 0 deletions crates/engine/src/template_cmds.rs
Original file line number Diff line number Diff line change
Expand Up @@ -211,6 +211,7 @@ impl Session {
for set_index in 0..project.texture_sets.len() {
if let Some(set) = project.texture_sets.get_mut(set_index) {
set.channels = template.channels.clone();
set.channel_names.retain(|channel, _| template.channels.iter().any(|(wanted, _)| wanted == channel));
set.format_precision = template.format_precision;
}

Expand Down
1 change: 1 addition & 0 deletions crates/engine/tests/it/main.rs
Original file line number Diff line number Diff line change
Expand Up @@ -72,6 +72,7 @@ mod polygon_fill;
mod project_recovery;
mod rebuilt_uv_layout;
mod rename_project;
mod rename_user_channel;
mod resource_updater;
mod resources_used;
mod sample;
Expand Down
125 changes: 125 additions & 0 deletions crates/engine/tests/it/rename_user_channel.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,125 @@
//! `textureSet.renameChannel`: custom display names for user channels (`User0`..`User31`).

use std::io::{Cursor, Read, Write};

use serde_json::{Value, json};
use texturecraft_engine::core::Channel;
use texturecraft_engine::geom::primitives;
use texturecraft_engine::{Session, execute};

fn channel_name_in_inspect(session: &mut Session, ts: usize, channel_id: &str) -> String {
let inspect = execute(session, "textureSet.inspect", &json!({"ts": ts})).unwrap();
inspect["channels"].as_array().unwrap().iter().find(|entry| entry["channel"] == channel_id).unwrap()["name"].as_str().unwrap().to_owned()
}

#[test]
fn renaming_a_user_channel_updates_inspect_and_undoes() {
let mut session = Session::new_project("t", primitives::material_ball(), "builtin:material_ball", None, 128).unwrap();
execute(&mut session, "textureSet.channel.add", &json!({"ts": 1, "channel": "user0"})).unwrap();
assert_eq!(channel_name_in_inspect(&mut session, 1, "user0"), "User0");

execute(&mut session, "textureSet.renameChannel", &json!({"ts": 1, "channel": "user0", "name": " Wear Mask "})).unwrap();
assert_eq!(channel_name_in_inspect(&mut session, 1, "user0"), "Wear Mask");
assert_eq!(session.doc.project.texture_sets[1].channel_name(Channel::User0), "Wear Mask");
assert_eq!(session.doc.project.texture_sets[0].channel_name(Channel::User0), "User0");

execute(&mut session, "edit.undo", &Value::Null).unwrap();
assert_eq!(channel_name_in_inspect(&mut session, 1, "user0"), "User0");

execute(&mut session, "edit.redo", &Value::Null).unwrap();
assert_eq!(channel_name_in_inspect(&mut session, 1, "user0"), "Wear Mask");

// Empty name restores the default label in one undo step
execute(&mut session, "textureSet.renameChannel", &json!({"ts": 1, "channel": "user0", "name": " "})).unwrap();
assert_eq!(channel_name_in_inspect(&mut session, 1, "user0"), "User0");
assert!(session.doc.project.texture_sets[1].channel_names.is_empty());

execute(&mut session, "edit.undo", &Value::Null).unwrap();
assert_eq!(channel_name_in_inspect(&mut session, 1, "user0"), "Wear Mask");

// `reset: true` also restores the default label
execute(&mut session, "textureSet.renameChannel", &json!({"ts": 1, "channel": "user0", "reset": true})).unwrap();
assert_eq!(channel_name_in_inspect(&mut session, 1, "user0"), "User0");
}

#[test]
fn renamed_user_channel_survives_save_and_reopen_and_old_projects_load() {
let mut session = Session::new_project("t", primitives::material_ball(), "builtin:material_ball", None, 128).unwrap();

// Unchanged projects omit `channel_names` in project.json
let clean_bytes = session.to_project_bytes().unwrap();
let mut clean_zip = zip::ZipArchive::new(Cursor::new(&clean_bytes)).unwrap();
let mut clean_json = String::new();
clean_zip.by_name("project.json").unwrap().read_to_string(&mut clean_json).unwrap();
assert!(!clean_json.contains("channel_names"), "unchanged projects must not serialize channel_names");

execute(&mut session, "textureSet.channel.add", &json!({"ts": 0, "channel": "user2"})).unwrap();
execute(&mut session, "textureSet.renameChannel", &json!({"ts": 0, "channel": "user2", "name": "Rust / Dirt"})).unwrap();

let saved = session.to_project_bytes().unwrap();
let mut reopened = Session::from_project_bytes(&saved).unwrap();
assert_eq!(channel_name_in_inspect(&mut reopened, 0, "user2"), "Rust / Dirt");

// Strip `channel_names` from project.json to simulate an older .tcraft file
let mut old_zip_bytes = Vec::new();
{
let mut reader = zip::ZipArchive::new(Cursor::new(&saved)).unwrap();
let mut writer = zip::ZipWriter::new(Cursor::new(&mut old_zip_bytes));
for index in 0..reader.len() {
let mut entry = reader.by_index(index).unwrap();
let name = entry.name().unwrap().into_owned();
let mut data = Vec::new();
entry.read_to_end(&mut data).unwrap();
if name == "project.json" {
let mut project: Value = serde_json::from_slice(&data).unwrap();
for set in project["texture_sets"].as_array_mut().unwrap() {
set.as_object_mut().unwrap().remove("channel_names");
}
data = serde_json::to_vec_pretty(&project).unwrap();
}
writer.start_file(name, zip::write::SimpleFileOptions::default()).unwrap();
writer.write_all(&data).unwrap();
}
writer.finish().unwrap();
}

let mut old_loaded = Session::from_project_bytes(&old_zip_bytes).unwrap();
assert_eq!(channel_name_in_inspect(&mut old_loaded, 0, "user2"), "User2");
}

#[test]
fn invalid_renames_fail_and_removing_a_channel_drops_its_name() {
let mut session = Session::new_project("t", primitives::material_ball(), "builtin:material_ball", None, 128).unwrap();
execute(&mut session, "textureSet.channels", &json!({"ts": 0, "add": ["user0", "user1"]})).unwrap();
let before = session.doc.project.texture_sets[0].clone();
let steps = session.history_labels().len();

let refused = [
json!({"ts": 0, "channel": "baseColor", "name": "Albedo"}),
json!({"ts": 0, "channel": "user5", "name": "Missing"}),
json!({"ts": 0, "channel": "user0"}),
json!({"ts": 0, "channel": "user0", "name": 42}),
json!({"ts": 0, "channel": "user0", "name": "a".repeat(129)}),
json!({"ts": 99, "channel": "user0", "name": "BadSet"}),
];
for params in &refused {
assert!(execute(&mut session, "textureSet.renameChannel", params).is_err(), "{params}");
}
assert_eq!(session.doc.project.texture_sets[0], before);
assert_eq!(session.history_labels().len(), steps);

// 128 characters is accepted
let at_limit = "界".repeat(128);
execute(&mut session, "textureSet.renameChannel", &json!({"ts": 0, "channel": "user0", "name": at_limit})).unwrap();
assert_eq!(session.doc.project.texture_sets[0].channel_name(Channel::User0), at_limit);

// Removing through either channel-removal command drops the custom name
execute(&mut session, "textureSet.renameChannel", &json!({"ts": 0, "channel": "user1", "name": "Glow Mask"})).unwrap();
execute(&mut session, "textureSet.channel.remove", &json!({"ts": 0, "channel": "user0"})).unwrap();
execute(&mut session, "textureSet.channels", &json!({"ts": 0, "remove": ["user1"]})).unwrap();
assert!(session.doc.project.texture_sets[0].channel_names.is_empty());

execute(&mut session, "textureSet.channels", &json!({"ts": 0, "add": ["user0", "user1"]})).unwrap();
assert_eq!(channel_name_in_inspect(&mut session, 0, "user0"), "User0");
assert_eq!(channel_name_in_inspect(&mut session, 0, "user1"), "User1");
}
Loading
Loading