Folders and instances: Contents Scale and Rotation, Randomize seeds, the instance's source card

This commit is contained in:
Rebornim committed 2026-11-22 05:30:04 +00:00
1 parent 9ed26168d0
commit 32654f417e
5 files changed
+691

No files matched your search

+246
View File
@@ -0,0 +1,246 @@
//! A folder's actions on everything inside it: the Scale and Rotation laid on its fills, and new seeds for its patterns
use std::collections::{HashMap, HashSet};
use serde_json::{Value, json};
use texturecraft_core::project::MAX_DEPTH;
use texturecraft_core::{ContentsOffset, EffectKind, Fill, Filter, Layer, LayerId, LayerKind, Project, RandomizedSeed, Source};
use crate::commands::{CommandSpec, bad, f32p, has_layer, layer_param};
use crate::{Result, Session, cmd};
pub fn specs() -> Vec<CommandSpec> {
vec![
cmd!(
"folder.contents.set",
"Folder contents",
[],
None,
"{layer?: folder (default selected), scale?: 0.01..100 multiplying every fill's tiling inside, rotation?: degrees added to every fill's angle inside (wrapped to -180..180), merge?} — relative to each fill's own and never written into the fills; one undo step",
has_layer,
set_contents
),
cmd!(
"folder.contents.reset",
"Reset folder contents",
[],
None,
"{layer?: folder (default selected)} — drop the folder's Scale and Rotation: every fill inside back to its own, and put back the seeds its Randomize seeds changed (a seed changed since, or a layer moved out, keeps its own), in one undo step",
has_layer,
reset_contents
),
cmd!(
"folder.randomizeSeeds",
"Randomize seeds",
[],
None,
"{layer?: folder (default selected)} — a new seed for every pattern, generator and noise filter inside the folder (fills, masks, effects, nested folders; instanced sources stay), in one undo step; seeds that were equal stay equal; the folder keeps each seed's value from before so its Contents reset can put it back. Returns {seeds: how many changed}",
has_layer,
randomize_seeds
),
]
}
/// The folder a command acts on: the `layer` param or the selected layer, refused unless it is a folder
fn folder_param(s: &Session, cmd: &str, p: &Value) -> Result<LayerId> {
let id = layer_param(s, cmd, p)?;
match s.doc.project.layers.get(&id) {
Some(layer) if layer.is_group() => Ok(id),
_ => Err(bad(cmd, format!("layer {} is not a folder", id.0))),
}
}
/// The Scale and Rotation folder `id` lays on its fills
fn contents_mut(project: &mut Project, id: LayerId) -> Option<&mut ContentsOffset> {
match &mut project.layers.get_mut(&id)?.kind {
LayerKind::Group { contents, .. } => Some(contents),
_ => None,
}
}
/// The seeds inside folder `id` that its Randomize seeds changed
fn randomized_mut(project: &mut Project, id: LayerId) -> Option<&mut Vec<RandomizedSeed>> {
match &mut project.layers.get_mut(&id)?.kind {
LayerKind::Group { randomized, .. } => Some(randomized),
_ => None,
}
}
/// Whether folder `id`'s Contents differ from a new folder's: a Scale or Rotation laid on its fills, or seeds its Randomize seeds changed
pub fn contents_changed(project: &Project, id: LayerId) -> bool {
match project.layers.get(&id).map(|layer| &layer.kind) {
Some(LayerKind::Group { contents, randomized, .. }) => !contents.is_none() || !randomized.is_empty(),
_ => false,
}
}
fn set_contents(s: &mut Session, p: &Value) -> Result<Value> {
const CMD: &str = "folder.contents.set";
let id = folder_param(s, CMD, p)?;
let (scale, rotation) = (f32p(p, "scale"), f32p(p, "rotation"));
if scale.is_none() && rotation.is_none() {
return Err(bad(CMD, "give `scale` and/or `rotation`"));
}
let current = s.doc.project.contents_offset(id);
let offset = ContentsOffset::new(scale.unwrap_or(current.scale), rotation.unwrap_or(current.rotation));
let reply = json!({ "scale": offset.scale, "rotation": offset.rotation });
if offset == current {
return Ok(reply);
}
s.edit("Folder contents", |s| {
let contents = contents_mut(&mut s.doc.project, id).ok_or_else(|| bad(CMD, format!("layer {} is not a folder", id.0)))?;
*contents = offset;
Ok(())
})?;
Ok(reply)
}
fn reset_contents(s: &mut Session, p: &Value) -> Result<Value> {
const CMD: &str = "folder.contents.reset";
let id = folder_param(s, CMD, p)?;
if !contents_changed(&s.doc.project, id) {
return Ok(Value::Null);
}
let mut descended = Vec::new();
descendants(&s.doc.project, id, 0, &mut descended);
let inside: HashSet<LayerId> = descended.into_iter().collect();
s.edit("Reset folder contents", |s| {
let contents = contents_mut(&mut s.doc.project, id).ok_or_else(|| bad(CMD, format!("layer {} is not a folder", id.0)))?;
*contents = ContentsOffset::NONE;
let randomized = randomized_mut(&mut s.doc.project, id).map(std::mem::take).unwrap_or_default();
for record in randomized.iter().filter(|record| inside.contains(&record.layer)) {
let Some(layer) = s.doc.project.layers.get_mut(&record.layer) else { continue };
// Only a seed still at the value Randomize seeds gave it goes back: one changed since keeps the artist's pick
if let Some(seed) = layer_seeds(layer).into_iter().nth(record.index as usize).filter(|seed| **seed == record.after) {
*seed = record.before;
}
}
Ok(())
})?;
Ok(Value::Null)
}
fn randomize_seeds(s: &mut Session, p: &Value) -> Result<Value> {
const CMD: &str = "folder.randomizeSeeds";
let folder = folder_param(s, CMD, p)?;
let mut inside = Vec::new();
descendants(&s.doc.project, folder, 0, &mut inside);
let seeds: usize = inside.iter().filter_map(|id| s.doc.project.layers.get(id)).map(seed_count).sum();
if seeds == 0 {
return Ok(json!({ "seeds": 0 }));
}
// One mixing key per folder: a seed maps to the same new seed wherever it is, so patterns that lined up still do
let key = next_seed(folder.0 as u32 ^ (folder.0 >> 32) as u32);
s.edit("Randomize seeds", |s| {
let mut randomized = randomized_mut(&mut s.doc.project, folder).map(std::mem::take).unwrap_or_default();
let mut positions = randomized.iter().enumerate().map(|(position, record)| ((record.layer, record.index), position)).collect();
for id in &inside {
let Some(layer) = s.doc.project.layers.get_mut(id) else { continue };
for (index, seed) in (0u32..).zip(layer_seeds(layer)) {
let after = next_seed(*seed ^ key);
remember(&mut randomized, &mut positions, RandomizedSeed { layer: *id, index, before: *seed, after });
*seed = after;
}
}
*randomized_mut(&mut s.doc.project, folder).ok_or_else(|| bad(CMD, format!("layer {} is not a folder", folder.0)))? = randomized;
Ok(())
})?;
Ok(json!({ "seeds": seeds }))
}
/// Adds `change` to the folder's randomized seeds, found by (layer, seed index) in `positions`; a seed randomized again keeps its first `before` (what the reset puts back), unless it was changed by hand in between
fn remember(randomized: &mut Vec<RandomizedSeed>, positions: &mut HashMap<(LayerId, u32), usize>, change: RandomizedSeed) {
match positions.get(&(change.layer, change.index)).and_then(|position| randomized.get_mut(*position)) {
Some(record) if record.after == change.before => record.after = change.after,
Some(record) => *record = change,
None => {
positions.insert((change.layer, change.index), randomized.len());
randomized.push(change);
}
}
}
/// Whether folder `id` holds anything its Contents act on: a fill (layer, content or mask fill) or a seed
pub fn has_contents(project: &Project, id: LayerId) -> bool {
let mut inside = Vec::new();
descendants(project, id, 0, &mut inside);
inside.iter().filter_map(|id| project.layers.get(id)).any(|layer| {
let fills = matches!(layer.kind, LayerKind::Fill(_))
|| layer
.content_effects
.iter()
.chain(layer.mask.iter().flat_map(|mask| mask.effects.iter()))
.any(|effect| matches!(effect.kind, EffectKind::Fill { .. } | EffectKind::Material(_)));
fills || seed_count(layer) > 0
})
}
/// Every layer inside folder `id`, nested folders' children too (instances' sources are not followed: they live elsewhere)
fn descendants(project: &Project, id: LayerId, depth: usize, out: &mut Vec<LayerId>) {
if depth > MAX_DEPTH {
return;
}
for child in project.layers.get(&id).map(|folder| folder.children().to_vec()).unwrap_or_default() {
out.push(child);
descendants(project, child, depth + 1, out);
}
}
/// The seeds of a layer's fill, content effects and mask effects
fn layer_seeds(layer: &mut Layer) -> Vec<&mut u32> {
let Layer { kind, content_effects, mask, .. } = layer;
let mut seeds = Vec::new();
if let LayerKind::Fill(fill) = kind {
seeds.extend(fill.sources.values_mut().filter_map(source_seed));
}
let effects = content_effects.iter_mut().chain(mask.iter_mut().flat_map(|mask| mask.effects.iter_mut()));
for effect in effects {
match &mut effect.kind {
EffectKind::Fill { source, .. } => seeds.extend(source_seed(source)),
EffectKind::Material(fill) => seeds.extend(fill.sources.values_mut().filter_map(source_seed)),
EffectKind::Generator(generator) => seeds.push(&mut generator.seed),
EffectKind::Filter(Filter::Warp { seed, .. } | Filter::SlopeBlur { seed, .. } | Filter::DirectionalWarp { seed, .. }) => seeds.push(seed),
_ => {}
}
}
seeds
}
/// How many seeds [`layer_seeds`] gives for `layer`, read without borrowing it mutably (the panel asks every frame)
fn seed_count(layer: &Layer) -> usize {
let fill_seeds = |fill: &Fill| fill.sources.values().filter(|source| matches!(source, Source::Procedural { .. })).count();
let own = match &layer.kind {
LayerKind::Fill(fill) => fill_seeds(fill),
_ => 0,
};
let effects = layer.content_effects.iter().chain(layer.mask.iter().flat_map(|mask| mask.effects.iter()));
let effect_seeds: usize = effects
.map(|effect| match &effect.kind {
EffectKind::Fill { source, .. } => usize::from(matches!(source, Source::Procedural { .. })),
EffectKind::Material(fill) => fill_seeds(fill),
_ => 0,
})
.sum();
own + effect_seeds
}
fn source_seed(source: &mut Source) -> Option<&mut u32> {
match source {
Source::Procedural { pattern, .. } => Some(&mut pattern.seed),
_ => None,
}
}
/// A new seed that looks random but follows from `seed` (SplitMix32's mixing step), so tests and replays get the same seeds
pub fn next_seed(seed: u32) -> u32 {
let mut z = seed.wrapping_add(0x9e37_79b9);
z = (z ^ (z >> 16)).wrapping_mul(0x85eb_ca6b);
z = (z ^ (z >> 13)).wrapping_mul(0xc2b2_ae35);
z ^ (z >> 16)
}
+179
View File
@@ -0,0 +1,179 @@
//! A folder's Scale and Rotation over the fills inside it (stored on the folder, reset drops it) and Randomize seeds as one undo step
use serde_json::{Value, json};
use texturecraft_engine::core::{Channel, ContentsOffset, EffectKind, Filter, LayerId, LayerKind, Projection, Source};
use texturecraft_engine::geom::primitives;
use texturecraft_engine::{Session, execute};
/// The test project's texture size
const RESOLUTION: u32 = 128;
/// Texels between two base colour samples, across and down
const SAMPLE_STRIDE: usize = 9;
fn id(v: Value, key: &str) -> LayerId {
LayerId(v[key].as_u64().unwrap())
}
/// A folder holding a Clouds fill (base color and roughness on one seed) with a warp filter in its mask; returns (session, folder, fill)
fn folder_with_fill() -> (Session, LayerId, LayerId) {
let mut s = Session::new_project("t", primitives::sphere(1.0, 16, 8), "builtin:sphere", None, RESOLUTION).unwrap();
let fill = id(execute(&mut s, "layer.add.fill", &Value::Null).unwrap(), "layer");
for channel in ["baseColor", "roughness"] {
execute(&mut s, "layer.fill.set", &json!({"layer": fill.0, "channel": channel, "procedural": "Clouds", "seed": 7})).unwrap();
}
execute(&mut s, "layer.fill.projection", &json!({"layer": fill.0, "projection": "uv", "scale": [2.0, 2.0], "rotation": 10.0})).unwrap();
execute(&mut s, "mask.add.white", &json!({"layer": fill.0})).unwrap();
execute(&mut s, "effect.add.filter", &json!({"layer": fill.0, "target": "mask", "filter": "warp"})).unwrap();
let folder = id(execute(&mut s, "layer.group", &json!({"layer": fill.0})).unwrap(), "layer");
s.update();
(s, folder, fill)
}
fn projection(s: &Session, fill: LayerId) -> Projection {
match &s.doc.project.layer(fill).unwrap().kind {
LayerKind::Fill(f) => f.projection.clone(),
other => panic!("not a fill: {other:?}"),
}
}
fn base_colors(s: &Session) -> Vec<[f32; 3]> {
let composite = &s.caches[s.ts()].composite;
let samples = || (0..RESOLUTION).step_by(SAMPLE_STRIDE);
samples().flat_map(|y| samples().map(move |x| (x, y))).map(|(x, y)| composite.value(Channel::BaseColor, x, y)).collect()
}
#[test]
fn a_folders_scale_and_rotation_lay_on_its_fills_without_changing_them_and_reset_drops_them() {
let (mut s, folder, fill) = folder_with_fill();
let own = projection(&s, fill);
let before = base_colors(&s);
let steps = s.history_labels().len();
let set = execute(&mut s, "folder.contents.set", &json!({"layer": folder.0, "scale": 1.5, "rotation": 30.0})).unwrap();
assert_eq!(set, json!({"scale": 1.5, "rotation": 30.0}));
assert_eq!(s.history_labels().len(), steps + 1, "one undo step");
assert_eq!(s.doc.project.contents_around(fill), ContentsOffset::new(1.5, 30.0));
assert_eq!(projection(&s, fill), own, "the fill keeps its own values");
s.update();
let turned = base_colors(&s);
assert_ne!(turned, before, "the fill renders scaled and turned");
let inspect = execute(&mut s, "project.inspect", &Value::Null).unwrap().to_string();
assert!(inspect.contains(r#""contents":{"rotation":30.0,"scale":1.5}"#), "{inspect}");
// A drag continues its step; one value given keeps the other
execute(&mut s, "folder.contents.set", &json!({"layer": folder.0, "rotation": 400.0, "merge": true})).unwrap();
assert_eq!(s.history_labels().len(), steps + 1);
assert_eq!(s.doc.project.contents_offset(folder), ContentsOffset::new(1.5, 40.0));
// The values it already has add no step
let unchanged = execute(&mut s, "folder.contents.set", &json!({"layer": folder.0, "scale": 1.5, "rotation": 40.0})).unwrap();
assert_eq!(unchanged, json!({"scale": 1.5, "rotation": 40.0}));
assert_eq!(s.history_labels().len(), steps + 1, "no step for the same values");
execute(&mut s, "folder.contents.reset", &json!({"layer": folder.0})).unwrap();
assert!(s.doc.project.contents_offset(folder).is_none());
s.update();
assert_eq!(base_colors(&s), before, "reset gives every fill its own back");
let steps = s.history_labels().len();
execute(&mut s, "folder.contents.reset", &json!({"layer": folder.0})).unwrap();
assert_eq!(s.history_labels().len(), steps, "nothing to drop, no step");
execute(&mut s, "edit.undo", &Value::Null).unwrap();
assert_eq!(s.doc.project.contents_offset(folder), ContentsOffset::new(1.5, 40.0));
// Only folders take an offset, and it needs a value
assert!(execute(&mut s, "folder.contents.set", &json!({"layer": fill.0, "scale": 2.0})).is_err());
assert!(execute(&mut s, "folder.contents.set", &json!({"layer": folder.0})).is_err());
assert!(execute(&mut s, "folder.randomizeSeeds", &json!({"layer": fill.0})).is_err());
}
#[test]
fn randomize_seeds_gives_every_pattern_inside_a_new_seed_in_one_undo_step() {
let (mut s, folder, fill) = folder_with_fill();
// The folder inside another: its seeds are inside that one too
let outer = id(execute(&mut s, "layer.group", &json!({"layer": folder.0})).unwrap(), "layer");
let before = fill_seeds(&s, fill);
let steps = s.history_labels().len();
let out = execute(&mut s, "folder.randomizeSeeds", &json!({"layer": outer.0})).unwrap();
assert_eq!(out["seeds"], 3);
assert_eq!(s.history_labels().len(), steps + 1, "one undo step");
let after = fill_seeds(&s, fill);
assert!(after.0 != before.0 && after.2 != before.2, "{before:?} -> {after:?}");
assert_eq!(after.0, after.1, "channels on one seed stay on one seed");
execute(&mut s, "edit.undo", &Value::Null).unwrap();
assert_eq!(fill_seeds(&s, fill), before, "one undo takes every seed back");
// A folder with nothing seeded inside adds no step
let empty = id(execute(&mut s, "layer.add.group", &Value::Null).unwrap(), "layer");
let steps = s.history_labels().len();
assert_eq!(execute(&mut s, "folder.randomizeSeeds", &json!({"layer": empty.0})).unwrap()["seeds"], 0);
assert_eq!(s.history_labels().len(), steps);
}
/// The seeds of fill layer `id`'s base color and roughness patterns and of its mask's warp filter
fn fill_seeds(s: &Session, id: LayerId) -> (u32, u32, u32) {
let layer = s.doc.project.layer(id).unwrap();
let LayerKind::Fill(fill) = &layer.kind else { panic!("not a fill") };
let pattern = |channel| match fill.sources.get(&channel) {
Some(Source::Procedural { pattern, .. }) => pattern.seed,
other => panic!("not a pattern: {other:?}"),
};
let warp = layer.mask.as_ref().unwrap().effects.iter().find_map(|effect| match effect.kind {
_ => None,
});
(pattern(Channel::BaseColor), pattern(Channel::Roughness), warp.unwrap())
}
#[test]
fn the_contents_reset_puts_back_the_seeds_randomize_seeds_changed_in_one_undo_step() {
let (mut s, folder, fill) = folder_with_fill();
let before = fill_seeds(&s, fill);
let pictured = base_colors(&s);
assert!(!texturecraft_engine::folder_cmds::contents_changed(&s.doc.project, folder), "a new folder's contents are at their defaults");
// Randomized twice, with a Scale laid on top: the reset still goes back to the seeds from before the first
execute(&mut s, "folder.randomizeSeeds", &json!({"layer": folder.0})).unwrap();
execute(&mut s, "folder.randomizeSeeds", &json!({"layer": folder.0})).unwrap();
execute(&mut s, "folder.contents.set", &json!({"layer": folder.0, "scale": 2.0})).unwrap();
let randomized = fill_seeds(&s, fill);
assert!(randomized.0 != before.0 && randomized.2 != before.2, "{before:?} -> {randomized:?}");
assert!(texturecraft_engine::folder_cmds::contents_changed(&s.doc.project, folder), "the reset is lit");
// Old projects: the record is saved with the folder and read back
let saved = serde_json::to_value(&s.doc.project).unwrap();
assert!(saved.to_string().contains("randomized"), "the folder keeps its seeds from before in the project");
let steps = s.history_labels().len();
execute(&mut s, "folder.contents.reset", &json!({"layer": folder.0})).unwrap();
assert_eq!(s.history_labels().len(), steps + 1, "one undo step");
assert_eq!(fill_seeds(&s, fill), before, "every seed is back");
assert!(s.doc.project.contents_offset(folder).is_none(), "the Scale is dropped too");
assert!(!texturecraft_engine::folder_cmds::contents_changed(&s.doc.project, folder), "nothing left to reset");
s.update();
assert_eq!(base_colors(&s), pictured, "the fill looks as it did before Randomize seeds");
execute(&mut s, "edit.undo", &Value::Null).unwrap();
assert_eq!(fill_seeds(&s, fill), randomized, "one undo brings the random seeds and the Scale back");
assert_eq!(s.doc.project.contents_offset(folder).scale, 2.0);
// A seed the artist set by hand after randomizing keeps their pick; the others go back
execute(&mut s, "layer.fill.set", &json!({"layer": fill.0, "channel": "roughness", "procedural": "Clouds", "seed": 42})).unwrap();
execute(&mut s, "folder.contents.reset", &json!({"layer": folder.0})).unwrap();
let after = fill_seeds(&s, fill);
assert_eq!((after.0, after.1, after.2), (before.0, 42, before.2));
}
/// A project saved before folders kept their randomized seeds opens with none and saves the folder as before
#[test]
fn a_folder_saved_without_randomized_seeds_opens_and_saves_unchanged() {
let (s, folder, _) = folder_with_fill();
let saved = serde_json::to_value(&s.doc.project.layers[&folder]).unwrap();
assert!(saved.to_string().contains("\"children\"") && !saved.to_string().contains("randomized"), "nothing new is written: {saved}");
let read: texturecraft_engine::core::Layer = serde_json::from_value(saved.clone()).unwrap();
assert!(matches!(&read.kind, LayerKind::Group { randomized, .. } if randomized.is_empty()));
assert_eq!(serde_json::to_value(&read).unwrap(), saved);
}
+45
View File
@@ -0,0 +1,45 @@
//! Properties of a folder: CONTENTS, the Scale and Rotation laid on every fill inside on top of their own (the round reset drops them and puts back the seeds Randomize seeds changed), and Randomize seeds
use egui::Ui;
use egui_phosphor::regular as ic;
use serde_json::json;
use texturecraft_engine::core::{ContentsOffset, LayerId};
use texturecraft_engine::folder_cmds::{contents_changed, has_contents};
use crate::TextureCraftApp;
use crate::i18n::tr;
use crate::property_sheet::PropertySheet;
/// Halvings and doublings the Scale track spans each way from ×1 (typed values go to the engine's range)
const SCALE_DOUBLINGS: f32 = 2.0;
/// The properties of folder `folder`; every change goes through the `folder.*` commands
pub(crate) fn folder_properties(app: &mut TextureCraftApp, ui: &mut Ui, folder: LayerId) {
let project = &app.session.doc.project;
if !has_contents(project, folder) {
crate::widgets::empty_note(ui, tr("No properties found"));
return;
}
let offset = project.contents_offset(folder);
let changed = contents_changed(project, folder);
PropertySheet::show(ui, ("folder_sheet", folder.0), |sheet| {
if sheet.section_reset(tr("Contents"), changed) {
app.run("folder.contents.reset", json!({"layer": folder.0}));
}
let (low, high) = ContentsOffset::SCALE_RANGE;
let mut scale = offset.scale;
if let Some(merge) = sheet.factor_slider(tr("Scale"), &mut scale, SCALE_DOUBLINGS, low..=high) {
app.run("folder.contents.set", json!({"layer": folder.0, "scale": scale, "merge": merge}));
}
let (turn_start, turn_end) = ContentsOffset::ROTATION_RANGE;
let mut rotation = offset.rotation;
if let Some(merge) = sheet.relative_angle(tr("Rotation"), &mut rotation, turn_start..=turn_end) {
app.run("folder.contents.set", json!({"layer": folder.0, "rotation": rotation, "merge": merge}));
}
if sheet.button(ic::DICE_FIVE, tr("Randomize seeds")).clicked() {
app.run("folder.randomizeSeeds", json!({"layer": folder.0}));
}
});
}
+100
View File
@@ -0,0 +1,100 @@
//! Properties of an instance: INSTANCE OF, the card of the layer it draws (a click goes to it), or a missing layer where the source is gone
use egui::epaint::RectShape;
use egui::{Color32, CornerRadius, Painter, Rect, TextureId, Ui, pos2};
use serde_json::json;
use texturecraft_engine::compose::ThumbTarget;
use texturecraft_engine::core::{Channel, Layer, LayerId, Project};
use crate::TextureCraftApp;
use crate::i18n::tr;
use crate::property_sheet::PropertySheet;
use crate::slot_thumbnail::{THUMB_RADIUS, paint_empty_slot};
use crate::theme::Tokens;
/// The properties of instance `layer`: where it draws from
pub(crate) fn instance_properties(app: &mut TextureCraftApp, ui: &mut Ui, layer: &Layer) {
let Some(source) = layer.instance_source() else { return };
let project = &app.session.doc.project;
let missing = !project.layers.contains_key(&source);
let name = project.layers.get(&source).map_or_else(|| tr("Missing layer").to_string(), |source_layer| source_layer.name.clone());
// A missing source has no texture set left; the instance's own names where it was
let set = set_name(project, if missing { layer.id } else { source });
let picture = if missing {
None
} else {
app.layer_panel.texture_outside(ui.ctx(), &app.session, ThumbTarget::Content { layer: source, channel: Channel::BaseColor })
};
let tokens = Tokens::get(ui.ctx());
let thumbnail = |painter: &Painter, rect: Rect| paint_thumbnail(painter, rect, picture, missing, &tokens);
let clicked = PropertySheet::show(ui, ("instance_sheet", layer.id.0), |sheet| {
sheet.section(tr("Instance of"), false);
sheet.source_card(&thumbnail, &name, &set, missing)
});
if clicked {
app.run("layer.select", json!({"layer": source.0, "target": "content"}));
}
}
/// The name of the texture set holding `layer`, empty when none does
fn set_name(project: &Project, layer: LayerId) -> String {
project.locate(layer).and_then(|(set_index, _, _)| project.texture_sets.get(set_index)).map(|texture_set| texture_set.name.clone()).unwrap_or_default()
}
/// The source's thumbnail with rounded corners (the field colour until it is rendered), or an empty outlined square for a missing source
fn paint_thumbnail(painter: &Painter, rect: Rect, picture: Option<TextureId>, missing: bool, tokens: &Tokens) {
if missing {
paint_empty_slot(painter, rect, tokens);
return;
}
let radius = CornerRadius::same(THUMB_RADIUS);
match picture {
Some(texture) => {
let uv = Rect::from_min_max(pos2(0.0, 0.0), pos2(1.0, 1.0));
painter.add(RectShape::filled(rect, radius, Color32::WHITE).with_texture(texture, uv));
}
None => {
painter.rect_filled(rect, radius, tokens.field);
}
}
}
#[cfg(test)]
mod tests {
use std::time::Duration;
use serde_json::json;
use texturecraft_engine::compose::ThumbTarget;
use texturecraft_engine::core::{Channel, LayerId};
use crate::docking::Panel;
#[test]
fn the_source_card_renders_its_picture_while_layers_is_closed() {
// Long enough for the render worker on a busy machine
const ATTEMPTS: usize = 500;
const WAIT: Duration = Duration::from_millis(10);
let _language = crate::i18n::TEST_LANGUAGE.lock().unwrap_or_else(std::sync::PoisonError::into_inner);
let mut harness = crate::frame_gizmo::tests::ball_app(false);
let source = harness.state_mut().run("layer.add.fill", json!({})).unwrap()["layer"].as_u64().unwrap();
let instance = harness.state_mut().run("layer.instance", json!({"layer": source})).unwrap()["layer"].as_u64().unwrap();
harness.state_mut().run("layer.select", json!({"layer": instance, "target": "content"})).unwrap();
harness.state_mut().ui.dock.close(Panel::Layers);
let target = ThumbTarget::Content { layer: LayerId(source), channel: Channel::BaseColor };
let rendered = (0..ATTEMPTS).any(|_| {
harness.step();
let fresh = harness.state().layer_panel.service().is_fresh(target);
if !fresh {
std::thread::sleep(WAIT);
}
fresh
});
assert!(!harness.state().ui.dock.is_open(Panel::Layers), "Layers stays closed");
assert!(rendered, "the Instance card's source picture renders without the Layers panel");
}
}
@@ -0,0 +1,121 @@
//! The folder in Properties: CONTENTS with Scale and Rotation over every fill inside (a drag is one undo step, the round reset drops them) and Randomize seeds (the reset also puts back the seeds it changed); an empty folder has no properties
use egui::accesskit::Role;
use egui_kittest::Harness;
use egui_kittest::kittest::{NodeT, Queryable};
use serde_json::json;
use texturecraft_engine::core::{Channel, ContentsOffset, LayerId, LayerKind, Source};
use texturecraft_engine::execute;
use texturecraft_ui_egui::TextureCraftApp;
use crate::{BAKE_RESOLUTION, DRAG_STEP_FRAMES, FRAME_SECONDS, PROPERTIES_WINDOW, SETTLE_FRAMES, SLIDER_END_INSET, STARTUP_FRAMES, TEXTURE_RESOLUTION};
/// How near a dragged Scale and Rotation land to the track's value (a drag ends a pixel or so off it)
const SCALE_TOLERANCE: f32 = 0.05;
const ROTATION_TOLERANCE_DEGREES: f32 = 3.0;
/// Hovers a drag passes through on its way, so the slider follows it as a hand would
const DRAG_MOVES: usize = 3;
/// A folder holding a Clouds fill (or nothing), the folder selected: (harness, folder, fill)
fn folder_harness(with_fill: bool) -> (Harness<'static, TextureCraftApp>, LayerId, LayerId) {
let mut session = texturecraft_engine::sample_session(TEXTURE_RESOLUTION, BAKE_RESOLUTION).unwrap();
let fill = LayerId(execute(&mut session, "layer.add.fill", &json!({})).unwrap()["layer"].as_u64().unwrap());
execute(&mut session, "layer.fill.set", &json!({"layer": fill.0, "channel": "baseColor", "procedural": "Clouds", "seed": 7})).unwrap();
let folder = if with_fill {
LayerId(execute(&mut session, "layer.group", &json!({"layer": fill.0})).unwrap()["layer"].as_u64().unwrap())
} else {
LayerId(execute(&mut session, "layer.add.group", &json!({})).unwrap()["layer"].as_u64().unwrap())
};
execute(&mut session, "layer.select", &json!({"layer": folder.0, "target": "content"})).unwrap();
let mut harness = Harness::builder().with_size(PROPERTIES_WINDOW).with_step_dt(FRAME_SECONDS).build_eframe(|cc| TextureCraftApp::new(cc, session));
harness.state_mut().ui.prefs.language = "en".into();
harness.run_steps(STARTUP_FRAMES);
(harness, folder, fill)
}
fn offset(harness: &Harness<'_, TextureCraftApp>, folder: LayerId) -> ContentsOffset {
harness.state().session.doc.project.contents_offset(folder)
}
/// Drags the slider labelled `label` from its middle to `to` (0 = its left end, 1 = its right end), hovering on the way
fn drag(harness: &mut Harness<'_, TextureCraftApp>, label: &str, to: f32) {
let track = harness.get_by_role_and_label(Role::Slider, label).rect();
let at = |t: f32| egui::pos2(track.left() + SLIDER_END_INSET + (track.width() - 2.0 * SLIDER_END_INSET) * t, track.center().y);
harness.drag_at(at(0.5));
harness.run_steps(DRAG_STEP_FRAMES);
for step in 1..=DRAG_MOVES {
harness.hover_at(at(0.5 + (to - 0.5) * step as f32 / DRAG_MOVES as f32));
harness.run_steps(DRAG_STEP_FRAMES);
}
harness.drop_at(at(to));
harness.run_steps(SETTLE_FRAMES);
}
#[test]
fn scale_and_rotation_drags_are_one_undo_step_each_and_the_reset_drops_them() {
let (mut harness, folder, fill) = folder_harness(true);
let steps = harness.state().session.history_labels().len();
drag(&mut harness, "Scale", 1.0);
let scaled = offset(&harness, folder);
assert!((scaled.scale - 4.0).abs() < SCALE_TOLERANCE, "the right end is x4: {scaled:?}");
assert_eq!(harness.state().session.history_labels().len(), steps + 1, "one undo step for the drag");
drag(&mut harness, "Rotation", 0.75);
let turned = offset(&harness, folder);
assert!((turned.rotation - 90.0).abs() < ROTATION_TOLERANCE_DEGREES && turned.scale == scaled.scale, "{turned:?}");
assert_eq!(harness.state().session.history_labels().len(), steps + 2);
let LayerKind::Fill(own) = &harness.state().session.doc.project.layer(fill).unwrap().kind else { panic!("not a fill") };
assert_eq!(own.projection, Default::default(), "the fill keeps its own projection");
harness.get_by_role_and_label(Role::Button, "Contents: Reset to defaults").click();
harness.run_steps(SETTLE_FRAMES);
assert!(offset(&harness, folder).is_none(), "the reset drops the offset");
assert_eq!(harness.state().session.history_labels().len(), steps + 3);
}
#[test]
fn randomize_seeds_is_one_undo_step_the_contents_reset_puts_them_back_and_an_empty_folder_has_no_properties() {
let (mut harness, _, fill) = folder_harness(true);
let seed = |harness: &Harness<'_, TextureCraftApp>| match &harness.state().session.doc.project.layer(fill).unwrap().kind {
LayerKind::Fill(fill_layer) => match fill_layer.sources.get(&Channel::BaseColor) {
Some(Source::Procedural { pattern, .. }) => pattern.seed,
other => panic!("not a pattern: {other:?}"),
},
other => panic!("not a fill: {other:?}"),
};
let steps = harness.state().session.history_labels().len();
harness.get_by_role_and_label(Role::Button, "Randomize seeds").click();
harness.run_steps(SETTLE_FRAMES);
assert_ne!(seed(&harness), 7);
assert_eq!(harness.state().session.history_labels().len(), steps + 1);
// The Contents reset lights up and puts the seed back, in one undo step
let reset = harness.get_by_role_and_label(Role::Button, "Contents: Reset to defaults");
assert!(!reset.accesskit_node().is_disabled(), "randomized seeds light the reset");
reset.click();
harness.run_steps(SETTLE_FRAMES);
assert_eq!(seed(&harness), 7, "the seed from before Randomize seeds");
assert_eq!(harness.state().session.history_labels().len(), steps + 2);
assert!(harness.get_by_role_and_label(Role::Button, "Contents: Reset to defaults").accesskit_node().is_disabled(), "nothing left to reset");
let (harness, _, _) = folder_harness(false);
assert!(harness.query_by_label("No properties found").is_some());
assert!(harness.query_by_role_and_label(Role::Slider, "Scale").is_none());
}
/// An empty folder's note starts at the Properties header name's left edge, as the note with no project open does (it was centred)
#[test]
fn an_empty_folders_note_starts_at_its_header_names_left_edge() {
let (harness, _, _) = folder_harness(false);
let painted_left = |wanted: &dyn Fn(&str) -> bool| {
harness.output().shapes.iter().find_map(|clipped| match &clipped.shape {
egui::Shape::Text(text) if wanted(text.galley.text()) => Some(text.pos.x),
_ => None,
})
};
let note = painted_left(&|text| text == "No properties found");
let header = painted_left(&|text| text.starts_with("PROPERTIES"));
assert!(note.is_some() && note == header, "the note starts at {note:?}, the header name at {header:?}");
}