Fills: the Material section with Material | Channels and linked materials

This commit is contained in:
Rebornim committed 2026-11-22 05:30:03 +00:00
1 parent 9e79434632
commit 5afbbbe08b
4 files changed
+1544 -15

No files matched your search

+126 -14
View File
@@ -1,17 +1,18 @@
//! MaterialCraft materials as fill layers. A `.mcmat` portable material becomes a fill whose
//! channel sources are its cooked maps (image resources) and whose [`MaterialLink`] keeps the
//! graph's exposed parameters. Changing one re-cooks the maps through `materialcraft-cli` at the
//! texture set's resolution, with the set's baked mesh maps feeding graph inputs of the same name.
//! Both apps use the shared craft-mcmat container and the public CLI.
//! layer's picked resolution (default: the texture set's), with the set's baked mesh maps feeding graph inputs of the same name;
//! both apps use the shared craft-mcmat container and the public CLI
use std::collections::{BTreeMap, BTreeSet};
use std::sync::Arc;
use serde_json::{Map, Value, json};
use texturecraft_core::{Channel, Fill, Layer, LayerId, LayerKind, LinkParam, MaterialLink, Source};
use texturecraft_core::{Channel, CookResolution, Fill, Layer, LayerId, LayerKind, LinkParam, MaterialLink, Source};
use texturecraft_formats::RamReservation as CookReservation;
use texturecraft_formats::mcmat::{MCRAFT_EXT, is_mcmat, is_mcraft, validate_mcmat_version};
use crate::commands::{CommandSpec, bad, boolp, has_layer, layer_param, strp};
use crate::commands::{CommandSpec, bad, boolp, channel_param, has_layer, layer_param, strp};
use crate::materials::Place;
use crate::{EngineError, Result, Session, cmd};
@@ -61,13 +62,31 @@ pub fn specs() -> Vec<CommandSpec> {
"Re-cook MaterialCraft material",
[],
None,
"{layer?} — re-cooks a MaterialCraft material layer at its texture set's resolution with the set's baked mesh maps",
"{layer?} — re-cooks a MaterialCraft material layer at its picked resolution (default: the texture set's) with the set's baked mesh maps",
has_layer,
|s, p| {
let id = layer_param(s, "material.link.cook", p)?;
cook(s, id, Map::new())
}
),
cmd!(
"material.link.map",
"Map material channel",
[],
None,
"{layer?, channel, output} — makes a channel of a MaterialCraft material layer read another output of the material (an output id such as \"roughness\")",
has_layer,
map
),
cmd!(
"material.link.resolution",
"Set material resolution",
[],
None,
"{layer?, relative: -3..3 | fixed: 128..8192 (power of two), cook?: true} — the size a MaterialCraft material layer cooks at: the texture set's resolution times 2^relative (0 = the texture set's), or fixed pixels across",
has_layer,
resolution
),
cmd!(
"material.link.saveSource",
"Save MaterialCraft package",
@@ -192,6 +211,81 @@ fn update(s: &mut Session, cmd: &str, id: LayerId, overrides: impl IntoIterator<
Ok(json!({"layer": id.0, "cooked": false}))
}
fn map(s: &mut Session, p: &Value) -> Result<Value> {
const CMD: &str = "material.link.map";
let id = layer_param(s, CMD, p)?;
let channel = channel_param(CMD, p, "channel")?.ok_or_else(|| bad(CMD, "`channel` is required"))?;
let output = strp(p, "output").ok_or_else(|| bad(CMD, "`output` is required"))?;
link_of(s, CMD, id)?;
s.edit("Map material channel", |s| {
let LayerKind::Fill(fill) = &mut s.doc.project.layer_mut(id)?.kind else { return Ok(()) };
let outputs = fill.link_outputs();
let image = outputs.get(output).ok_or_else(|| bad(CMD, format!("the material has no output `{output}`")))?.clone();
let normal_format = match fill.sources.get(&channel) {
Some(Source::Image { normal_format, .. }) => *normal_format,
_ => Default::default(),
};
fill.sources.insert(channel, Source::Image { name: image, normal_format });
if let Some(link) = &mut fill.link {
if output == channel.id() {
link.mapping.remove(&channel);
} else {
link.mapping.insert(channel, output.to_string());
}
// Sources no longer name every output once one is mapped elsewhere
link.outputs = outputs;
}
Ok(())
})?;
Ok(json!({"layer": id.0, "channel": channel.id(), "output": output}))
}
/// The `relative` or `fixed` param of `material.link.resolution`; `Some(None)` is the texture set's own size
pub(crate) fn picked_resolution(p: &Value) -> Option<Option<CookResolution>> {
let integer = |key: &str| p.get(key).and_then(Value::as_i64);
match (integer("relative"), integer("fixed")) {
(Some(factor), None) => {
let factor = i8::try_from(factor).ok().filter(|factor| CookResolution::FACTORS.contains(factor))?;
Some((factor != 0).then_some(CookResolution::Relative(factor)))
}
(None, Some(size)) => u32::try_from(size).ok().filter(|size| CookResolution::cookable(*size)).map(|size| Some(CookResolution::Fixed(size))),
_ => None,
}
}
fn resolution(s: &mut Session, p: &Value) -> Result<Value> {
const CMD: &str = "material.link.resolution";
let id = layer_param(s, CMD, p)?;
let size = picked_resolution(p).ok_or_else(|| bad(CMD, "give `relative` (-3..3) or `fixed` (a power of two from 128 to 8192)"))?;
let link = link_of(s, CMD, id)?;
let store = |s: &mut Session| {
s.edit(EDIT, |s| {
if let LayerKind::Fill(Fill { link: Some(link), .. }) = &mut s.doc.project.layer_mut(id)?.kind {
link.resolution = size;
}
Ok(())
})
};
if !boolp(p, "cook").unwrap_or(true) {
// Only the stored size changes, so the size it already has adds no undo step
if link.resolution != size {
store(s)?;
}
return Ok(json!({"layer": id.0, "cooked": false}));
}
// Cook first so a failed cook changes nothing, then store and swap the maps as one step
let mut job = s.link_job(id, &Map::new())?;
let (texture_set, _, _) = s.doc.project.locate(id).ok_or_else(|| bad(CMD, format!("layer {} is not in a stack", id.0)))?;
job.size = size.unwrap_or(CookResolution::TEXTURE_SET).size(s.doc.project.texture_set(texture_set)?.resolution);
let material = job.run()?;
store(s)?;
s.apply_link_cook(id, &material, true)?;
Ok(json!({"layer": id.0, "cooked": true, "size": job.size}))
}
fn cook(s: &mut Session, id: LayerId, overrides: Map<String, Value>) -> Result<Value> {
let job = s.link_job(id, &overrides)?;
let material = job.run()?;
@@ -377,6 +471,9 @@ impl Session {
presets: m.interface.presets.clone(),
inputs: m.interface.inputs.iter().map(|i| i.identifier.clone()).collect(),
size: m.size,
resolution: None,
mapping: BTreeMap::new(),
outputs: BTreeMap::new(),
};
let mut fill = Fill { link: Some(Box::new(link)), ..Fill::default() };
let names = put_maps(s, &stem, &m.maps, &mut fill);
@@ -447,14 +544,12 @@ impl Session {
let mut values = self.link_values(id)?;
values.extend(overrides.clone());
// UDIM tiles share one cook at the texture set's base resolution
let size = self.doc.project.texture_set(texture_set)?.resolution;
Ok(LinkJob {
layer: id,
package: self.link_package(id)?,
source_ext: source_extension(&link.package),
graph: Some(link.graph.clone()),
size,
size: self.link_size(id)?,
values,
input_identifiers: link.inputs,
baked: self.doc.baked.get(&texture_set).cloned(),
@@ -463,6 +558,14 @@ impl Session {
})
}
/// Pixels across linked layer `id` cooks at: its picked resolution, else its texture set's
pub fn link_size(&self, id: LayerId) -> Result<u32> {
let link = link_of(self, "material.link", id)?;
let (texture_set, _, _) = self.doc.project.locate(id).ok_or_else(|| EngineError::Other(format!("layer {} is not in a stack", id.0)))?;
// UDIM tiles share one cook at the texture set's base resolution
Ok(link.resolution.unwrap_or(CookResolution::TEXTURE_SET).size(self.doc.project.texture_set(texture_set)?.resolution))
}
/// Install the maps and exposed values returned by a completed [`LinkJob`].
/// With `merge`, this folds into the previous undo step when that was an edit of the same kind
/// (a parameter set while the cook ran).
@@ -481,8 +584,9 @@ impl Session {
}
link.size = material.size;
let stem = texturecraft_formats::sanitize_resource_name(&link.name);
let old_names: Vec<String> =
let mut old_names: Vec<String> =
fill.sources.values().filter_map(|source| if let Source::Image { name, .. } = source { Some(name.clone()) } else { None }).collect();
old_names.extend(fill.link_outputs().into_values());
let names = put_maps(session, &stem, &material.maps, &mut fill);
session.doc.project.layer_mut(id)?.kind = LayerKind::Fill(fill);
@@ -537,26 +641,34 @@ fn unique(session: &Session, stem: &str, suffix: &str) -> String {
format!("{stem}{suffix}")
}
/// Store `maps` as new resources (names carry a fresh id, so the decoded-image cache never
/// confuses two cooks) and point `fill`'s channels at them. Returns the names, in map order.
/// Store `maps` as new resources (names carry a fresh id, so the decoded-image cache never confuses two cooks), list them as the link's outputs and point `fill`'s channels at them: each channel at its mapped output, else at the output named like it. Returns the names, in map order
fn put_maps(s: &mut Session, stem: &str, maps: &[CookedMap], fill: &mut Fill) -> Vec<String> {
let cook = s.doc.project.alloc_id().0;
let mut names = Vec::new();
let mut outputs = BTreeMap::new();
for map in maps {
let channel = map.channel;
let extension = if map.bytes.starts_with(crate::resource_cmds::EXR_SIGNATURE) { "exr" } else { "png" };
let name = unique(s, stem, &format!("_{}_{cook}.{extension}", channel.id()));
s.doc.resources.insert(name.clone(), Arc::clone(&map.bytes));
outputs.insert(channel.id().to_string(), name.clone());
names.push(name);
}
// Preserve a normal convention the user chose for this layer
// Both callers cook a linked fill; one without a link only keeps the stored maps
let Some(link) = fill.link.as_mut() else { return names };
let channels: BTreeSet<Channel> = maps.iter().map(|map| map.channel).chain(link.mapping.keys().copied()).collect();
for channel in channels {
let Some(name) = outputs.get(link.output_of(channel)) else { continue };
// A normal map the user marked DirectX stays marked through re-cooks
let normal_format = match fill.sources.get(&channel) {
Some(Source::Image { normal_format, .. }) => *normal_format,
_ => Default::default(),
};
fill.sources.insert(channel, Source::Image { name: name.clone(), normal_format });
names.push(name);
}
link.outputs = outputs;
names
}
+1 -1
View File
@@ -21,7 +21,7 @@ pub struct LinkJob {
pub source_ext: &'static str,
/// The named graph in a linked material; direct package imports use its default.
pub graph: Option<String>,
/// Pixels across (the texture set's resolution).
/// Pixels across: the layer's picked resolution (default: the texture set's)
pub size: u32,
/// Every parameter's value, by id, in MaterialCraft's typed form.
pub values: Map<String, Value>,
+617
View File
@@ -0,0 +1,617 @@
//! A fill's Material section: the channel strip, the orb with the Material | Channels switch, then one slot card per channel that is on (Channels) or the fill's whole material (Material)
use std::collections::HashMap;
use std::sync::Arc;
use egui::{Color32, Painter, Rect};
use egui_phosphor::regular as ic;
use serde_json::{Value, json};
use texturecraft_engine::compose::{ImageRes, ImageStore};
use texturecraft_engine::core::{
Channel, ChannelKind, CookResolution, Fill, LayerId, LinkParam, MaterialLink, NormalFormat, OutputResolution, Procedural, ProceduralKind, ResolutionMode,
Source,
};
use texturecraft_engine::fill_alpha::library_alpha_of;
use texturecraft_engine::fill_material_cmds::whole_materials;
use texturecraft_engine::materials::find;
use texturecraft_engine::paint::alphas;
use texturecraft_engine::texel::linear_to_srgb;
use crate::TextureCraftApp;
use crate::color_picker::{ColorPick, SwatchEdit};
use crate::dock::{anchors_below, project_effect_anchors_below, with};
use crate::fill_panel::{FillKey, fill_key};
use crate::i18n::{n_, tr};
use crate::material_orb::material_orb;
use crate::orb_material::OrbMaterial;
use crate::pattern_panel::tile_generator_sections;
use crate::pattern_target::PatternTarget;
use crate::picker_group::PickerGroup;
use crate::picker_tab::PickerTab;
use crate::property_sheet::PropertySheet;
use crate::resolution_band::{resolution_band, resolution_row};
use crate::resource_picker;
use crate::resource_picker_item::ResourcePickerItem;
use crate::slot_thumbnail::{paint_thumbnail, thumbnail};
use crate::source_choice::SourceChoice;
use crate::source_slot::SourceSlot;
use crate::state::UiState;
use crate::theme::Tokens;
use crate::thumbs::Thumbs;
use crate::tile_picture::TilePicture;
use crate::widgets::press_edit;
/// The switch's two sides: the fill's whole material, or one source per channel
const MODES: [&str; 2] = [n_("Material"), n_("Channels")];
/// The switch's side that shows the fill's whole material
const MATERIAL_MODE: usize = 0;
/// The switch's side that shows one source per channel
const CHANNELS_MODE: usize = 1;
/// Decimals a linked material's number input shows
const FLOAT_DECIMALS: usize = 2;
/// Pattern scale a procedural's slider runs over (typed values stay inside it too)
const PATTERN_SCALE: std::ops::RangeInclusive<f32> = 0.1..=32.0;
/// Pattern contrast a procedural's slider runs over
const PATTERN_CONTRAST: std::ops::RangeInclusive<f32> = 0.0..=2.0;
/// Pattern balance a procedural's slider runs over: below the middle darker, above lighter
const PATTERN_BALANCE: std::ops::RangeInclusive<f32> = -1.0..=1.0;
/// The size a pattern's Resolution reads the texture set at when none is open: a new project's default
const FALLBACK_TEXTURE_SET_SIZE: u32 = 2048;
/// The Material section of the fill at `base`; `on` holds the channels the fill writes
pub(crate) fn material_section(app: &mut TextureCraftApp, sheet: &mut PropertySheet<'_>, fill: &Fill, base: &Value, on: &[Channel], reader: LayerId) {
sheet.section(tr("Material"), false);
let channels = app.session.doc.project.texture_set(app.session.ts()).map(|texture_set| texture_set.channel_list()).unwrap_or_default();
let names: Vec<&str> = channels.iter().map(|channel| tr(pill_name(*channel))).collect();
let enabled: Vec<bool> = channels.iter().map(|channel| on.contains(channel)).collect();
if let Some((index, solo)) = sheet.channel_pills(&names, &enabled)
&& let Some(channel) = channels.get(index)
{
let enable = solo || !enabled.get(index).copied().unwrap_or(false);
app.run("layer.fill.set", with(base, json!({"channel": channel.id(), "enabled": enable, "solo": solo})));
}
let tokens = Tokens::get(sheet.ui.ctx());
let salt = fill_key(base);
let look = OrbMaterial::of_fill(fill, on, &app.session.images);
let channel_look = channel_orb_look(&app.ui, fill, on, &app.session.images);
let shown = channel_look.as_ref().unwrap_or(&look);
let orb = |painter: &Painter, rect: Rect| material_orb(painter, rect, shown, &tokens, ("orb", salt));
let link = fill.link.as_deref().zip(base.get("layer").and_then(Value::as_u64)).map(|(link, layer)| (link, LayerId(layer)));
let mode_id = sheet.ui.make_persistent_id(("material_mode", salt));
// A fill opens on the side that made it: a material (linked or built-in) on Material, separate sources on Channels
let made_whole = link.is_some() || fill.material.is_some();
let mode = sheet.ui.data(|data| data.get_temp::<usize>(mode_id)).unwrap_or(if made_whole { MATERIAL_MODE } else { CHANNELS_MODE });
let modes = MODES.map(tr);
if let Some(picked) = sheet.orb_switch(&orb, &modes, mode) {
sheet.ui.data_mut(|data| data.insert_temp(mode_id, picked));
}
match link {
Some((link, layer)) if mode == MATERIAL_MODE => {
let shown: Vec<Channel> = channels.into_iter().filter(|channel| on.contains(channel)).collect();
material_card(app, sheet, link, layer, &look, salt);
mapping_band(app, sheet, fill, &shown, layer);
let texture_set = texture_set_size(app, link.size);
let picked = resolution_band(sheet, link.resolution.unwrap_or(CookResolution::TEXTURE_SET), texture_set).filter(|_| LINK_EDITABLE);
if let Some(picked) = picked {
let size = resolution_json(picked);
if app.run("material.link.resolution", with(&json!({"layer": layer.0, "cook": false}), size)).is_some() {
app.cook_link(layer);
}
}
#[cfg(not(target_arch = "wasm32"))]
if sheet.button(ic::ARROW_SQUARE_OUT, tr("Open in MaterialCraft")).clicked() {
crate::dock::open_link_in_materialcraft(app, layer, link);
}
}
None if mode == MATERIAL_MODE => whole_material_card(app, sheet, fill, base, &look, salt),
_ => {
for channel in channels.into_iter().filter(|channel| on.contains(channel)) {
source_card(app, sheet, fill.source(channel), base, SourceSlot::Channel(channel), reader, false);
}
}
}
}
/// Whether a linked material's settings can change here: a change cooks it again, which needs the MaterialCraft CLI the browser has not got (it shows them as they were cooked)
const LINK_EDITABLE: bool = cfg!(not(target_arch = "wasm32"));
/// What the orb shows instead of the whole material, following the Layers panel's channel list: the channel picked there alone (None: the whole material)
fn channel_orb_look(ui: &UiState, fill: &Fill, on: &[Channel], images: &HashMap<String, Arc<ImageRes>>) -> Option<OrbMaterial> {
(!ui.layer_material_view).then(|| OrbMaterial::of_channel(fill, ui.layer_channel, on, images))
}
/// `resolution` as the commands read it: `{"relative": factor}` or `{"fixed": size}`
fn resolution_json(resolution: CookResolution) -> Value {
match resolution {
CookResolution::Relative(factor) => json!({"relative": factor}),
CookResolution::Fixed(size) => json!({"fixed": size}),
}
}
/// The size of the texture set being painted, `fallback` when none is
fn texture_set_size(app: &TextureCraftApp, fallback: u32) -> u32 {
app.session.doc.project.texture_set(app.session.ts()).map_or(fallback, |texture_set| texture_set.resolution)
}
/// A channel's name on its pill: the reference strip's short Title Case words, the full name where it has none
pub(crate) fn pill_name(channel: Channel) -> &'static str {
match channel {
Channel::BaseColor => n_("Color"),
Channel::Metallic => n_("Metal"),
Channel::Roughness => n_("Rough"),
Channel::Normal => n_("Normal"),
Channel::Height => n_("Height"),
Channel::Opacity => n_("Opacity"),
other => other.label(),
}
}
/// A linear colour as the sRGB colour the screen shows
pub(crate) fn shown_color(linear: [f32; 3]) -> Color32 {
let [r, g, b] = linear.map(|channel_value| (linear_to_srgb(channel_value.clamp(0.0, 1.0)) * 255.0).round() as u8);
Color32::from_rgb(r, g, b)
}
/// What the slot's source line says
pub(crate) fn source_line(app: &TextureCraftApp, source: &Source) -> String {
match source {
Source::Uniform(_) => tr("Uniform").to_owned(),
Source::Procedural { pattern, .. } => format!("{} · {}", tr(pattern.kind.label()), tr("procedural")),
Source::Image { name, .. } => match library_alpha_of(name) {
Some(alpha) => format!("{} · {}", tr(&alpha.label), tr("alpha")),
None => format!("{name} · {}", tr("image")),
},
Source::Anchor { anchor, .. } => {
let name = app.session.doc.project.effect(*anchor).map_or_else(|| tr("missing").to_owned(), |(_, effect)| effect.name.clone());
format!("{} · {name}", tr("Anchor"))
}
}
}
pub(crate) fn source_card(
app: &mut TextureCraftApp,
sheet: &mut PropertySheet<'_>,
source: Source,
base: &Value,
slot_of: SourceSlot,
reader: LayerId,
in_card: bool,
) {
let set = |extra: Value| with(base, with(&slot_of.fields(), extra));
let tokens = Tokens::get(sheet.ui.ctx());
let picture = thumbnail(app, &sheet.ui.ctx().clone(), &source);
let line = source_line(app, &source);
let uniform = matches!(source, Source::Uniform(_));
let procedural = matches!(source, Source::Procedural { .. });
let thumb = |painter: &egui::Painter, rect: egui::Rect| paint_thumbnail(painter, rect, &picture, &tokens);
let slot = if in_card {
sheet.slot_in_card(&thumb, slot_of.name(), &line, !uniform)
} else {
sheet.slot(&thumb, slot_of.name(), &line, None, !uniform, procedural)
};
let popup = sheet.ui.make_persistent_id(("source_picker", fill_key(base), slot_of.key()));
if slot.pick.clicked() {
resource_picker::toggle(sheet.ui.ctx(), popup);
}
let current = source_choice(&source);
// From Uniform the picker opens at the top, not at its Uniform tile at the end
let reveal = current != SourceChoice::Uniform;
let uniform = match source {
Source::Uniform(value) => value,
_ => slot_of.default_value(),
};
let ctx = sheet.ui.ctx().clone();
// The anchors below the reader are listed only while the picker is open; an effect's (an instance's inherited mask fill) must also sit below the effect's owner
let effect = base.get("effect").and_then(Value::as_u64).map(LayerId);
let tabs = |thumbs: &mut Thumbs| {
let anchors = match effect {
Some(effect) => project_effect_anchors_below(&app.session.doc.project, reader, effect),
None => anchors_below(&app.session.doc.project, reader),
};
source_tabs(thumbs, &ctx, &app.session.images, &anchors, shown_color(uniform))
};
let picked = resource_picker::show(&slot.pick, popup, &mut app.thumbs, Some(&current), reveal, tabs);
if let Some(choice) = picked.filter(|choice| *choice != current) {
pick_source(app, sheet.ui.ctx(), slot_of, choice, &set);
}
if slot.clear {
app.run("layer.fill.set", set(json!({"value": slot_of.default_value()})));
}
if let Some(name) = crate::dock::image_drop(sheet.ui, &slot.pick) {
app.run("layer.fill.set", set(json!({"image": name})));
}
// A slot in a mode's card shows a pattern's Scale and Contrast like every slot; its other rows and Resolution band would split the card
if in_card {
if let Source::Procedural { pattern, .. } = source {
let mut edited = pattern.clone();
if let Some((key, value, merge)) = scale_and_contrast(sheet, &mut edited) {
let mut settings = json!({"procedural": pattern.kind.label(), "merge": merge});
settings[key] = value;
app.run("layer.fill.set", set(settings));
}
}
return;
}
match source {
Source::Uniform(value) => uniform_rows(app, sheet, slot_of, value, &set),
Source::Procedural { pattern, low, high, .. } => procedural_rows(app, sheet, slot_of, &pattern, [low, high], slot.reset, &set),
Source::Image { normal_format, .. } if slot_of.kind() == ChannelKind::NormalMap => {
if sheet.fold(tr("Attributes"), None, false) {
let formats = [tr("OpenGL"), tr("DirectX")];
let chosen = usize::from(normal_format == NormalFormat::DirectX);
if let Some(picked) = sheet.switch(tr("Normal format"), &formats, chosen) {
app.run("layer.fill.set", set(json!({"normalFormat": if picked == 1 { "directX" } else { "openGl" }})));
}
}
}
Source::Image { .. } | Source::Anchor { .. } => {}
}
sheet.close_card();
}
/// Runs the fill command `choice` asks for on the slot (Import opens the import dialog)
fn pick_source(app: &mut TextureCraftApp, ctx: &egui::Context, slot_of: SourceSlot, choice: SourceChoice, set: &impl Fn(Value) -> Value) {
match choice {
SourceChoice::Uniform => {
app.run("layer.fill.set", set(json!({"value": slot_of.default_value()})));
}
SourceChoice::Procedural(kind) => {
let (low, high) = slot_of.procedural_ends();
app.run("layer.fill.set", set(json!({"procedural": kind.label(), "low": low, "high": high})));
}
SourceChoice::Image(name) => {
app.run("layer.fill.set", set(json!({"image": name})));
}
SourceChoice::Alpha(id) => {
app.run("layer.fill.set", set(json!({"alpha": id})));
}
SourceChoice::Import => crate::menus::invoke(app, ctx, "resource.import"),
SourceChoice::Anchor(anchor) => {
app.run("layer.fill.set", set(json!({"anchor": anchor.0})));
}
}
}
/// The picker's choice `source` is: a library alpha's image is its alpha
match source {
Source::Uniform(_) => SourceChoice::Uniform,
Source::Procedural { pattern, .. } => SourceChoice::Procedural(pattern.kind),
Source::Image { name, .. } => library_alpha_of(name).map_or_else(|| SourceChoice::Image(name.clone()), |alpha| SourceChoice::Alpha(alpha.id.as_str())),
Source::Anchor { anchor, .. } => SourceChoice::Anchor(*anchor),
}
}
/// The source picker's tabs: Resources (Procedurals, Textures with Import... first, Alphas in their shelf groups, Uniform) and the stack's Anchor points
let procedurals =
ProceduralKind::ALL.into_iter().map(|kind| tile(SourceChoice::Procedural(kind), tr(kind.label()), None, TilePicture::Procedural(kind))).collect();
let textures = ResourcePickerItem::textures(images, SourceChoice::Import, |name| SourceChoice::Image(name.to_owned()));
let alphas = alphas::library()
.iter()
.map(|alpha| {
let picture = TilePicture::Texture(thumbs.alpha(ctx, alpha));
tile(SourceChoice::Alpha(alpha.id.as_str()), tr(&alpha.label), Some(tr(alpha.category)), picture)
})
.collect();
let uniform = vec![tile(SourceChoice::Uniform, tr("Uniform value"), None, TilePicture::Swatch(uniform))];
let resources = [(n_("Procedurals"), procedurals), (n_("Textures"), textures), (n_("Alphas"), alphas), (n_("Uniform"), uniform)]
.into_iter()
.map(|(header, items)| PickerGroup { header: Some(tr(header)), items })
.collect();
let anchors = anchors.iter().map(|(anchor, label)| tile(SourceChoice::Anchor(*anchor), label, None, TilePicture::Glyph(ic::ANCHOR))).collect();
vec![
PickerTab { icon: ic::SQUARES_FOUR, name: tr("Resources"), groups: resources },
PickerTab { icon: ic::ANCHOR, name: tr("Anchor points"), groups: vec![PickerGroup { header: None, items: anchors }] },
]
}
/// One tile of the source picker
fn tile(id: SourceChoice, label: &str, caption: Option<&'static str>, picture: TilePicture) -> ResourcePickerItem<SourceChoice> {
ResourcePickerItem { id, label: label.to_owned(), caption, picture }
}
/// A uniform source: the colour bar (a click opens the picker) or the gray ramp with its invert glyph
fn uniform_rows(app: &mut TextureCraftApp, sheet: &mut PropertySheet<'_>, slot_of: SourceSlot, value: [f32; 3], set: &impl Fn(Value) -> Value) {
let label = slot_of.name();
if slot_of.kind() == ChannelKind::Color {
let pick = sheet.color_bar(label, value, app.picking_color, &app.session.doc.project.swatches);
if let Some(color) = take_color_pick(app, pick) {
app.run("layer.fill.set", set(json!({"color": color, "merge": pick.merge})));
}
return;
}
let mut gray = value[0];
let edit = sheet.ramp(label, &mut gray, slot_of.range());
if edit.invert {
let inverted = if slot_of.kind() == ChannelKind::Signed { -gray } else { 1.0 - gray };
app.run("layer.fill.set", set(json!({"value": inverted})));
} else if let Some(merge) = edit.changed {
app.run("layer.fill.set", set(json!({"value": gray, "merge": merge})));
}
}
/// The colour `pick` picked, after starting or ending an eyedropper pick its eyedropper asked for and making the change its Swatches row asked for
pub(crate) fn take_color_pick(app: &mut TextureCraftApp, pick: ColorPick) -> Option<[f32; 3]> {
if pick.eyedropper {
app.picking_color = if app.picking_color == Some(pick.id) { None } else { Some(pick.id) };
}
match pick.swatch {
Some(SwatchEdit::Add(color)) => {
app.run("swatch.add", json!({"color": color}));
}
Some(SwatchEdit::Remove(index)) => {
app.run("swatch.remove", json!({"index": index}));
}
None => {}
}
pick.picked
}
/// A pattern's Scale and Contrast rows; returns the edit (key, value, whether it continues a drag)
fn scale_and_contrast(sheet: &mut PropertySheet<'_>, edited: &mut Procedural) -> Option<(&'static str, Value, bool)> {
let mut edit = None;
if let Some(merge) = sheet.slider(tr("Scale"), &mut edited.scale, PATTERN_SCALE, 2) {
edit = Some(("scale", json!(edited.scale), merge));
}
if let Some(merge) = sheet.slider(tr("Contrast"), &mut edited.contrast, PATTERN_CONTRAST, 2) {
edit = edit.or(Some(("contrast", json!(edited.contrast), merge)));
}
edit
}
/// A pattern's Balance and Seed rows; returns the edit like [`scale_and_contrast`]
fn balance_and_seed(sheet: &mut PropertySheet<'_>, edited: &mut Procedural) -> Option<(&'static str, Value, bool)> {
let mut edit = None;
if let Some(merge) = sheet.signed_slider(tr("Balance"), &mut edited.balance, PATTERN_BALANCE, 2) {
edit = Some(("balance", json!(edited.balance), merge));
}
if sheet.seed(tr("Seed"), &mut edited.seed) {
edit = edit.or(Some(("seed", json!(edited.seed), false)));
}
edit
}
/// A procedural source: Scale and Contrast, then its Attributes (seed, balance, invert and its two values), each sending only its own parameter
fn procedural_rows(
app: &mut TextureCraftApp,
sheet: &mut PropertySheet<'_>,
slot_of: SourceSlot,
pattern: &Procedural,
[low, high]: [[f32; 3]; 2],
reset: bool,
set: &impl Fn(Value) -> Value,
) {
let kind = pattern.kind.label();
if reset {
let fresh = Procedural::new(pattern.kind);
let settings = json!({
"procedural": kind, "scale": fresh.scale, "contrast": fresh.contrast, "seed": fresh.seed,
"balance": fresh.balance, "invert": fresh.invert, "low": low, "high": high, "merge": false,
"resolution": "auto", "customResolution": fresh.resolution.custom, "resolutionFactor": fresh.resolution.factor,
});
app.run("layer.fill.set", set(settings));
return;
}
let mut edited = pattern.clone();
let mut edit = scale_and_contrast(sheet, &mut edited);
if sheet.fold(tr("Attributes"), None, false) {
edit = edit.or(balance_and_seed(sheet, &mut edited));
if sheet.toggle(tr("Invert"), &mut edited.invert) {
edit = edit.or(Some(("invert", json!(edited.invert), false)));
}
let ends = [("low", tr("Low"), low), ("high", tr("High"), high)];
if slot_of.kind() == ChannelKind::Color {
for (key, label, value) in ends {
let pick = sheet.color_bar_led(label, value, app.picking_color, &app.session.doc.project.swatches);
if let Some(picked) = take_color_pick(app, pick) {
edit = edit.or(Some((key, json!(picked), pick.merge)));
}
}
} else {
for (key, label, value) in ends {
let mut gray = value[0];
if let Some(merge) = sheet.slider(label, &mut gray, slot_of.range(), 2) {
edit = edit.or(Some((key, json!([gray, gray, gray]), merge)));
}
}
}
}
// The size the pattern is made at, as a cooked texture would be (the texture set's own by default)
let texture_set = texture_set_size(app, FALLBACK_TEXTURE_SET_SIZE);
if let Some(picked) = resolution_row(sheet, band_size(pattern.resolution, texture_set), texture_set) {
let size = match picked {
CookResolution::Relative(factor) => json!({"resolution": "auto", "resolutionFactor": factor}),
CookResolution::Fixed(size) => json!({"resolution": "custom", "customResolution": size, "resolutionFactor": 0}),
};
app.run("layer.fill.set", set(with(&json!({"procedural": kind}), size)));
return;
}
if let Some((key, value, merge)) = edit {
let mut settings = json!({"procedural": kind, "merge": merge});
settings[key] = value;
app.run("layer.fill.set", set(settings));
}
// The Tile Generator's own parameters and image inputs follow the rows every pattern has
if let Some(tile) = pattern.tile.as_deref() {
let base = set(json!({"low": low, "high": high}));
let target = PatternTarget { command: "layer.fill.set", salt: base.to_string(), base };
sheet.embed(|ui| tile_generator_sections(app, ui, &target, pattern, tile));
}
}
/// The Resolution band's reading of a pattern's saved output resolution: a size of its own is Fixed, any other follows the texture set
fn band_size(resolution: OutputResolution, texture_set: u32) -> CookResolution {
match resolution.mode {
ResolutionMode::Custom => CookResolution::Fixed(resolution.output_size(texture_set, texture_set)),
_ => CookResolution::Relative(resolution.factor),
}
}
/// The Material side: the fill's whole material in one card (the row lists its presets), its inputs, then opening it in MaterialCraft
fn material_card(app: &mut TextureCraftApp, sheet: &mut PropertySheet<'_>, link: &MaterialLink, layer: LayerId, look: &OrbMaterial, salt: FillKey) {
let tokens = Tokens::get(sheet.ui.ctx());
let base = json!({"layer": layer.0, "cook": false});
let slot = sheet.slot(&|painter, rect| material_orb(painter, rect, look, &tokens, ("card", salt)), &link.name, tr("Material"), None, false, false);
let presets: Vec<usize> = (0..link.presets.len()).collect();
let preset_name = |index: usize| link.presets.get(index).map(|preset| preset.name.clone()).unwrap_or_default();
let editable = LINK_EDITABLE;
if editable
&& let (Some(index), _) = sheet.hanging_list(&slot.pick, usize::MAX, &presets, &preset_name, None)
&& app.run("material.link.preset", with(&base, json!({"name": preset_name(index)}))).is_some()
{
app.cook_link(layer);
}
let pending = sheet.ui.make_persistent_id(("material_cook_pending", layer.0));
for param in &link.params {
if let Some((value, merge)) = link_input(sheet, layer, param, editable)
&& app.run("material.link.set", with(&base, json!({"id": param.id, "value": value, "merge": merge}))).is_some()
{
sheet.ui.data_mut(|data| data.insert_temp(pending, true));
}
}
// A drag stores every step; the maps re-cook once the pointer lets go
let waiting = sheet.ui.data(|data| data.get_temp::<bool>(pending)).unwrap_or(false);
if waiting && !sheet.ui.input(|input| input.pointer.any_down()) {
sheet.ui.data_mut(|data| data.remove::<bool>(pending));
app.cook_link(layer);
}
sheet.close_card();
}
/// The Material side of a fill without a linked material: one card holding the built-in material its sources came from (the row lists every plain material, × returns the channels to their defaults)
fn whole_material_card(app: &mut TextureCraftApp, sheet: &mut PropertySheet<'_>, fill: &Fill, base: &Value, look: &OrbMaterial, salt: FillKey) {
let tokens = Tokens::get(sheet.ui.ctx());
let held = fill.material.as_deref().and_then(find);
let name = held.map_or_else(|| tr("None"), |material| tr(material.label));
let slot = sheet.slot(&|painter, rect| material_orb(painter, rect, look, &tokens, ("card", salt)), name, tr("Material"), None, held.is_some(), false);
let popup = sheet.ui.make_persistent_id(("material_picker", salt));
if slot.pick.clicked() {
resource_picker::toggle(sheet.ui.ctx(), popup);
}
let current = held.map(|material| material.id);
let ctx = sheet.ui.ctx().clone();
let picked = resource_picker::show(&slot.pick, popup, &mut app.thumbs, current.as_ref(), current.is_some(), |thumbs| material_tabs(&ctx, thumbs));
if let Some(id) = picked.filter(|id| Some(*id) != current) {
app.run("layer.fill.material", with(base, json!({"material": id})));
}
if slot.clear {
app.run("layer.fill.material", with(base, json!({"material": null})));
}
sheet.close_card();
}
/// The material picker's one tab: every plain material's preview ball, grouped under its shelf category in library order
fn material_tabs(ctx: &egui::Context, thumbs: &mut Thumbs) -> Vec<PickerTab<&'static str>> {
let mut groups: Vec<PickerGroup<&'static str>> = Vec::new();
for material in whole_materials() {
let item = ResourcePickerItem {
id: material.id,
label: tr(material.label).to_owned(),
caption: None,
picture: TilePicture::Texture(thumbs.material(ctx, material.id)),
};
let header = Some(tr(material.category));
match groups.iter_mut().find(|group| group.header == header) {
Some(group) => group.items.push(item),
None => groups.push(PickerGroup { header, items: vec![item] }),
}
}
vec![PickerTab { icon: ic::SPHERE, name: tr("Materials"), groups }]
}
/// Channels mapping: which of the material's outputs each channel that is on reads
fn mapping_band(app: &mut TextureCraftApp, sheet: &mut PropertySheet<'_>, fill: &Fill, shown: &[Channel], layer: LayerId) {
let Some(link) = &fill.link else { return };
if !sheet.band(tr("Channels mapping"), true, None, None).open {
return;
}
let outputs: Vec<String> = fill.link_outputs().into_keys().collect();
let indices: Vec<usize> = (0..outputs.len()).collect();
for channel in shown {
let reads = link.output_of(*channel);
let current = outputs.iter().position(|output| output == reads).unwrap_or(usize::MAX);
let name = |index: usize| outputs.get(index).map_or(reads, String::as_str).to_owned();
if let (Some(index), _) = sheet.dropdown(tr(channel.label()), current, &indices, name, None)
&& let Some(output) = outputs.get(index)
{
app.run("material.link.map", json!({"layer": layer.0, "channel": channel.id(), "output": output}));
}
}
}
/// One input of the material: a slider for numbers, a toggle, a dropdown for choices, an egui editor for colours and vectors; its new typed value when it changed and whether it continues a drag
fn link_input(sheet: &mut PropertySheet<'_>, layer: LayerId, param: &LinkParam, editable: bool) -> Option<(Value, bool)> {
let kind = param.default.get("t").and_then(Value::as_str).unwrap_or("");
let value = param.value.get("v").unwrap_or(&Value::Null);
let number = value.as_f64().unwrap_or(0.0) as f32;
let (low, high) = if param.max > param.min { (param.min, param.max) } else { (0.0, 1.0) };
let changed = match kind {
"bool" => {
let mut on = value.as_bool().unwrap_or(number != 0.0);
sheet.toggle(&param.label, &mut on).then(|| (json!(on), false))
}
"enum" if !param.options.is_empty() => {
let options: Vec<usize> = (0..param.options.len()).collect();
let name = |index: usize| param.options.get(index).cloned().unwrap_or_default();
sheet.dropdown(&param.label, number.max(0.0) as usize, &options, name, None).0.map(|index| (json!(index), false))
}
"float" => {
let mut edited = number;
sheet.slider(&param.label, &mut edited, low.min(number)..=high.max(number), FLOAT_DECIMALS).map(|merge| (json!(edited), merge))
}
"int" | "enum" => {
let mut edited = number;
let moved = sheet.slider(&param.label, &mut edited, low.min(number)..=high.max(number), 0).is_some();
// Whole numbers: a press's first whole-number change starts its undo step, moves that round to the value it has send nothing (no step, no cook)
let whole = edited.round();
let press = sheet.ui.make_persistent_id(("link_input_press", layer.0, &param.id));
press_edit(sheet.ui, press, moved && whole != number).map(|merge| (json!(whole), merge))
}
// Colours and vectors keep their egui editors until the sheet draws them
_ => sheet.embed(|ui| crate::dock::link_param_editor(ui, layer, param)),
};
changed.filter(|_| editable)
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn the_orb_shows_the_channel_the_layers_panel_shows_and_the_whole_material_on_material() {
let mut ui = UiState::default();
let on = [Channel::BaseColor, Channel::Roughness];
let whole = OrbMaterial::of_fill(&Fill::default(), &on, &HashMap::new());
let starting = channel_orb_look(&ui, &Fill::default(), &on, &HashMap::new());
ui.layer_material_view = false;
ui.layer_channel = Channel::Roughness;
let roughness = channel_orb_look(&ui, &Fill::default(), &on, &HashMap::new()).unwrap();
assert!(starting.is_none(), "the list starts on Material: the whole material");
assert_eq!(whole.alone(), None);
assert_eq!(roughness.alone(), Some(Channel::Roughness));
assert_ne!(whole.key(), roughness.key(), "a new pick draws a new orb");
}
}
@@ -0,0 +1,800 @@
//! A fill's Material section: the channel strip turns channels on and off, each slot's row lists the sources, ⟲ and × restore and clear, the ramp inverts, a linked material maps its channels and picks its resolution
use std::sync::Arc;
use egui::Role;
use egui_kittest::Harness;
use egui_kittest::kittest::{NodeT, Queryable};
use serde_json::json;
use texturecraft_engine::compose::ImageRes;
use texturecraft_engine::core::{Channel, CookResolution, LayerId, LayerKind, LinkParam, MaterialLink, Procedural, ProceduralKind, Source};
use texturecraft_ui_egui::TextureCraftApp;
use texturecraft_ui_egui::screen_pick::{PickOutcome, ScreenPick};
use crate::fill_support::{click_node, fill_app, fill_of};
use crate::filter_support::{along, click_at, drag, undo_depth};
use crate::{SETTLE_FRAMES, TEXTURE_RESOLUTION};
/// Tall enough that Properties shows the whole fill and an open source list without scrolling
const WINDOW_SIZE: egui::Vec2 = egui::vec2(1600.0, 1600.0);
/// Frames for the shelf's and the picker's thumbnails to render a few per frame, enough for every pattern were all of them asked for
const THUMBNAIL_FRAMES: usize = 200;
/// Frames for a scroll to bring a control into view
const SCROLL_FRAMES: usize = 25;
/// The app with a new fill layer (`settings` given to layer.add.fill) selected and its Material tab clicked, and the layer's id
fn app_with_fill(settings: serde_json::Value) -> (Harness<'static, TextureCraftApp>, LayerId) {
fill_app(settings, None, Some("Material"), WINDOW_SIZE)
}
/// The source `channel` of the fill `layer` reads
fn source(harness: &Harness<'_, TextureCraftApp>, layer: LayerId, channel: Channel) -> Source {
fill_of(harness, layer).source(channel)
}
fn click(harness: &mut Harness<'_, TextureCraftApp>, role: Role, label: &str) {
// A link without a package fails to re-cook with a toast, which must not take the click
harness.state_mut().toasts.clear();
click_node(harness, role, label);
}
/// Scrolls the `role` named `label` into view (the scroll animates for about twenty frames), then clicks it
fn click_below(harness: &mut Harness<'_, TextureCraftApp>, role: Role, label: &str) {
harness.get_by_role_and_label(role, label).scroll_to_me();
harness.run_steps(SCROLL_FRAMES);
click(harness, role, label);
}
/// Clicks the eyedropper at the end of the Base color bar's row in the panel (the open picker has its own)
fn click_bar_eyedropper(harness: &mut Harness<'_, TextureCraftApp>) {
let bar = harness.get_by_role_and_label(Role::Button, "Base color").rect();
let eyedropper = harness
.get_all_by_role_and_label(Role::Button, "Pick color")
.find(|node| bar.y_range().contains(node.rect().center().y) && node.rect().left() >= bar.right())
.unwrap()
.rect();
click_at(harness, eyedropper.center());
}
/// Clicks the open picker's own eyedropper, beside its hex field
fn click_picker_eyedropper(harness: &mut Harness<'_, TextureCraftApp>) {
let hex = harness.get_by_role_and_label(Role::TextInput, "Hex color").rect();
let title = harness.get_by_role_and_label(Role::TitleBar, "Base color").rect();
let in_picker_row = |at: egui::Pos2| hex.y_range().contains(at.y) && at.x >= hex.right() && at.x <= title.right() + CLOSE_ROOM;
let eyedropper = harness.get_all_by_role_and_label(Role::Button, "Pick color").map(|node| node.rect().center()).find(|at| in_picker_row(*at)).unwrap();
click_at(harness, eyedropper);
}
/// Clicks the `role` named `label` that sits in the row of the slot named `slot` (bands above have their own ⟲)
fn click_in_slot(harness: &mut Harness<'_, TextureCraftApp>, slot: &str, role: Role, label: &str) {
let row = harness.get_by_role_and_label(Role::ComboBox, slot).rect();
let at = harness.get_all_by_role_and_label(role, label).map(|node| node.rect().center()).find(|at| row.contains(*at)).unwrap();
click_at(harness, at);
}
#[test]
fn the_channel_strip_turns_a_channel_and_its_card_off_and_on() {
let (mut harness, layer) = app_with_fill(json!({}));
assert!(harness.query_by_role_and_label(Role::ComboBox, "Metallic").is_some(), "Metallic is on: its card shows");
click(&mut harness, Role::CheckBox, "Metal");
let channels = &harness.state().session.doc.project.layer(layer).unwrap().channels;
assert!(!channels.contains_key(&Channel::Metallic), "off in the strip, the fill stops writing Metallic");
assert!(harness.query_by_role_and_label(Role::ComboBox, "Metallic").is_none(), "a channel that is off has no card");
click(&mut harness, Role::CheckBox, "Metal");
assert!(harness.state().session.doc.project.layer(layer).unwrap().channels.contains_key(&Channel::Metallic));
assert!(harness.query_by_role_and_label(Role::ComboBox, "Metallic").is_some());
}
#[test]
fn a_slot_lists_its_sources_restores_a_procedural_and_clears_back_to_uniform() {
let (mut harness, layer) = app_with_fill(json!({}));
click(&mut harness, Role::ComboBox, "Metallic");
click(&mut harness, Role::ListBoxOption, ProceduralKind::Clouds.label());
let Source::Procedural { pattern, .. } = source(&harness, layer, Channel::Metallic) else { panic!("a procedural") };
assert_eq!(pattern.kind, ProceduralKind::Clouds);
assert!(harness.query_by_role_and_label(Role::Slider, "Contrast").is_some(), "a procedural shows its Scale and Contrast");
texturecraft_engine::execute(
&mut harness.state_mut().session,
"layer.fill.set",
&json!({"layer": layer.0, "channel": "metallic", "procedural": "Clouds", "scale": 9.0, "seed": 7}),
)
.unwrap();
harness.run_steps(SETTLE_FRAMES);
click_in_slot(&mut harness, "Metallic", Role::Button, "Restore defaults");
let Source::Procedural { pattern, .. } = source(&harness, layer, Channel::Metallic) else { panic!("still a procedural") };
assert_eq!(pattern, Procedural::new(ProceduralKind::Clouds), "⟲ keeps the pattern and restores its settings");
click_in_slot(&mut harness, "Metallic", Role::Button, "Clear");
assert_eq!(source(&harness, layer, Channel::Metallic), Source::uniform_of(Channel::Metallic), "× goes back to a uniform value");
}
/// A pattern's thumbnail is made only once its tile is drawn: a search renders the patterns it shows, not every pattern
#[test]
fn searching_the_source_picker_renders_only_the_shown_pattern_thumbnails() {
let (mut harness, layer) = app_with_fill(json!({}));
let pattern_thumbnails = |harness: &Harness<'_, TextureCraftApp>| {
harness.ctx.tex_manager().read().allocated().filter(|(_, texture)| texture.name.starts_with("thumb_proc:")).count()
};
click(&mut harness, Role::ComboBox, "Metallic");
harness.event(egui::Event::Text("Smooth fur".into()));
harness.run_steps(THUMBNAIL_FRAMES);
let after_search = pattern_thumbnails(&harness);
let rendered = |name: &str| harness.ctx.tex_manager().read().allocated().any(|(_, texture)| texture.name == name);
assert!(rendered("thumb_proc:SmoothFur"), "the pattern the search shows gets its thumbnail");
assert!(after_search < ProceduralKind::ALL.len(), "{after_search} of {} pattern thumbnails made", ProceduralKind::ALL.len());
click(&mut harness, Role::ListBoxOption, ProceduralKind::SmoothFur.label());
let Source::Procedural { pattern, .. } = source(&harness, layer, Channel::Metallic) else { panic!("a procedural") };
assert_eq!(pattern.kind, ProceduralKind::SmoothFur);
assert_eq!(pattern_thumbnails(&harness), after_search, "the pick reuses the thumbnail it showed");
let context = harness.ctx.clone();
drop(harness);
let left = context.tex_manager().read().allocated().filter(|(_, texture)| texture.name.starts_with("thumb_proc:")).count();
assert_eq!(left, 0, "closing the app releases the pattern thumbnails");
}
/// A project image's thumbnail is made once its tile scrolls into view, not when the picker opens, and goes with the image
#[test]
fn source_picker_images_render_on_scroll_and_release_on_removal() {
const IMAGE_COUNT: usize = 128;
const IMAGE_SIDE: u32 = 64;
let (mut harness, layer) = app_with_fill(json!({}));
let session = &mut harness.state_mut().session;
for index in 0..IMAGE_COUNT {
let name = format!("picker-image-{index:03}.png");
let texels = (IMAGE_SIDE * IMAGE_SIDE) as usize;
session.doc.resources.insert(name.clone(), Arc::new(vec![0]));
session.images.insert(name, Arc::new(ImageRes::new(IMAGE_SIDE, IMAGE_SIDE, vec![[0.5; 4]; texels], false)));
}
let image_thumbnails = |harness: &Harness<'_, TextureCraftApp>| {
harness.ctx.tex_manager().read().allocated().filter(|(_, texture)| texture.name.starts_with("res_picker-image-")).count()
};
click(&mut harness, Role::ComboBox, "Metallic");
harness.run_steps(THUMBNAIL_FRAMES);
let opened = image_thumbnails(&harness);
assert!(opened < IMAGE_COUNT, "opening the picker makes thumbnails only for the tiles in view: {opened}");
let last = format!("picker-image-{:03}.png", IMAGE_COUNT - 1);
harness.get_by_role_and_label(Role::ListBoxOption, &last).scroll_to_me();
harness.run_steps(THUMBNAIL_FRAMES);
let scrolled = image_thumbnails(&harness);
assert!(scrolled > opened, "a scroll makes the thumbnails of the tiles it brings into view: {opened} -> {scrolled}");
click(&mut harness, Role::ListBoxOption, &last);
assert_eq!(source(&harness, layer, Channel::Metallic), Source::image(last));
let app = harness.state_mut();
app.session.images.clear();
app.thumbs.sync_images(&app.session.images, app.session.revision + 1);
assert_eq!(image_thumbnails(&harness), 0, "removed images release their picker thumbnails");
}
/// Dragging the pattern's Contrast changes only the contrast: the pattern keeps its balance, invert, seed, scale and values
#[test]
fn dragging_a_pattern_slider_changes_only_its_own_parameter() {
let (mut harness, layer) = app_with_fill(json!({}));
let pattern = json!({
"layer": layer.0, "channel": "metallic", "procedural": "Clouds", "scale": 9.0, "contrast": 1.0, "seed": 7,
"balance": 0.25, "invert": true, "low": [0.2, 0.2, 0.2], "high": [0.8, 0.8, 0.8],
});
texturecraft_engine::execute(&mut harness.state_mut().session, "layer.fill.set", &pattern).unwrap();
harness.run_steps(SETTLE_FRAMES);
let Source::Procedural { pattern: before, low, high, .. } = source(&harness, layer, Channel::Metallic) else { panic!("a procedural") };
harness.get_by_role_and_label(Role::Slider, "Contrast").scroll_to_me();
harness.run_steps(SCROLL_FRAMES);
let track = harness.get_by_role_and_label(Role::Slider, "Contrast").rect();
let from = track.center();
drag(&mut harness, from, from + egui::vec2(track.width() / 4.0, 0.0));
let Source::Procedural { pattern: after, low: after_low, high: after_high, .. } = source(&harness, layer, Channel::Metallic) else {
panic!("still a procedural")
};
assert_ne!(after.contrast, before.contrast, "the drag changes the contrast");
assert_eq!(Procedural { contrast: before.contrast, ..after }, before, "the rest of the pattern stays");
assert_eq!((after_low, after_high), (low, high), "the pattern's values stay");
}
#[test]
fn a_uniform_gray_ramp_inverts_its_value() {
let (mut harness, layer) = app_with_fill(json!({"roughness": 0.3}));
texturecraft_engine::execute(&mut harness.state_mut().session, "layer.fill.set", &json!({"layer": layer.0, "channel": "roughness", "solo": true})).unwrap();
harness.run_steps(SETTLE_FRAMES);
click(&mut harness, Role::Button, "Invert");
let Source::Uniform(value) = source(&harness, layer, Channel::Roughness) else { panic!("uniform") };
assert!((value[0] - 0.7).abs() < 1e-5, "1 - 0.3: {value:?}");
}
#[test]
fn a_linked_material_shows_its_inputs_and_the_switch_shows_its_channels() {
let (mut harness, layer) = app_with_fill(json!({}));
assert!(harness.query_by_role_and_label(Role::RadioButton, "Material").is_some(), "every fill has the switch");
let wear = float_param("wear", "Wear", 0.5);
link_fill(&mut harness, layer, vec![wear], &[]);
assert!(harness.query_by_role_and_label(Role::ComboBox, "Painted steel").is_some(), "the Material side shows the whole material");
assert!(harness.query_by_role_and_label(Role::Slider, "Wear").is_some(), "with its inputs");
assert!(harness.query_by_role_and_label(Role::ComboBox, "Metallic").is_none(), "and no channel cards");
click(&mut harness, Role::RadioButton, "Channels");
assert!(harness.query_by_role_and_label(Role::ComboBox, "Metallic").is_some(), "the Channels side shows a card per channel");
assert!(harness.query_by_role_and_label(Role::Slider, "Wear").is_none());
}
/// A drag on a linked material's number input is one undo step, however many frames it spans
#[test]
fn dragging_a_linked_material_input_adds_one_undo_step() {
let (mut harness, layer) = app_with_fill(json!({}));
let wear = float_param("wear", "Wear", 0.25);
link_fill(&mut harness, layer, vec![wear], &[]);
let steps = undo_depth(&harness);
let track = harness.get_by_role_and_label(Role::Slider, "Wear").rect();
let from = track.center();
drag(&mut harness, from, from + egui::vec2(track.width() / 4.0, 0.0));
let fill = fill_of(&harness, layer);
assert_ne!(fill.link.as_deref().unwrap().params[0].value, json!({"t": "float", "v": 0.25}), "the drag changes the input");
assert_eq!(undo_depth(&harness), steps + 1, "every frame of the drag merges into one step");
}
/// A click inside a linked whole-number input's current band is no edit (no undo step, no re-cook); a drag across whole numbers is one step
#[test]
fn a_linked_whole_number_input_changes_only_on_a_new_whole_number() {
let (mut harness, layer) = app_with_fill(json!({}));
let rings = LinkParam { value: json!({"t": "int", "v": 3}), default: json!({"t": "int", "v": 3}), max: 10.0, ..float_param("rings", "Rings", 0.0) };
link_fill(&mut harness, layer, vec![rings], &[]);
harness.state_mut().toasts.clear();
let steps = undo_depth(&harness);
let track = harness.get_by_role_and_label(Role::Slider, "Rings").rect();
// A link without a package fails to re-cook with a toast: no toast, no cook
click_at(&mut harness, along(track, 0.32));
harness.run_steps(SETTLE_FRAMES);
assert_eq!(undo_depth(&harness), steps, "3.2 rounds to the 3 the input holds: no undo step");
assert!(harness.state().toasts.is_empty(), "and no re-cook");
drag(&mut harness, along(track, 0.3), along(track, 0.53));
harness.run_steps(SETTLE_FRAMES);
assert_eq!(fill_of(&harness, layer).link.unwrap().params[0].value, json!({"t": "int", "v": 5}), "the drag ends on 5");
assert_eq!(undo_depth(&harness), steps + 1, "the drag's whole numbers merge into one step");
}
/// A drag in a linked material's colour picker is one undo step, however many frames it spans
#[test]
fn dragging_in_a_linked_colour_picker_adds_one_undo_step() {
let (mut harness, layer) = app_with_fill(json!({}));
let gray = json!({"t": "color", "v": [0.5, 0.5, 0.5, 1.0]});
let tint = LinkParam { value: gray.clone(), default: gray.clone(), ..float_param("tint", "Tint", 0.0) };
link_fill(&mut harness, layer, vec![tint], &[]);
let steps = undo_depth(&harness);
// The swatch sits right of its label; its picker's saturation and value square lies under the R, G, B row
let label = harness.get_by_label("Tint").rect();
let swatch = egui::pos2(label.right() + SWATCH_REACH, label.center().y);
harness.drag_at(swatch);
harness.drop_at(swatch);
harness.run_steps(SETTLE_FRAMES);
let copy = harness.get_by_role_and_label(Role::Button, "Copy RGB values").rect();
let red = harness
.get_all_by_role(Role::SpinButton)
.map(|node| node.rect())
.filter(|field| field.center().y < copy.bottom())
.min_by(|a, b| a.left().total_cmp(&b.left()))
.unwrap();
let from = egui::pos2(red.left() + SQUARE_REACH, copy.bottom() + SQUARE_REACH);
drag(&mut harness, from, from + egui::vec2(SQUARE_REACH / 2.0, SQUARE_REACH / 2.0));
let fill = fill_of(&harness, layer);
assert_ne!(fill.link.as_deref().unwrap().params[0].value, gray, "the drag changes the colour");
assert_eq!(undo_depth(&harness), steps + 1, "every frame of the drag merges into one step");
}
/// From a label's right edge into the colour swatch beside it
const SWATCH_REACH: f32 = 30.0;
/// From the picker's top-left content corner into its saturation and value square, and half of it for the drag
const SQUARE_REACH: f32 = 80.0;
#[test]
fn a_linked_material_maps_its_channels_and_picks_its_resolution() {
let (mut harness, layer) = app_with_fill(json!({}));
link_fill(&mut harness, layer, Vec::new(), &[("baseColor", "steel_base.png"), ("roughness", "steel_rough.png")]);
let link = |harness: &Harness<'_, TextureCraftApp>| *fill_of(harness, layer).link.unwrap();
// Channels mapping: the Roughness row lists the outputs; picking one makes Roughness read it
click_below(&mut harness, Role::ComboBox, "roughness");
click(&mut harness, Role::ListBoxOption, "baseColor");
assert_eq!(link(&harness).output_of(Channel::Roughness), "baseColor");
assert!(matches!(source(&harness, layer, Channel::Roughness), Source::Image { name, .. } if name == "steel_base.png"));
// Resolution: folded until clicked; Fixed keeps the size, the list picks another, Relative goes back to a factor
assert!(harness.query_by_role_and_label(Role::RadioButton, "Fixed").is_none(), "Resolution starts folded");
click_below(&mut harness, Role::Button, "Resolution");
click_below(&mut harness, Role::RadioButton, "Fixed");
assert_eq!(link(&harness).resolution, Some(CookResolution::Fixed(TEXTURE_RESOLUTION)));
click_below(&mut harness, Role::ComboBox, "256 × 256");
click(&mut harness, Role::ListBoxOption, "1024 × 1024");
assert_eq!(link(&harness).resolution, Some(CookResolution::Fixed(1024)));
click_below(&mut harness, Role::RadioButton, "Relative");
assert_eq!(link(&harness).resolution, Some(CookResolution::Relative(2)), "1024 is the texture set's ×4");
}
/// Links the fill `layer` to a material with `params` and image `outputs` (output, image), as a cooked link leaves it
fn link_fill(harness: &mut Harness<'_, TextureCraftApp>, layer: LayerId, params: Vec<LinkParam>, outputs: &[(&str, &str)]) {
let link = MaterialLink {
name: "Painted steel".into(),
package: String::new(),
graph: "main".into(),
params,
presets: Vec::new(),
inputs: Vec::new(),
size: 256,
resolution: None,
mapping: Default::default(),
outputs: outputs.iter().map(|(output, image)| ((*output).to_owned(), (*image).to_owned())).collect(),
};
if let Some(LayerKind::Fill(fill)) = harness.state_mut().session.doc.project.layers.get_mut(&layer).map(|layer| &mut layer.kind) {
fill.link = Some(Box::new(link));
}
harness.run_steps(SETTLE_FRAMES);
}
/// A 0..1 number input `id` shown as `label`, at `value` and by default
fn float_param(id: &str, label: &str, value: f64) -> LinkParam {
let value = json!({"t": "float", "v": value});
LinkParam { id: id.into(), label: label.into(), group: String::new(), value: value.clone(), default: value, min: 0.0, max: 1.0, options: Vec::new() }
}
/// Types the sRGB code `hex` into the open picker's Hex field and confirms it
fn type_hex(harness: &mut Harness<'_, TextureCraftApp>, hex: &str) {
click(harness, Role::TextInput, "Hex color");
harness.key_press_modifiers(egui::Modifiers::COMMAND, egui::Key::A);
harness.event(egui::Event::Text(hex.into()));
harness.key_press(egui::Key::Enter);
harness.run_steps(SETTLE_FRAMES);
}
/// The fill's uniform base colour (linear)
fn base_color(harness: &Harness<'_, TextureCraftApp>, layer: LayerId) -> [f32; 3] {
let Source::Uniform(color) = source(harness, layer, Channel::BaseColor) else { panic!("a uniform colour") };
color
}
#[test]
fn the_colour_bar_opens_the_picker_which_types_restores_and_waits_for_an_eyedropper_click() {
let (mut harness, layer) = app_with_fill(json!({"color": [0.2, 0.2, 0.2]}));
let before = base_color(&harness, layer);
click(&mut harness, Role::Button, "Base color");
assert!(harness.query_by_role_and_label(Role::ComboBox, "sRGB").is_some(), "the picker shows its colour space");
type_hex(&mut harness, "FF8000");
let typed = base_color(&harness, layer);
let expected = [1.0, texturecraft_engine::texel::srgb_to_linear(128.0 / 255.0), 0.0];
assert!(typed.iter().zip(expected).all(|(a, b)| (a - b).abs() < 1e-3), "the typed sRGB code is stored linear: {typed:?}");
click(&mut harness, Role::ComboBox, "HSV");
click(&mut harness, Role::ListBoxOption, "RGB");
assert!(harness.query_by_role_and_label(Role::Slider, "R").is_some(), "the sliders edit R, G and B");
assert!(harness.query_by_role_and_label(Role::ComboBox, "sRGB").is_some(), "picking from its own list keeps the picker open");
click(&mut harness, Role::Button, "Previous color");
let restored = base_color(&harness, layer);
assert!(restored.iter().zip(before).all(|(a, b)| (a - b).abs() < 1e-4), "a click on the previous colour restores it: {restored:?} {before:?}");
click_picker_eyedropper(&mut harness);
harness.run_steps(SETTLE_FRAMES);
assert!(harness.state().picking_color.is_some(), "the eyedropper waits for a click on the model");
}
#[test]
fn the_picker_is_a_window_beside_the_panel_that_its_title_drags_and_its_close_or_escape_closes() {
let (mut harness, _) = app_with_fill(json!({"color": [0.2, 0.2, 0.2]}));
click(&mut harness, Role::Button, "Base color");
let bar = harness.get_by_role_and_label(Role::Button, "Base color").rect();
let title = harness.get_by_role_and_label(Role::TitleBar, "Base color").rect();
let space = harness.get_by_role_and_label(Role::ComboBox, "sRGB").rect();
assert!(title.right() <= bar.left(), "the window stands beside the panel, off its rows: {title:?} {bar:?}");
assert!(title.top() <= bar.top() + 1.0, "level with the bar, or raised to stay on screen: {title:?} {bar:?}");
assert!(space.width() < title.width() / 3.0, "the colour space dropdown is as wide as its text: {space:?}");
let from = title.left_center() + egui::vec2(20.0, 0.0);
let by = egui::vec2(-120.0, 90.0);
harness.hover_at(from);
harness.event(egui::Event::PointerButton { pos: from, button: egui::PointerButton::Primary, pressed: true, modifiers: egui::Modifiers::NONE });
harness.run_steps(1);
for step in 1..=4 {
harness.hover_at(from + by * (step as f32 / 4.0));
harness.run_steps(1);
}
harness.event(egui::Event::PointerButton { pos: from + by, button: egui::PointerButton::Primary, pressed: false, modifiers: egui::Modifiers::NONE });
harness.run_steps(SETTLE_FRAMES);
let moved = harness.get_by_role_and_label(Role::TitleBar, "Base color").rect();
assert!((moved.min - (title.min + by)).length() < 1.0, "the title bar drags the window: {moved:?} from {title:?}");
assert!(harness.query_by_role_and_label(Role::ComboBox, "sRGB").is_some(), "a drag on the title keeps it open");
let close = harness
.get_all_by_role_and_label(Role::Button, "Close")
.find(|node| moved.y_range().contains(node.rect().center().y) && node.rect().left() >= moved.right())
.unwrap()
.rect();
click_at(&mut harness, close.center());
assert!(harness.query_by_role_and_label(Role::TitleBar, "Base color").is_none(), "× closes it");
click(&mut harness, Role::Button, "Base color");
let reopened = harness.get_by_role_and_label(Role::TitleBar, "Base color").rect();
assert!((reopened.min - moved.min).length() < 1.0, "it opens again where it was dragged: {reopened:?}");
harness.key_press(egui::Key::Escape);
harness.run_steps(SETTLE_FRAMES);
assert!(harness.query_by_role_and_label(Role::TitleBar, "Base color").is_none(), "Escape closes it");
}
#[test]
fn escape_ends_an_eyedropper_pick_before_the_picker_and_an_alt_orbit_keeps_the_picker_open() {
let (mut harness, _) = app_with_fill(json!({"color": [0.2, 0.2, 0.2]}));
click(&mut harness, Role::Button, "Base color");
click_bar_eyedropper(&mut harness);
harness.run_steps(SETTLE_FRAMES);
assert!(harness.state().picking_color.is_some(), "the eyedropper waits for a click on the model");
harness.key_press(egui::Key::Escape);
harness.run_steps(SETTLE_FRAMES);
assert!(harness.state().picking_color.is_none(), "Escape ends the pick");
assert!(harness.query_by_role_and_label(Role::TitleBar, "Base color").is_some(), "the same Escape leaves the picker open");
let view = harness.state().viewport_rect.center();
let alt = egui::Modifiers::ALT;
harness.event(egui::Event::ModifiersChanged(alt));
harness.hover_at(view);
harness.event(egui::Event::PointerButton { pos: view, button: egui::PointerButton::Primary, pressed: true, modifiers: alt });
harness.run_steps(1);
harness.hover_at(view + egui::vec2(40.0, 10.0));
harness.run_steps(1);
harness.event(egui::Event::PointerButton { pos: view + egui::vec2(40.0, 10.0), button: egui::PointerButton::Primary, pressed: false, modifiers: alt });
harness.event(egui::Event::ModifiersChanged(egui::Modifiers::NONE));
harness.run_steps(SETTLE_FRAMES);
assert!(harness.query_by_role_and_label(Role::TitleBar, "Base color").is_some(), "an Alt+drag on the model orbits and keeps the picker open");
harness.key_press(egui::Key::Escape);
harness.run_steps(SETTLE_FRAMES);
assert!(harness.query_by_role_and_label(Role::TitleBar, "Base color").is_none(), "the next Escape closes the picker");
}
/// A secondary-button press and release at `pos`, a frame apart, as a real right-click arrives
fn right_click(harness: &mut Harness<'_, TextureCraftApp>, pos: egui::Pos2) {
let button = egui::PointerButton::Secondary;
harness.hover_at(pos);
harness.run_steps(1);
for pressed in [true, false] {
harness.event(egui::Event::PointerButton { pos, button, pressed, modifiers: egui::Modifiers::NONE });
harness.run_steps(1);
}
harness.run_steps(SETTLE_FRAMES);
}
#[test]
fn the_swatches_row_keeps_the_picker_colour_in_the_project_applies_it_on_a_click_and_removes_it_from_its_menu() {
let (mut harness, layer) = app_with_fill(json!({"color": [0.2, 0.2, 0.2]}));
let before = base_color(&harness, layer);
click(&mut harness, Role::Button, "Base color");
type_hex(&mut harness, "FF8000");
let orange = base_color(&harness, layer);
let add = harness.get_by_role_and_label(Role::Button, "Add swatch").rect();
let space = harness.get_by_role_and_label(Role::ComboBox, "sRGB").rect();
assert!(add.top() > space.bottom() && (add.left() - space.left()).abs() < 1.0, "the row is under the picker, at its left edge: {add:?}");
click_at(&mut harness, add.center());
assert_eq!(harness.state().session.doc.project.swatches, vec![orange], "+ keeps the picker's colour in the project");
assert!(harness.query_by_role_and_label(Role::ComboBox, "sRGB").is_some(), "the picker stays open");
let depth = undo_depth(&harness);
let kept = harness.get_by_role_and_label(Role::Button, "#FF8000").rect();
click_at(&mut harness, kept.center());
assert_eq!(undo_depth(&harness), depth, "a swatch the picker already shows changes nothing");
click(&mut harness, Role::Button, "Previous color");
assert_eq!(base_color(&harness, layer), before);
let chip = harness.get_by_role_and_label(Role::Button, "#FF8000").rect();
let moved_add = harness.get_by_role_and_label(Role::Button, "Add swatch").rect();
assert!((chip.left() - add.left()).abs() < 1.0 && moved_add.left() > chip.right(), "the swatch takes the + chip's place, + moves right");
click_at(&mut harness, chip.center());
assert_eq!(base_color(&harness, layer), orange, "a click on a swatch applies it");
assert!(harness.query_by_role_and_label(Role::ComboBox, "sRGB").is_some(), "applying keeps the picker open");
right_click(&mut harness, chip.center());
let remove = harness.get_by_role_and_label(Role::Button, "Remove swatch").rect();
click_at(&mut harness, remove.center());
assert!(harness.state().session.doc.project.swatches.is_empty(), "its right-click menu removes it");
assert!(harness.query_by_role_and_label(Role::ComboBox, "sRGB").is_some(), "a pick in the menu keeps the picker open");
}
#[test]
fn a_hex_code_left_as_it_opened_is_no_edit() {
let (mut harness, layer) = app_with_fill(json!({"color": [0.2, 0.2, 0.2]}));
click(&mut harness, Role::Button, "Base color");
let depth = undo_depth(&harness);
click(&mut harness, Role::TextInput, "Hex color");
harness.key_press(egui::Key::Enter);
harness.run_steps(SETTLE_FRAMES);
assert_eq!(base_color(&harness, layer), [0.2, 0.2, 0.2], "the colour is not rounded to the code it shows");
assert_eq!(undo_depth(&harness), depth, "no undo step");
}
#[test]
fn a_hex_code_typed_is_applied_when_another_widget_takes_the_focus() {
let (mut harness, layer) = app_with_fill(json!({"color": [0.2, 0.2, 0.2]}));
click(&mut harness, Role::Button, "Base color");
let depth = undo_depth(&harness);
click(&mut harness, Role::TextInput, "Hex color");
harness.key_press_modifiers(egui::Modifiers::COMMAND, egui::Key::A);
harness.event(egui::Event::Text("FF8000".into()));
harness.run_steps(1);
// As a shortcut focusing another field would: the field hears it lost the focus only a pass later
harness.ctx.memory_mut(|memory| memory.request_focus(egui::Id::unique("another field")));
harness.run_steps(SETTLE_FRAMES);
let [red, green, blue] = base_color(&harness, layer);
assert!(red > green && green > blue, "the code typed is the colour: {:?}", [red, green, blue]);
assert_eq!(undo_depth(&harness), depth + 1, "one undo step");
}
#[test]
fn a_hex_code_half_typed_when_a_press_closes_the_picker_is_gone_when_it_opens_again() {
let (mut harness, layer) = app_with_fill(json!({"color": [0.2, 0.2, 0.2]}));
click(&mut harness, Role::Button, "Base color");
click(&mut harness, Role::TextInput, "Hex color");
harness.key_press_modifiers(egui::Modifiers::COMMAND, egui::Key::A);
harness.event(egui::Event::Text("FF8000".into()));
harness.run_steps(1);
let view = harness.state().viewport_rect.center();
click_at(&mut harness, view);
assert!(harness.query_by_role_and_label(Role::TitleBar, "Base color").is_none(), "the press closes the picker");
assert_eq!(base_color(&harness, layer), [0.2, 0.2, 0.2], "closing applies nothing");
let depth = undo_depth(&harness);
click(&mut harness, Role::Button, "Base color");
click(&mut harness, Role::TextInput, "Hex color");
harness.key_press(egui::Key::Enter);
harness.run_steps(SETTLE_FRAMES);
assert_eq!(base_color(&harness, layer), [0.2, 0.2, 0.2], "the field shows the colour's own code, not the text typed before");
assert_eq!(undo_depth(&harness), depth, "no undo step");
}
/// The open picker's frame: its title bar's top and sides, down to the air under the + chip
fn picker_face(harness: &Harness<'_, TextureCraftApp>) -> egui::Rect {
// The air under the picker's last line (color_bar.rs PICKER_BOTTOM)
const PICKER_BOTTOM: f32 = 10.0;
let title = harness.get_by_role_and_label(Role::TitleBar, "Base color").rect();
let add = harness.get_by_role_and_label(Role::Button, "Add swatch").rect();
egui::Rect::from_min_max(title.min, egui::pos2(title.right() + CLOSE_ROOM, add.bottom() + PICKER_BOTTOM))
}
/// The title bar stops at the × (color_bar.rs: from the right edge to the close target's left edge: PAD + CLOSE_INK_HALF_WIDTH + half of CLOSE_TARGET)
const CLOSE_ROOM: f32 = 25.0;
/// The narrowest the picker resizes to and the shortest its colour field gets (color_bar.rs PICKER_MIN_WIDTH, color_picker_rows.rs FIELD_MIN_HEIGHT)
const PICKER_MIN_WIDTH: f32 = 240.0;
const FIELD_MIN_HEIGHT: f32 = 100.0;
#[test]
fn the_picker_is_titled_by_its_channel_resizes_from_its_edges_keeps_its_size_and_previews_nothing_on_hover() {
let (mut harness, _) = app_with_fill(json!({"color": [0.2, 0.2, 0.2]}));
click(&mut harness, Role::Button, "Base color");
assert!(harness.query_by_role_and_label(Role::TitleBar, "Base color").is_some(), "the title is the channel's name alone");
let face = picker_face(&harness);
let field = harness.get_by_role_and_label(Role::Slider, "Saturation and value").rect();
let hue = harness.get_by_role_and_label(Role::Slider, "Hue").rect();
let track = harness.get_by_role_and_label(Role::Slider, "S").rect();
let by = egui::vec2(80.0, 60.0);
let corner = face.right_bottom() - egui::vec2(2.0, 2.0);
drag(&mut harness, corner, corner + by);
assert!(harness.query_by_role_and_label(Role::ComboBox, "sRGB").is_some(), "a resize keeps the picker open");
let grown = picker_face(&harness);
assert!((grown.min - face.min).length() < 1.0, "the bottom right corner leaves the top left where it was: {grown:?} {face:?}");
assert!((grown.size() - (face.size() + by)).length() < 1.0, "the corner drags the size: {grown:?} from {face:?}");
let grown_field = harness.get_by_role_and_label(Role::Slider, "Saturation and value").rect();
let grown_hue = harness.get_by_role_and_label(Role::Slider, "Hue").rect();
let grown_track = harness.get_by_role_and_label(Role::Slider, "S").rect();
assert!((grown_field.size() - (field.size() + by)).length() < 1.0, "the field takes the new width and height: {grown_field:?} {field:?}");
assert!((grown_hue.height() - (hue.height() + by.y)).abs() < 1.0 && (grown_hue.right() - hue.right() - by.x).abs() < 1.0, "the hue strip grows with it");
assert!((grown_track.width() - (track.width() + by.x)).abs() < 1.0, "the sliders' tracks take the new width");
let left_edge = egui::pos2(grown.left() + 2.0, grown.center().y);
drag(&mut harness, left_edge, left_edge + egui::vec2(-50.0, 0.0));
let wider = picker_face(&harness);
assert!(
(wider.left() - (grown.left() - 50.0)).abs() < 1.0 && (wider.right() - grown.right()).abs() < 1.0,
"the left edge moves, the right stays: {wider:?}"
);
let wider_corner = wider.right_bottom() - egui::vec2(2.0, 2.0);
drag(&mut harness, wider_corner, wider_corner + egui::vec2(-1000.0, -1000.0));
let least = picker_face(&harness);
let least_field = harness.get_by_role_and_label(Role::Slider, "Saturation and value").rect();
assert!(least.width() >= PICKER_MIN_WIDTH - 1.0 && least_field.height() >= FIELD_MIN_HEIGHT - 1.0, "it stops at a usable size: {least:?} {least_field:?}");
harness.key_press(egui::Key::Escape);
harness.run_steps(SETTLE_FRAMES);
click(&mut harness, Role::Button, "Base color");
let reopened = picker_face(&harness);
assert!((reopened.size() - least.size()).length() < 1.0, "it opens again at the size it was left: {reopened:?} {least:?}");
let value = |harness: &Harness<'_, TextureCraftApp>| harness.get_by_role_and_label(Role::Slider, "V").accesskit_node().numeric_value();
let shown = value(&harness);
assert!(shown.is_some(), "the V slider says its value");
click(&mut harness, Role::ComboBox, "sRGB");
harness.get_by_role_and_label(Role::ListBoxOption, "Linear").hover();
harness.run_steps(SETTLE_FRAMES);
assert_eq!(value(&harness), shown, "a hovered colour space changes nothing");
harness.key_press(egui::Key::Escape);
harness.run_steps(SETTLE_FRAMES);
click(&mut harness, Role::ComboBox, "HSV");
harness.get_by_role_and_label(Role::ListBoxOption, "RGB").hover();
harness.run_steps(SETTLE_FRAMES);
assert!(harness.query_by_role_and_label(Role::Slider, "R").is_none(), "a hovered model changes nothing");
click(&mut harness, Role::ListBoxOption, "RGB");
assert!(harness.query_by_role_and_label(Role::Slider, "R").is_some(), "a click picks it");
}
/// The whole material the fill `layer` holds
fn whole_material(harness: &Harness<'_, TextureCraftApp>, layer: LayerId) -> Option<String> {
fill_of(harness, layer).material
}
#[test]
fn a_plain_fill_switches_to_one_whole_material_picks_it_from_its_card_and_clears_it() {
let (mut harness, layer) = app_with_fill(json!({}));
assert!(harness.query_by_role_and_label(Role::ComboBox, "Metallic").is_some(), "a plain fill opens on Channels: a card per channel");
click_node(&mut harness, Role::RadioButton, "Material");
assert!(harness.query_by_role_and_label(Role::ComboBox, "Metallic").is_none(), "the Material side has no channel cards");
click_node(&mut harness, Role::ComboBox, "None");
// The card opens the material picker, not a list: unfiltered it offers the plain materials but no smart ones
assert!(harness.query_by_role_and_label(Role::ListBoxOption, "Steel").is_some(), "the picker offers the plain materials");
assert!(harness.query_by_role_and_label(Role::ListBoxOption, "Steel Painted Worn").is_none(), "smart materials are folders of layers: not offered");
// Its search keeps only the materials it names
harness.event(egui::Event::Text("hammered".into()));
harness.run_steps(SETTLE_FRAMES);
assert!(harness.query_by_role_and_label(Role::ListBoxOption, "Steel").is_none(), "searching hides what it doesn't name");
click_node(&mut harness, Role::ListBoxOption, "Copper Hammered");
assert_eq!(whole_material(&harness, layer).as_deref(), Some("copper_hammered"), "the picker sets the whole material");
assert!(harness.query_by_role_and_label(Role::ComboBox, "Copper Hammered").is_some(), "the card names it");
assert!(harness.query_by_role(Role::ListBoxOption).is_none(), "the picker closed on the pick");
click_node(&mut harness, Role::RadioButton, "Channels");
assert!(matches!(source(&harness, layer, Channel::BaseColor), Source::Procedural { .. }), "the material set every channel");
assert!(harness.query_by_role_and_label(Role::ComboBox, "Height").is_some(), "its channels show as cards");
click_node(&mut harness, Role::RadioButton, "Material");
click_in_slot(&mut harness, "Copper Hammered", Role::Button, "Clear");
assert_eq!(whole_material(&harness, layer), None, "× drops the material");
assert_eq!(source(&harness, layer, Channel::BaseColor), Source::uniform_of(Channel::BaseColor), "and returns the channels to their defaults");
}
/// Arms the base colour bar's eyedropper and gives its pick the click outside the app that ended as `outcome`
fn pick_outside(harness: &mut Harness<'_, TextureCraftApp>, outcome: PickOutcome) {
click_bar_eyedropper(harness);
harness.run_steps(SETTLE_FRAMES);
let bar = harness.state().picking_color.expect("the eyedropper waits for a click");
harness.state_mut().screen_pick = Some(ScreenPick::ended(bar, outcome));
harness.run_steps(SETTLE_FRAMES);
}
#[test]
fn a_click_outside_the_app_hands_its_screen_colour_to_the_bar_and_a_cancelled_or_impossible_one_changes_nothing() {
let (mut harness, layer) = app_with_fill(json!({"color": [0.2, 0.2, 0.2]}));
assert!(!harness.state().screen_picking, "tests have no real window: no system hook or grab");
let before = base_color(&harness, layer);
click(&mut harness, Role::Button, "Base color");
pick_outside(&mut harness, PickOutcome::Unavailable);
assert!(harness.state().picking_color.is_some(), "where the system cannot read the screen the pick stays on the model");
assert_eq!(base_color(&harness, layer), before, "nothing changes until a click");
harness.key_press(egui::Key::Escape);
harness.run_steps(SETTLE_FRAMES);
assert!(harness.state().picking_color.is_none() && harness.state().screen_pick.is_none(), "Escape ends the pick and its wait");
pick_outside(&mut harness, PickOutcome::Cancelled);
assert!(harness.state().picking_color.is_none(), "dismissing the desktop's picker ends the pick");
assert_eq!(base_color(&harness, layer), before, "a cancelled pick changes nothing");
let undo_before = undo_depth(&harness);
pick_outside(&mut harness, PickOutcome::Picked([255, 128, 0]));
let picked = base_color(&harness, layer);
let expected = [1.0, texturecraft_engine::texel::srgb_to_linear(128.0 / 255.0), 0.0];
assert!(picked.iter().zip(expected).all(|(a, b)| (a - b).abs() < 1e-3), "the screen's sRGB pixel is stored linear: {picked:?}");
assert!(harness.state().picking_color.is_none() && harness.state().screen_pick.is_none(), "the click ends the pick");
assert_eq!(undo_depth(&harness), undo_before + 1, "one undo step");
}
#[test]
fn an_armed_eyedropper_is_the_pointer_over_the_whole_window_and_the_app_losing_the_focus_ends_it() {
let (mut harness, layer) = app_with_fill(json!({"color": [0.2, 0.2, 0.2]}));
let before = base_color(&harness, layer);
click(&mut harness, Role::Button, "Base color");
click_bar_eyedropper(&mut harness);
harness.run_steps(SETTLE_FRAMES);
let bar = harness.state().picking_color.expect("the eyedropper waits for a click");
harness.get_by_role_and_label(Role::Tab, "Material").hover();
harness.run_steps(SETTLE_FRAMES);
let pointer = harness.output().platform_output.cursor_icon;
assert_eq!(pointer, egui::CursorIcon::None, "over the Properties panel, not only the 3D view, the drawn eyedropper is the pointer");
harness.state_mut().screen_pick = Some(ScreenPick::waiting(bar));
harness.run_steps(SETTLE_FRAMES);
assert!(harness.state().picking_color.is_some(), "a focused app keeps waiting");
harness.input_mut().viewports.entry(egui::ViewportId::ROOT).or_default().focused = Some(false);
harness.run_steps(SETTLE_FRAMES);
assert!(harness.state().picking_color.is_none() && harness.state().screen_pick.is_none(), "another app came forward: the pick ends");
assert_eq!(base_color(&harness, layer), before, "nothing changes");
assert_ne!(harness.output().platform_output.cursor_icon, egui::CursorIcon::None, "the pointer is the user's again");
}
#[test]
fn escape_in_the_hex_field_ends_the_typing_and_a_second_escape_closes_the_picker() {
let (mut harness, layer) = app_with_fill(json!({"color": [0.2, 0.2, 0.2]}));
click(&mut harness, Role::Button, "Base color");
click(&mut harness, Role::TextInput, "Hex color");
harness.key_press_modifiers(egui::Modifiers::COMMAND, egui::Key::A);
harness.event(egui::Event::Text("FF8000".into()));
harness.run_steps(1);
harness.key_press(egui::Key::Escape);
harness.run_steps(SETTLE_FRAMES);
assert!(harness.query_by_role_and_label(Role::TitleBar, "Base color").is_some(), "the first Escape only ends the typing");
assert_eq!(base_color(&harness, layer), [0.2, 0.2, 0.2], "and applies nothing");
harness.key_press(egui::Key::Escape);
harness.run_steps(SETTLE_FRAMES);
assert!(harness.query_by_role_and_label(Role::TitleBar, "Base color").is_none(), "the next Escape closes the picker");
}
#[test]
fn a_hex_code_left_as_it_opened_keeps_a_colour_set_meanwhile() {
let (mut harness, layer) = app_with_fill(json!({"color": [0.2, 0.2, 0.2]}));
click(&mut harness, Role::Button, "Base color");
click(&mut harness, Role::TextInput, "Hex color");
// An agent sets the colour while the field is open
harness.state_mut().run("layer.fill.set", json!({"layer": layer.0, "channel": "baseColor", "color": [0.0, 0.0, 1.0]})).unwrap();
harness.run_steps(2);
let depth = undo_depth(&harness);
harness.key_press(egui::Key::Enter);
harness.run_steps(SETTLE_FRAMES);
assert_eq!(base_color(&harness, layer), [0.0, 0.0, 1.0], "the untouched code is not written back");
assert_eq!(undo_depth(&harness), depth, "no undo step");
}
#[test]
fn a_swatch_menu_left_open_while_the_list_changes_never_removes_another_swatch() {
let (mut harness, _) = app_with_fill(json!({"color": [0.2, 0.2, 0.2]}));
let [red, green, blue] = [[1.0, 0.0, 0.0], [0.0, 1.0, 0.0], [0.0, 0.0, 1.0]];
for color in [red, green, blue] {
harness.state_mut().run("swatch.add", json!({"color": color})).unwrap();
}
click(&mut harness, Role::Button, "Base color");
let green_chip = harness.get_by_role_and_label(Role::Button, "#00FF00").rect();
right_click(&mut harness, green_chip.center());
assert!(harness.query_by_role_and_label(Role::Button, "Remove swatch").is_some(), "the green swatch's menu is open");
// An agent removes the first swatch: green moves to its place, blue to green's
harness.state_mut().run("swatch.remove", json!({"index": 0})).unwrap();
harness.run_steps(SETTLE_FRAMES);
if let Some(remove) = harness.query_by_role_and_label(Role::Button, "Remove swatch").map(|node| node.rect()) {
click_at(&mut harness, remove.center());
}
let swatches = &harness.state().session.doc.project.swatches;
assert!(swatches.contains(&blue), "blue stays: {swatches:?}");
assert!(*swatches == vec![blue] || *swatches == vec![green, blue], "only the green swatch the menu was opened on may go: {swatches:?}");
}