Pick the brush alpha from a slot and shape it beside a picture of it

The Alpha section's grid of tiles becomes one slot showing the alpha in
use (thumbnail, name, kind). A click opens the resource picker with the
built-in shapes, the library's alphas and the project's textures; the ×
goes back to the Round shape. An alpha or a texture dropped on the slot
becomes the alpha.

Parameters is a band: Hardness, Roundness (Round shape only), Size X and
Size Y stack beside a live picture of the stamp they make, then Contrast
and Invert. Text is a folded band in the sheet's rows.
This commit is contained in:
Rebornim committed 2026-11-27 08:25:57 +00:00
1 parent 2cf3d2ad67
commit 161d09514a
11 files changed
+449 -173

No files matched your search

+12
View File
@@ -0,0 +1,12 @@
//! What the brush Alpha slot's picker offers
use texturecraft_engine::paint::BrushAlpha;
/// One tile of the Alpha slot's picker: a built-in shape, a library alpha, an image resource, or importing one
#[derive(Clone, Debug, PartialEq)]
pub(crate) enum AlphaChoice {
Shape(BrushAlpha),
Library(&'static str),
Image(String),
Import,
}
+297
View File
@@ -0,0 +1,297 @@
//! The Alpha section of a paint tool's Properties: the alpha's slot with its picker, its Parameters beside a picture of the shape they make, and the Text band
use std::ops::RangeInclusive;
use egui::{Color32, CornerRadius, Painter, Rect, Stroke, Ui, pos2};
use egui_phosphor::regular as ic;
use serde_json::{Value, json};
use texturecraft_engine::Session;
use texturecraft_engine::core::Channel;
use texturecraft_engine::paint::alpha_params::MAX_ALPHA_CONTRAST;
use texturecraft_engine::paint::{BrushAlpha, BrushSettings, alphas};
use crate::TextureCraftApp;
use crate::alpha_choice::AlphaChoice;
use crate::brush_pictures::alpha_image;
use crate::brush_stroke_preview::BrushStrokePreview;
use crate::i18n::{n_, tr};
use crate::picker_group::PickerGroup;
use crate::picker_tab::PickerTab;
use crate::property_sheet::{PropertySheet, StackSlider};
use crate::resource_picker;
use crate::resource_picker_item::ResourcePickerItem;
use crate::theme::Tokens;
use crate::tile_picture::TilePicture;
/// Hardness, Roundness and Size X / Y, in percent
const HARDNESS_PERCENT_RANGE: RangeInclusive<f32> = 0.0..=99.9;
const ROUNDNESS_PERCENT_RANGE: RangeInclusive<f32> = 0.0..=100.0;
const ALPHA_SIZE_PERCENT_RANGE: RangeInclusive<f32> = 5.0..=100.0;
/// Rows the text box shows before it scrolls
const TEXT_ROWS: usize = 2;
/// Air inside the text box, around its words
const TEXT_BOX_MARGIN: i8 = 6;
/// Corner radius of the text box, as the sheet's fields
const TEXT_BOX_ROUNDING: u8 = 3;
/// Width of the text box's outline
const TEXT_BOX_OUTLINE_WIDTH: f32 = 1.0;
/// The Alpha section: the alpha's slot, its Parameters band and the Text band
pub(crate) fn alpha_section(app: &mut TextureCraftApp, sheet: &mut PropertySheet<'_>) {
alpha_slot(app, sheet);
parameters_band(app, sheet);
if sheet.band(tr("Text"), false, None, None).open {
text_rows(app, sheet);
}
}
/// The slot showing the alpha in use; a click opens the picker of shapes, library alphas and images, × goes back to the Round shape
fn alpha_slot(app: &mut TextureCraftApp, sheet: &mut PropertySheet<'_>) {
let ctx = sheet.ui.ctx().clone();
let current = current_choice(&app.session);
let brush = &app.session.tool.brush;
let hardness = brush.hardness;
let (name, source, texture) = match &current {
AlphaChoice::Image(name) => {
let texture = app.session.images.get(name).map(|image| app.thumbs.image(&ctx, name, image));
(name.clone(), tr("Imported image"), texture)
}
AlphaChoice::Library(id) => {
let alpha = alphas::find(id);
let texture = alpha.and_then(|alpha| app.thumbs.alpha(&ctx, alpha));
(alpha.map_or_else(|| (*id).to_owned(), |alpha| tr(&alpha.label).to_owned()), tr("Library alpha"), texture)
}
AlphaChoice::Shape(_) | AlphaChoice::Import => (tr(brush.alpha.label()).to_owned(), tr("Built-in shape"), None),
};
let shape = brush.alpha;
let thumbnail = |painter: &Painter, rect: Rect| {
painter.rect_filled(rect, CornerRadius::ZERO, Color32::BLACK);
match &texture {
Some(texture) => {
painter.image(texture.id(), rect, Rect::from_min_max(pos2(0.0, 0.0), pos2(1.0, 1.0)), Color32::WHITE);
}
None => crate::thumbs::paint_alpha(painter, rect, shape, hardness),
}
};
// The default Round shape has nothing to clear back to
let clearable = current != AlphaChoice::Shape(BrushAlpha::default());
let slot = sheet.slot(&thumbnail, &name, source, None, clearable, false);
let popup = sheet.ui.make_persistent_id("brush_alpha_source");
if slot.pick.clicked() {
resource_picker::toggle(&ctx, popup);
}
let tabs = || alpha_tabs(&app.session, hardness);
match resource_picker::show(&slot.pick, popup, &mut app.thumbs, Some(&current), true, tabs) {
Some(AlphaChoice::Import) => crate::menus::invoke(app, &ctx, "resource.import"),
Some(choice) if choice != current => {
app.run("tool.brush", json!({ "alpha": alpha_value(&choice) }));
}
_ => {}
}
if slot.clear {
app.run("tool.brush", json!({ "alpha": BrushAlpha::default().label() }));
}
// An alpha from the Assets panel, or an image, dropped on the slot becomes the alpha
crate::shelf::drop_target(app, sheet.ui, &slot.pick, crate::shelf::DropZone::Brush);
if let Some(name) = crate::dock::image_drop(sheet.ui, &slot.pick) {
app.run("tool.brush", json!({ "alpha": { "image": name } }));
}
sheet.close_card();
}
/// The picker's choice the brush's alpha is
fn current_choice(session: &Session) -> AlphaChoice {
let brush = &session.tool.brush;
match (&brush.alpha_image, brush.alpha_library.as_deref().and_then(alphas::find)) {
(Some(name), _) => AlphaChoice::Image(name.clone()),
(None, Some(alpha)) => AlphaChoice::Library(alpha.id.as_str()),
(None, None) => AlphaChoice::Shape(brush.alpha),
}
}
/// What `tool.brush` takes as `alpha` for `choice`
fn alpha_value(choice: &AlphaChoice) -> Value {
match choice {
AlphaChoice::Shape(shape) => json!(shape.label()),
AlphaChoice::Library(id) => json!({ "library": id }),
AlphaChoice::Image(name) => json!({ "image": name }),
AlphaChoice::Import => Value::Null,
}
}
/// The picker's one tab: the built-in Shapes at the brush's `hardness`, the library's Alphas in their shelf groups, then Textures with Import... first
fn alpha_tabs(session: &Session, hardness: f32) -> Vec<PickerTab<AlphaChoice>> {
let shapes = BrushAlpha::ALL
.into_iter()
.map(|shape| ResourcePickerItem {
id: AlphaChoice::Shape(shape),
label: tr(shape.label()).to_owned(),
caption: None,
picture: TilePicture::Shape(shape, hardness),
})
.collect();
let library = alphas::library()
.iter()
.map(|alpha| ResourcePickerItem {
id: AlphaChoice::Library(alpha.id.as_str()),
label: tr(&alpha.label).to_owned(),
caption: Some(tr(alpha.category)),
picture: TilePicture::Alpha(alpha),
})
.collect();
let textures = ResourcePickerItem::textures(session, AlphaChoice::Import, |name| AlphaChoice::Image(name.to_owned()));
let groups = [(n_("Shapes"), shapes), (n_("Alphas"), library), (n_("Textures"), textures)]
.into_iter()
.map(|(header, items)| PickerGroup { header: Some(tr(header)), items })
.collect();
vec![PickerTab { icon: ic::CIRCLE_HALF, name: tr("Alphas"), groups }]
}
/// Hardness and the parameters every alpha shares beside the shape they make; the band's reset puts them all back
fn parameters_band(app: &mut TextureCraftApp, sheet: &mut PropertySheet<'_>) {
let tokens = Tokens::get(sheet.ui.ctx());
let image = app.session.tool.brush.alpha_image.as_ref().and_then(|name| app.session.images.get(name)).cloned();
let brush = &mut app.session.tool.brush;
let defaults = BrushSettings::default();
let fields = |settings: &BrushSettings| (settings.hardness, settings.alpha_params);
let band = sheet.band(tr("Parameters"), true, Some(fields(brush) != fields(&defaults)), None);
if band.reset {
(brush.hardness, brush.alpha_params) = fields(&defaults);
}
if !band.open {
return;
}
let shown = brush.clone();
let ctx = sheet.ui.ctx().clone();
let tint = tokens.text.to_array();
let picture = |painter: &Painter, rect: Rect| {
painter.rect_filled(rect, CornerRadius::ZERO, tokens.field);
BrushStrokePreview::paint_picture(&ctx, painter, rect, "brush_alpha_picture", (&shown, image.as_ref()), |_| [tint[0], tint[1], tint[2]], alpha_image);
};
// Only the procedural Round shape has a roundness
let round = brush.alpha == BrushAlpha::Round && brush.alpha_image.is_none() && brush.alpha_library.is_none();
let before = [brush.hardness, brush.alpha_params.roundness, brush.alpha_params.size_x, brush.alpha_params.size_y].map(|fraction| fraction * 100.0);
let [mut hardness, mut roundness, mut size_x, mut size_y] = before;
let percent = |label: &'static str, value, range: RangeInclusive<f32>| StackSlider {
label: tr(label),
value,
range: range.clone(),
typed: range,
decimals: 0,
suffix: "",
dial: false,
};
if round {
sheet.picture_sliders(
&picture,
&mut [
percent(n_("Hardness"), &mut hardness, HARDNESS_PERCENT_RANGE),
percent(n_("Roundness"), &mut roundness, ROUNDNESS_PERCENT_RANGE),
percent(n_("Size X"), &mut size_x, ALPHA_SIZE_PERCENT_RANGE),
percent(n_("Size Y"), &mut size_y, ALPHA_SIZE_PERCENT_RANGE),
],
);
} else {
sheet.picture_sliders(
&picture,
&mut [
percent(n_("Hardness"), &mut hardness, HARDNESS_PERCENT_RANGE),
percent(n_("Size X"), &mut size_x, ALPHA_SIZE_PERCENT_RANGE),
percent(n_("Size Y"), &mut size_y, ALPHA_SIZE_PERCENT_RANGE),
],
);
}
// Only what moved is written back, so an untouched value keeps its exact fraction
for (after, was, fraction) in [
(hardness, before[0], &mut brush.hardness),
(roundness, before[1], &mut brush.alpha_params.roundness),
(size_x, before[2], &mut brush.alpha_params.size_x),
(size_y, before[3], &mut brush.alpha_params.size_y),
] {
if after != was {
*fraction = after / 100.0;
}
}
sheet.slider(tr("Contrast"), &mut brush.alpha_params.contrast, 1.0..=MAX_ALPHA_CONTRAST, 2);
sheet.toggle(tr("Invert"), &mut brush.alpha_params.invert);
*brush = brush.sanitized();
}
/// Text drawn in a font, as the brush alpha or a decal (`resource.text`)
fn text_rows(app: &mut TextureCraftApp, sheet: &mut PropertySheet<'_>) {
if app.ui.text.fonts.is_empty()
&& let Some(fonts) = app.run("text.fonts", Value::Null)
{
let installed = fonts["installed"].as_array().into_iter().flatten().map(|font| {
let styles = font["styles"].as_array().into_iter().flatten().filter_map(Value::as_str).map(str::to_string).collect();
(font["family"].as_str().unwrap_or_default().to_string(), styles)
});
let built_in = fonts["builtIn"].as_array().into_iter().flatten().filter_map(Value::as_str).map(|name| (name.to_string(), Vec::new()));
app.ui.text.fonts = installed.chain(built_in).collect();
}
// A decal shows the text in the tool's base color; an alpha must stay white
let color = app.session.tool.values.get(&Channel::BaseColor).copied().unwrap_or([1.0; 3]);
let tokens = Tokens::get(sheet.ui.ctx());
let text = &mut app.ui.text;
sheet.embed(|ui: &mut Ui| {
let frame = egui::Frame::NONE
.fill(tokens.field)
.stroke(Stroke::new(TEXT_BOX_OUTLINE_WIDTH, tokens.field_border))
.corner_radius(CornerRadius::same(TEXT_BOX_ROUNDING))
.inner_margin(egui::Margin::same(TEXT_BOX_MARGIN));
frame.show(ui, |ui| {
let edit =
egui::TextEdit::multiline(&mut text.text).frame(egui::Frame::NONE).desired_rows(TEXT_ROWS).desired_width(f32::INFINITY).hint_text(tr("Text"));
ui.add(edit);
});
});
// Index 0 is the default font, then the families in the order `text.fonts` lists them
let family = text.fonts.iter().position(|(family, _)| *family == text.font).map_or(0, |index| index + 1);
let family_name = |index: usize| if index == 0 { tr("Default").to_owned() } else { text.fonts[index - 1].0.clone() };
let (picked, _) = sheet.dropdown_built(tr("Font"), family, || 0..=text.fonts.len(), family_name, None);
if let Some(index) = picked {
text.font = if index == 0 { String::new() } else { text.fonts[index - 1].0.clone() };
text.style = String::new();
}
let styles = text.fonts.iter().find(|(family, _)| *family == text.font).map(|(_, styles)| styles.clone()).unwrap_or_default();
if styles.len() > 1 {
let style = styles.iter().position(|style| *style == text.style).map_or(0, |index| index + 1);
let style_name = |index: usize| if index == 0 { tr("Default").to_owned() } else { styles[index - 1].clone() };
let (picked, _) = sheet.dropdown_built(tr("Style"), style, || 0..=styles.len(), style_name, None);
if let Some(index) = picked {
text.style = if index == 0 { String::new() } else { styles[index - 1].clone() };
}
}
let mut params =
json!({"text": text.text, "font": (!text.font.is_empty()).then_some(&text.font), "style": (!text.style.is_empty()).then_some(&text.style)});
let ready = !text.text.trim().is_empty();
let alpha = sheet.button_enabled(ic::CIRCLE_HALF, tr("Use as brush alpha"), false, ready).clicked();
let decal = sheet.button_enabled(ic::STAMP, tr("Place as decal"), false, ready).clicked();
if decal {
params["color"] = json!(color);
}
if (alpha || decal)
&& let Some(name) = app.run("resource.text", params).and_then(|result| result["name"].as_str().map(str::to_string))
{
if alpha {
app.run("tool.brush", json!({"alpha": {"image": name}}));
} else {
app.run("layer.add.decal", json!({"image": name}));
}
}
}
+5
View File
@@ -45,6 +45,11 @@ pub(crate) fn stamp_image(brush: &BrushSettings, image: Option<&ImageRes>, size:
stroke_strip(&still, image, size, |_| radius, |_| center, |x| column_tint(tints, x))
}
/// The brush's alpha as its Parameters shape it, upright: the Alpha section's Parameters picture
pub(crate) fn alpha_image(brush: &BrushSettings, image: Option<&ImageRes>, size: [usize; 2], pixels_per_point: f32, tints: &[[u8; 3]]) -> ColorImage {
stamp_image(&BrushSettings { angle: 0.0, ..brush.clone() }, image, size, pixels_per_point, tints)
}
/// A row of the brush's dabs across a `size` strip, scattered by its four jitters; dabs shrink as Position Jitter grows so the scatter stays inside
pub(crate) fn jitter_image(brush: &BrushSettings, image: Option<&ImageRes>, size: [usize; 2], _pixels_per_point: f32, tints: &[[u8; 3]]) -> ColorImage {
let spaced = BrushSettings { spacing: brush.spacing.max(STRIP_DAB_SPACING), follow_path: false, flow: 1.0, opacity: 1.0, ..brush.clone() };
+2 -150
View File
@@ -8,8 +8,6 @@ use texturecraft_engine::compose::ThumbTarget;
use texturecraft_engine::core::{
BakedMap, BlendMode, Channel, ChannelBlend, Effect, EffectKind, Layer, LayerId, LayerKind, LinkParam, Projection, Sampling, Source,
};
use texturecraft_engine::paint::alpha_params::MAX_ALPHA_CONTRAST;
use texturecraft_engine::paint::{BrushAlpha, BrushSettings, alphas};
use texturecraft_engine::texel::linear_to_srgb;
use texturecraft_engine::{CloneFrom, StackTarget, Tool};
@@ -23,7 +21,7 @@ use crate::property_sheet::{PropertySheet, SectionScope};
use crate::shelf::{Asset, ShelfDrag};
use crate::source_choice::SourceChoice;
use crate::theme::{Tokens, caption};
use crate::widgets::{chip, color_swatch, combo, dnd_release, elided, icon_button, press_edit, section, section_with_reset, slider, slider_edit};
use crate::widgets::{chip, color_swatch, combo, dnd_release, elided, icon_button, press_edit, section, slider, slider_edit};
const TAG_COLORS: [Color32; 8] = [
Color32::from_rgb(0xc0, 0x40, 0x40),
@@ -2130,7 +2128,7 @@ fn tool_properties(app: &mut TextureCraftApp, ui: &mut Ui) {
let menu = sheet.section(section.title(), section == PaintSection::Brush);
match section {
PaintSection::Brush => crate::brush_sheet::brush_section(app, sheet, menu),
PaintSection::Alpha => legacy(sheet, app, alpha_section),
PaintSection::Alpha => crate::alpha_sheet::alpha_section(app, sheet),
PaintSection::Stencil => legacy(sheet, app, stencil_section),
PaintSection::Material => legacy(sheet, app, material_controls),
PaintSection::Grayscale => crate::mask_paint_panel::grayscale_section(app, sheet),
@@ -2367,152 +2365,6 @@ fn polygon_fill_paints_mask(app: &TextureCraftApp) -> Result<bool, String> {
}
}
/// One alpha in the picker: a 52×64 tile with the shape drawn by `paint` and a label.
fn alpha_tile(ui: &mut Ui, on: bool, label: &str, paint: impl FnOnce(&egui::Painter, Rect)) -> egui::Response {
let tk = Tokens::get(ui.ctx());
let (rect, resp) = ui.allocate_exact_size(vec2(52.0, 64.0), Sense::click());
let p = ui.painter();
p.rect_filled(rect, 3.0, tk.viewport);
if on {
p.rect_stroke(rect, 3.0, Stroke::new(1.0, tk.accent), egui::StrokeKind::Inside);
}
paint(p, Rect::from_center_size(rect.center() - vec2(0.0, 7.0), vec2(40.0, 40.0)));
let name = elided(p, label, 9.5, tk.viewport_text, rect.width() - 4.0);
p.galley(rect.center_bottom() - vec2(name.size().x * 0.5, 6.0 + name.size().y * 0.5), name, tk.viewport_text);
resp.on_hover_text(label)
}
fn alpha_section(app: &mut TextureCraftApp, ui: &mut Ui) {
let tk = Tokens::get(ui.ctx());
import_button(app, ui);
let brush = &app.session.tool.brush;
let (current, image, hardness) = (brush.alpha, brush.alpha_image.clone(), brush.hardness);
let library = if image.is_none() { brush.alpha_library.as_deref().and_then(alphas::find) } else { None };
let mut pick = None;
let zone = ui.horizontal_wrapped(|ui| {
for a in BrushAlpha::ALL {
let on = image.is_none() && library.is_none() && current == a;
if alpha_tile(ui, on, tr(a.label()), |p, r| crate::thumbs::paint_alpha(p, r, a, hardness)).clicked() {
pick = Some(json!(a.label()));
}
}
// The library alpha in use (picked from the shelf's Alphas tab)
if let Some(a) = library {
let tex = app.thumbs.alpha(ui.ctx(), a);
alpha_tile(ui, true, &a.label, |p, r| {
if let Some(t) = tex {
p.image(t.id(), r, Rect::from_min_max(pos2(0.0, 0.0), pos2(1.0, 1.0)), Color32::WHITE);
}
});
}
// Imported images, sampled as grayscale
for name in app.session.doc.resources.keys() {
let Some(img) = app.session.images.get(name) else { continue };
let tex = app.thumbs.image(ui.ctx(), name, img);
let on = image.as_deref() == Some(name.as_str());
if alpha_tile(ui, on, name, |p, r| {
p.image(tex.id(), r, Rect::from_min_max(pos2(0.0, 0.0), pos2(1.0, 1.0)), Color32::WHITE);
})
.clicked()
{
pick = Some(json!({ "image": name }));
}
}
});
if let Some(alpha) = pick {
app.run("tool.brush", json!({ "alpha": alpha }));
}
ui.label(RichText::new(tr("More in Assets > Alphas: click one, or drag it here")).size(10.0).color(tk.text_dim));
crate::shelf::drop_target(app, ui, &zone.response, crate::shelf::DropZone::Brush);
alpha_parameters(&mut app.session.tool.brush, ui);
section(ui, "sec_text", tr("Text"), true, |ui| text_section(app, ui));
}
/// Hardness and the parameters every alpha shares, under a header whose reset puts them back
fn alpha_parameters(brush: &mut BrushSettings, ui: &mut Ui) {
let defaults = BrushSettings::default();
let at_defaults = brush.hardness == defaults.hardness && brush.alpha_params == defaults.alpha_params;
let round = brush.alpha == BrushAlpha::Round && brush.alpha_image.is_none() && brush.alpha_library.is_none();
let percent_slider = |ui: &mut Ui, label: &str, value: &mut f32, min: f32, max: f32| {
let mut percent = *value * 100.0;
if slider(ui, label, &mut percent, min..=max, 0).changed() {
*value = percent / 100.0;
}
};
let reset = section_with_reset(ui, "sec_alpha_params", tr("Parameters"), true, at_defaults, |ui| {
percent_slider(ui, tr("Hardness"), &mut brush.hardness, 0.0, 99.9);
percent_slider(ui, tr("Size X"), &mut brush.alpha_params.size_x, 5.0, 100.0);
percent_slider(ui, tr("Size Y"), &mut brush.alpha_params.size_y, 5.0, 100.0);
// Only the procedural Round shape has a roundness
ui.add_enabled_ui(round, |ui| percent_slider(ui, tr("Roundness"), &mut brush.alpha_params.roundness, 0.0, 100.0));
slider(ui, tr("Contrast"), &mut brush.alpha_params.contrast, 1.0..=MAX_ALPHA_CONTRAST, 2);
ui.checkbox(&mut brush.alpha_params.invert, tr("Invert"));
});
if reset {
(brush.hardness, brush.alpha_params) = (defaults.hardness, defaults.alpha_params);
}
*brush = brush.sanitized();
}
/// Text drawn in a font, as the brush alpha or a decal (`resource.text`).
fn text_section(app: &mut TextureCraftApp, ui: &mut Ui) {
if app.ui.text.fonts.is_empty()
&& let Some(f) = app.run("text.fonts", Value::Null)
{
let installed = f["installed"].as_array().into_iter().flatten().map(|v| {
let styles = v["styles"].as_array().into_iter().flatten().filter_map(Value::as_str).map(str::to_string).collect();
(v["family"].as_str().unwrap_or_default().to_string(), styles)
});
let built_in = f["builtIn"].as_array().into_iter().flatten().filter_map(Value::as_str).map(|n| (n.to_string(), Vec::new()));
app.ui.text.fonts = installed.chain(built_in).collect();
}
// A decal shows the text in the tool's base color; an alpha must stay white.
let color = app.session.tool.values.get(&Channel::BaseColor).copied().unwrap_or([1.0; 3]);
let t = &mut app.ui.text;
ui.add(egui::TextEdit::multiline(&mut t.text).desired_rows(2).desired_width(f32::INFINITY).hint_text(tr("Text")));
let shown = if t.font.is_empty() { tr("Default").to_string() } else { t.font.clone() };
combo(ui, tr("Font"), shown, |ui| {
if ui.selectable_label(t.font.is_empty(), tr("Default")).clicked() {
(t.font, t.style) = (String::new(), String::new());
}
for (family, _) in &t.fonts {
if ui.selectable_label(t.font == *family, family).clicked() {
(t.font, t.style) = (family.clone(), String::new());
}
}
});
let styles = t.fonts.iter().find(|(f, _)| *f == t.font).map(|(_, s)| s.clone()).unwrap_or_default();
if styles.len() > 1 {
let shown = if t.style.is_empty() { tr("Default").to_string() } else { t.style.clone() };
combo(ui, tr("Style"), shown, |ui| {
for s in styles {
ui.selectable_value(&mut t.style, s.clone(), s);
}
});
}
let mut params = json!({"text": t.text, "font": (!t.font.is_empty()).then_some(&t.font), "style": (!t.style.is_empty()).then_some(&t.style)});
let ready = !t.text.trim().is_empty();
ui.horizontal_wrapped(|ui| {
let alpha = ui.add_enabled(ready, egui::Button::new(tr("Use as brush alpha"))).clicked();
let decal = ui.add_enabled(ready, egui::Button::new(tr("Place as decal"))).clicked();
if decal {
params["color"] = json!(color);
}
if (alpha || decal)
&& let Some(name) = app.run("resource.text", params).and_then(|r| r["name"].as_str().map(str::to_string))
{
match alpha {
true => app.run("tool.brush", json!({"alpha": {"image": name}})),
false => app.run("layer.add.decal", json!({"image": name})),
};
}
});
}
/// Tooltip of the material channel chips.
pub(crate) const SOLO_HINT: &str = "Click: turn this channel on or off. Alt+click: this channel only";
+2
View File
@@ -7,6 +7,8 @@
#![forbid(unsafe_code)]
#![deny(clippy::unwrap_used, clippy::expect_used, clippy::panic, clippy::unimplemented, clippy::todo, clippy::unreachable)]
mod alpha_choice;
mod alpha_sheet;
mod anchor_properties;
mod angle_dial;
mod ask;
+5 -1
View File
@@ -395,7 +395,7 @@ fn tile_ui<K>(ui: &mut Ui, thumbs: &mut Thumbs, rect: Rect, (place, item): (usiz
TilePicture::Image(name, image) => Some(thumbs.image(ui.ctx(), name, image)),
TilePicture::Procedural(kind) => thumbs.procedural(ui.ctx(), *kind),
TilePicture::Generator(kind) => thumbs.generator(ui.ctx(), *kind),
TilePicture::Swatch(_) | TilePicture::Glyph(_) | TilePicture::Import => None,
TilePicture::Shape(..) | TilePicture::Swatch(_) | TilePicture::Glyph(_) | TilePicture::Import => None,
};
match (&item.picture, texture) {
@@ -419,6 +419,10 @@ fn tile_ui<K>(ui: &mut Ui, thumbs: &mut Thumbs, rect: Rect, (place, item): (usiz
tokens.text_dim.gamma_multiply(LOADING_GLYPH_OPACITY),
);
}
(TilePicture::Shape(alpha, hardness), None) => {
painter.rect_filled(picture, rounding, Color32::BLACK);
crate::thumbs::paint_alpha(painter, picture, *alpha, *hardness);
}
(TilePicture::Swatch(color), None) => {
painter.rect_filled(picture, rounding, *color);
}
+3
View File
@@ -5,6 +5,7 @@ use std::sync::Arc;
use egui::Color32;
use texturecraft_engine::compose::ImageRes;
use texturecraft_engine::core::{GeneratorKind, ProceduralKind};
use texturecraft_engine::paint::BrushAlpha;
use texturecraft_engine::paint::alphas::LibraryAlpha;
/// A tile's picture source. Previews are requested only when its tile is drawn.
@@ -12,6 +13,8 @@ pub(crate) enum TilePicture {
Material(&'static str),
Filter(&'static str),
Alpha(&'static LibraryAlpha),
/// A built-in brush shape at a hardness, drawn as the shape tiles of the old alpha grid were
Shape(BrushAlpha, f32),
Image(String, Arc<ImageRes>),
Procedural(ProceduralKind),
/// A mask generator at its defaults on the smart masks' orb, a die in its corner when a seed changes its result
+8 -3
View File
@@ -28,8 +28,13 @@ fn app_with_brush(brush: BrushSettings) -> Harness<'static, TextureCraftApp> {
harness
}
/// The reset on the Parameters band's row
fn restore_defaults<'tree>(harness: &'tree Harness<'_, TextureCraftApp>) -> egui_kittest::Node<'tree> {
harness.get_by_role_and_label(egui::Role::Button, "Parameters: Reset to defaults")
let band = harness.get_by_role_and_label(egui::Role::Button, "Parameters").rect();
harness
.query_all_by_role_and_label(egui::Role::Button, "Restore defaults")
.find(|node| node.rect().y_range().intersects(band.y_range()))
.unwrap_or_else(|| panic!("no reset on the Parameters band"))
}
fn invert_checkbox<'tree>(harness: &'tree Harness<'_, TextureCraftApp>) -> Option<egui_kittest::Node<'tree>> {
@@ -89,8 +94,8 @@ fn hardness_left_the_brush_tab_and_its_reset() {
let harness = app_with_brush(BrushSettings::default());
// One page: the Brush section comes first, Hardness only in the Alpha section under it
let hardness: Vec<_> = harness.get_all_by_label("Hardness").map(|node| node.rect().top()).collect();
let flow = harness.get_by_label("Flow").rect().top();
let hardness: Vec<_> = harness.query_all_by_role_and_label(egui::Role::Slider, "Hardness").map(|node| node.rect().top()).collect();
let flow = harness.get_by_role_and_label(egui::Role::Slider, "Flow").rect().top();
assert_eq!(hardness.len(), 1, "Hardness is in the Alpha section alone");
assert!(hardness[0] > flow, "the Alpha section follows the Brush section's Flow");
}
+107
View File
@@ -0,0 +1,107 @@
//! The Alpha section's slot: its picker sets the brush alpha, × goes back to the Round shape, and Roundness shows only for the Round shape
use egui::Role;
use egui_kittest::Harness;
use egui_kittest::kittest::Queryable;
use texturecraft_engine::paint::{BrushAlpha, BrushSettings, alphas};
use texturecraft_ui_egui::TextureCraftApp;
use crate::{BAKE_RESOLUTION, STARTUP_FRAMES, TEXTURE_RESOLUTION, click_widget};
/// Window the Alpha section tests run in
const WINDOW_SIZE: egui::Vec2 = egui::vec2(1600.0, 960.0);
/// Frames after a click in the slot, more than the crate's SETTLE_FRAMES to leave the alpha picker's popup time to open or close
const SLOT_CLICK_FRAMES: usize = 6;
/// Frames for the jump tab's animated scroll to settle
const SCROLL_FRAMES: usize = 60;
/// The app showing the Alpha section of Properties, with `brush`
fn app_with_brush(brush: BrushSettings) -> Harness<'static, TextureCraftApp> {
let session = texturecraft_engine::sample_session(TEXTURE_RESOLUTION, BAKE_RESOLUTION).unwrap();
let mut harness = Harness::builder()
.with_size(WINDOW_SIZE)
.with_context_setup(texturecraft_ui_egui::framework::install_headless)
.build_eframe(|cc| TextureCraftApp::new(cc, session));
harness.state_mut().ui.prefs.language = "en".into();
harness.state_mut().session.tool.brush = brush;
harness.run_steps(STARTUP_FRAMES);
harness.get_by_role_and_label(Role::Tab, "Alpha").click();
harness.run_steps(SCROLL_FRAMES);
harness
}
fn click(harness: &mut Harness<'_, TextureCraftApp>, role: Role, label: &str) {
click_widget(harness, role, label);
harness.run_steps(SLOT_CLICK_FRAMES);
}
/// The × of the slot showing `slot`: the Clear button on its row
fn click_clear(harness: &mut Harness<'_, TextureCraftApp>, slot: &str) {
let row = harness.get_by_role_and_label(Role::ComboBox, slot).rect();
let clear = harness
.query_all_by_role_and_label(Role::Button, "Clear")
.find(|node| node.rect().y_range().intersects(row.y_range()))
.unwrap_or_else(|| panic!("no Clear on the {slot} slot"))
.rect();
super::click_at(harness, clear.center());
harness.run_steps(SLOT_CLICK_FRAMES);
}
/// Clicks the built-in shape `label`: the Shapes come first, above a library alpha of the same name
fn click_shape(harness: &mut Harness<'_, TextureCraftApp>, label: &str) {
let tile = harness
.query_all_by_role_and_label(Role::ListBoxOption, label)
.map(|node| node.rect())
.min_by(|a, b| a.top().total_cmp(&b.top()))
.unwrap_or_else(|| panic!("no {label} tile"));
super::click_at(harness, tile.center());
harness.run_steps(SLOT_CLICK_FRAMES);
}
#[test]
fn the_slot_picks_a_shape_and_its_clear_goes_back_to_round() {
let mut harness = app_with_brush(BrushSettings::default());
let row = harness.get_by_role_and_label(Role::ComboBox, "Round").rect();
assert!(
!harness.query_all_by_role_and_label(Role::Button, "Clear").any(|node| node.rect().y_range().intersects(row.y_range())),
"the Round shape has nothing to clear back to"
);
click(&mut harness, Role::ComboBox, "Round");
click_shape(&mut harness, "Star");
assert_eq!(harness.state().session.tool.brush.alpha, BrushAlpha::Star);
assert!(harness.query_by_role_and_label(Role::ComboBox, "Star").is_some(), "the slot shows the picked shape");
click_clear(&mut harness, "Star");
assert_eq!(harness.state().session.tool.brush.alpha, BrushAlpha::Round);
}
#[test]
fn the_picker_offers_the_library_alphas() {
// Any library alpha
let alpha = &alphas::library()[0];
let mut harness = app_with_brush(BrushSettings::default());
click(&mut harness, Role::ComboBox, "Round");
harness.event(egui::Event::Text(alpha.label.clone()));
harness.run_steps(SLOT_CLICK_FRAMES);
click(&mut harness, Role::ListBoxOption, &alpha.label);
let brush = &harness.state().session.tool.brush;
assert_eq!(brush.alpha_library.as_deref(), Some(alpha.id.as_str()));
assert!(harness.query_by_role_and_label(Role::ComboBox, &alpha.label).is_some(), "the slot shows the library alpha");
}
#[test]
fn roundness_shows_only_for_the_round_shape() {
let roundness = |harness: &Harness<'_, TextureCraftApp>| harness.query_all_by_role_and_label(Role::Slider, "Roundness").count();
let round = app_with_brush(BrushSettings::default());
assert_eq!(roundness(&round), 1, "the Round shape has a roundness");
let star = app_with_brush(BrushSettings { alpha: BrushAlpha::Star, ..BrushSettings::default() });
assert_eq!(roundness(&star), 0, "other alphas have none");
assert_eq!(star.query_all_by_role_and_label(Role::Slider, "Hardness").count(), 1, "the rest of the Parameters stay");
}
+1
View File
@@ -2,6 +2,7 @@
//! Keep feature tests in their own modules; the standalone ui_snapshots.rs target remains available.
mod alpha_parameters;
mod alpha_slot;
mod anchor_point;
mod bake_job_mesh;
mod bake_live_preview;
+7 -19
View File
@@ -22,23 +22,11 @@ fn picker<'a>(h: &'a Harness<'_, TextureCraftApp>, value: &str) -> egui_kittest:
h.get_all_by_role(Role::ComboBox).find(|node| node.value().as_deref() == Some(value)).unwrap_or_else(|| panic!("a view picker showing {value}"))
}
/// The nodes labelled `label` left of the Properties panel, whose paint tool sections also tile every image as an alpha
fn listed<'a>(h: &'a Harness<'_, TextureCraftApp>, label: &'a str) -> Vec<egui_kittest::Node<'a>> {
let properties = h.get_by_role_and_label(Role::Tab, "Properties - Paint").rect().left();
h.get_all_by_label(label).filter(|node| node.rect().center().x < properties).collect()
}
fn one_listed<'a>(h: &'a Harness<'_, TextureCraftApp>, label: &'a str) -> egui_kittest::Node<'a> {
let mut nodes = listed(h, label);
assert_eq!(nodes.len(), 1, "one {label} listed");
nodes.remove(0)
}
/// Clicks the entry `label` of the open list (a long list scrolls inside the viewport's height)
fn pick(h: &mut Harness<'_, TextureCraftApp>, label: &str) {
one_listed(h, label).scroll_to_me();
h.get_by_label(label).scroll_to_me();
h.run_steps(12);
one_listed(h, label).click();
h.get_by_label(label).click();
h.run_steps(3);
}
@@ -77,7 +65,7 @@ fn other_opens_an_image_picker_and_shows_the_chosen_image() {
query_field(&h);
h.get_by_label("reset query to default");
one_listed(&h, &name).click();
h.get_by_label(&name).click();
h.run_steps(3);
assert_eq!(h.state().session.view, ViewMode::Image);
@@ -93,19 +81,19 @@ fn the_image_picker_filters_by_name_and_the_reset_button_restores_the_query() {
h.run_steps(3);
open(&mut h, "Material");
pick(&mut h, "Other...");
assert!(!listed(&h, &first).is_empty() && !listed(&h, &second).is_empty(), "the default query lists every image");
assert!(h.query_by_label(&first).is_some() && h.query_by_label(&second).is_some(), "the default query lists every image");
let field = query_field(&h);
field.click();
field.type_text(" stone");
h.run_steps(3);
assert!(listed(&h, &second).is_empty(), "{second} does not match");
assert!(!listed(&h, &first).is_empty());
assert!(h.query_by_label(&second).is_none(), "{second} does not match");
assert!(h.query_by_label(&first).is_some());
h.get_by_label("reset query to default").click();
h.run_steps(3);
query_field(&h);
assert!(!listed(&h, &second).is_empty(), "the reset lists every image again");
assert!(h.query_by_label(&second).is_some(), "the reset lists every image again");
}
#[test]