Levels: edit the input range, gamma and output range on the histogram

Drag the input low, gamma and input high handles above the histogram and
the output low/high handles under a black-to-white strip; double-click a
handle to type its value. Reset, Auto and Invert replace the five sliders.
Every drag is one undo step through effect.set.
This commit is contained in:
Rebornim committed 2026-11-07 13:00:33 +00:00
1 parent 594f114ccc
commit ed45aa0807
17 files changed
+816 -75

No files matched your search

+2 -47
View File
@@ -17,7 +17,7 @@ use crate::i18n::{n_, tr, trf};
use crate::shelf::{Asset, ShelfDrag};
use crate::state::PropsTab;
use crate::theme::{Tokens, caption};
use crate::widgets::{chip, color_swatch, combo, dnd_release, elided, histogram, icon_button, section, slider, slider_edit};
use crate::widgets::{chip, color_swatch, combo, dnd_release, elided, icon_button, section, slider, slider_edit};
const TAG_COLORS: [Color32; 8] = [
Color32::from_rgb(0xc0, 0x40, 0x40),
@@ -1918,20 +1918,7 @@ fn effect_properties(app: &mut TextureCraftApp, ui: &mut Ui, layer: &Layer, eid:
);
}
}
EffectKind::Levels(l) => {
ui.label(caption(tr("Levels")));
levels_histogram(app, ui, layer, eid, (l.in_low, l.in_high));
let mut v = [l.in_low, l.in_high, l.gamma, l.out_low, l.out_high];
let labels = [tr("Input low"), tr("Input high"), tr("Gamma"), tr("Output low"), tr("Output high")];
let mut edit = None;
for (i, label) in labels.iter().enumerate() {
let range = if i == 2 { 0.1..=5.0 } else { 0.0..=1.0 };
edit = edit.or(slider_edit(ui, label, &mut v[i], range, 2));
}
if let Some(merge) = edit {
app.run("effect.set", json!({"effect": id, "inLow": v[0], "inHigh": v[1], "gamma": v[2], "outLow": v[3], "outHigh": v[4], "merge": merge}));
}
}
EffectKind::Levels(l) => crate::levels_properties::levels_properties(app, ui, layer, eid, l),
EffectKind::Fill { source, .. } => {
ui.label(caption(tr("Fill")));
let anchors = anchors_below(app, layer.id);
@@ -2026,38 +2013,6 @@ fn effect_properties(app: &mut TextureCraftApp, ui: &mut Ui, layer: &Layer, eid:
}
}
/// The histogram of what levels effect `eid` of `layer` remaps (its mask, or a content channel
/// picked here), with the input range marked. Recomputed after a document change once no
/// pointer button is held, so dragging a slider keeps the last one.
fn levels_histogram(app: &TextureCraftApp, ui: &mut Ui, layer: &Layer, eid: LayerId, range: (f32, f32)) {
let mut channel = layer.channels.keys().next().copied().unwrap_or(Channel::BaseColor);
if layer.content_effects.iter().any(|e| e.id == eid) {
let pick = egui::Id::unique(("levels_channel", eid.0));
let chans: Vec<Channel> = layer.channels.keys().copied().filter(|c| c.kind() != texturecraft_engine::core::ChannelKind::NormalMap).collect();
channel = ui.data(|d| d.get_temp(pick)).filter(|c| chans.contains(c)).or(chans.first().copied()).unwrap_or(channel);
combo(ui, tr("Channel"), tr(channel.label()), |ui| {
for c in chans {
if ui.selectable_label(c == channel, tr(c.label())).clicked() {
ui.data_mut(|d| d.insert_temp(pick, c));
}
}
});
}
let key = egui::Id::unique(("levels_histogram", eid.0, channel));
let rev = app.session.revision;
let counts = match ui.data(|d| d.get_temp::<(u64, std::sync::Arc<Vec<u32>>)>(key)) {
Some((r, h)) if r == rev || ui.input(|i| i.pointer.any_down()) => Some(h),
_ => app.session.effect_histogram(eid, channel, 64).map(|h| {
let h = std::sync::Arc::new(h);
ui.data_mut(|d| d.insert_temp(key, (rev, h.clone())));
h
}),
};
if let Some(counts) = counts {
histogram(ui, &counts, range);
}
}
/// The parameters of filter effect `id`.
fn filter_properties(app: &mut TextureCraftApp, ui: &mut Ui, id: u64, f: &Filter) {
let tk = Tokens::get(ui.ctx());
+3
View File
@@ -77,6 +77,7 @@ pub const TABLE: &[(&str, &str)] = &[
("Apply", "تطبيق"),
("ArtCraft website...", "موقع ArtCraft الإلكتروني..."),
("Assets", "الأصول"),
("Auto", "تلقائي"),
("Automatic (from the mesh UVs)", "تلقائي (من إحداثيات UV للمجسم)"),
("Autosave every", "حفظ تلقائي كل"),
(
@@ -308,6 +309,7 @@ pub const TABLE: &[(&str, &str)] = &[
("Filters", "مرشحات"),
("Fine noise", "ضوضاء دقيقة"),
("Fingerprints", "بصمات أصابع"),
("Fit the input range to the histogram", "ملاءمة نطاق الإدخال مع المدرج التكراري"),
("Flatten layer", "تسطيح الطبقة"),
(
"Flips the image's green channel, for normal maps made with Y pointing down",
@@ -644,6 +646,7 @@ pub const TABLE: &[(&str, &str)] = &[
("Replacement color", "لون الاستبدال"),
("Report a bug...", "الإبلاغ عن خطأ..."),
("Rescan the library folder", "إعادة فحص مجلد المكتبة"),
("Reset", "إعادة تعيين"),
("Reset UI", "إعادة ضبط واجهة المستخدم"),
("Reset all", "إعادة ضبط الكل"),
("Reset to {shortcut}", "إعادة الضبط إلى {shortcut}"),
+3
View File
@@ -80,6 +80,7 @@ pub const TABLE: &[(&str, &str)] = &[
("Apply", "Anwenden"),
("ArtCraft website...", "ArtCraft-Website..."),
("Assets", "Assets"),
("Auto", "Auto"),
("Automatic (from the mesh UVs)", "Automatisch (aus den UVs des Meshs)"),
("Autosave every", "Automatisch speichern alle"),
(
@@ -332,6 +333,7 @@ pub const TABLE: &[(&str, &str)] = &[
("Filters", "Filter"),
("Fine noise", "Feines Rauschen"),
("Fingerprints", "Fingerabdrücke"),
("Fit the input range to the histogram", "Eingabebereich an das Histogramm anpassen"),
("Flatten layer", "Ebene reduzieren"),
(
"Flips the image's green channel, for normal maps made with Y pointing down",
@@ -683,6 +685,7 @@ pub const TABLE: &[(&str, &str)] = &[
("Replacement color", "Ersatzfarbe"),
("Report a bug...", "Fehler melden..."),
("Rescan the library folder", "Bibliotheksordner neu einlesen"),
("Reset", "Zurücksetzen"),
("Reset UI", "UI zurücksetzen"),
("Reset all", "Alle zurücksetzen"),
("Reset to {shortcut}", "Auf {shortcut} zurücksetzen"),
+3
View File
@@ -77,6 +77,7 @@ pub const TABLE: &[(&str, &str)] = &[
("Apply", "Aplicar"),
("ArtCraft website...", "Sitio web de ArtCraft..."),
("Assets", "Recursos"),
("Auto", "Auto"),
("Automatic (from the mesh UVs)", "Automático (según las UV de la malla)"),
("Autosave every", "Autoguardar cada"),
(
@@ -323,6 +324,7 @@ pub const TABLE: &[(&str, &str)] = &[
("Filters", "Filtros"),
("Fine noise", "Ruido fino"),
("Fingerprints", "Huellas dactilares"),
("Fit the input range to the histogram", "Ajustar el rango de entrada al histograma"),
("Flatten layer", "Acoplar capa"),
(
"Flips the image's green channel, for normal maps made with Y pointing down",
@@ -671,6 +673,7 @@ pub const TABLE: &[(&str, &str)] = &[
("Replacement color", "Color de reemplazo"),
("Report a bug...", "Informar de un error..."),
("Rescan the library folder", "Volver a examinar la carpeta de la biblioteca"),
("Reset", "Restablecer"),
("Reset UI", "Restablecer interfaz"),
("Reset all", "Restablecer todo"),
("Reset to {shortcut}", "Restablecer a {shortcut}"),
+3
View File
@@ -83,6 +83,7 @@ pub const TABLE: &[(&str, &str)] = &[
("Apply", "Appliquer"),
("ArtCraft website...", "Site web d'ArtCraft..."),
("Assets", "Ressources"),
("Auto", "Auto"),
("Automatic (from the mesh UVs)", "Automatique (d'après les UV du maillage)"),
("Autosave every", "Sauvegarde automatique toutes les"),
(
@@ -335,6 +336,7 @@ pub const TABLE: &[(&str, &str)] = &[
("Filters", "Filtres"),
("Fine noise", "Bruit fin"),
("Fingerprints", "Empreintes digitales"),
("Fit the input range to the histogram", "Ajuster la plage d'entrée à l'histogramme"),
("Flatten layer", "Aplatir le calque"),
(
"Flips the image's green channel, for normal maps made with Y pointing down",
@@ -686,6 +688,7 @@ pub const TABLE: &[(&str, &str)] = &[
("Replacement color", "Couleur de remplacement"),
("Report a bug...", "Signaler un bug..."),
("Rescan the library folder", "Réanalyser le dossier de la bibliothèque"),
("Reset", "Réinitialiser"),
("Reset UI", "Réinitialiser l'interface"),
("Reset all", "Tout réinitialiser"),
("Reset to {shortcut}", "Réinitialiser à {shortcut}"),
+3
View File
@@ -80,6 +80,7 @@ pub const TABLE: &[(&str, &str)] = &[
("Apply", "Applica"),
("ArtCraft website...", "Sito web di ArtCraft..."),
("Assets", "Risorse"),
("Auto", "Auto"),
("Automatic (from the mesh UVs)", "Automatico (dagli UV della mesh)"),
("Autosave every", "Salvataggio automatico ogni"),
(
@@ -329,6 +330,7 @@ pub const TABLE: &[(&str, &str)] = &[
("Filters", "Filtri"),
("Fine noise", "Rumore fine"),
("Fingerprints", "Impronte digitali"),
("Fit the input range to the histogram", "Adatta l'intervallo di input all'istogramma"),
("Flatten layer", "Appiattisci livello"),
(
"Flips the image's green channel, for normal maps made with Y pointing down",
@@ -680,6 +682,7 @@ pub const TABLE: &[(&str, &str)] = &[
("Replacement color", "Colore sostitutivo"),
("Report a bug...", "Segnala un bug..."),
("Rescan the library folder", "Ripeti la scansione della cartella della libreria"),
("Reset", "Reimposta"),
("Reset UI", "Ripristina interfaccia"),
("Reset all", "Ripristina tutto"),
("Reset to {shortcut}", "Ripristina {shortcut}"),
+3
View File
@@ -83,6 +83,7 @@ pub const TABLE: &[(&str, &str)] = &[
("Apply", "適用"),
("ArtCraft website...", "ArtCraft ウェブサイト..."),
("Assets", "アセット"),
("Auto", "自動"),
("Automatic (from the mesh UVs)", "自動 (メッシュのUVから)"),
("Autosave every", "自動保存の間隔"),
(
@@ -320,6 +321,7 @@ pub const TABLE: &[(&str, &str)] = &[
("Filters", "フィルター"),
("Fine noise", "細かいノイズ"),
("Fingerprints", "指紋"),
("Fit the input range to the histogram", "入力範囲をヒストグラムに合わせる"),
("Flatten layer", "レイヤーを統合"),
("Flips the image's green channel, for normal maps made with Y pointing down", "画像の緑チャンネルを反転します (Y が下向きで作られたノーマルマップ用)"),
("Flow", "フロー"),
@@ -662,6 +664,7 @@ pub const TABLE: &[(&str, &str)] = &[
("Replacement color", "置き換え後の色"),
("Report a bug...", "バグを報告..."),
("Rescan the library folder", "ライブラリフォルダーを再スキャン"),
("Reset", "リセット"),
("Reset UI", "UIをリセット"),
("Reset all", "すべてリセット"),
("Reset to {shortcut}", "{shortcut} にリセット"),
+3
View File
@@ -80,6 +80,7 @@ pub const TABLE: &[(&str, &str)] = &[
("Apply", "적용"),
("ArtCraft website...", "ArtCraft 웹사이트..."),
("Assets", "에셋"),
("Auto", "자동"),
("Automatic (from the mesh UVs)", "자동 (메시 UV 기준)"),
("Autosave every", "자동 저장 간격"),
(
@@ -317,6 +318,7 @@ pub const TABLE: &[(&str, &str)] = &[
("Filters", "필터"),
("Fine noise", "미세 노이즈"),
("Fingerprints", "지문"),
("Fit the input range to the histogram", "입력 범위를 히스토그램에 맞추기"),
("Flatten layer", "레이어 병합"),
("Flips the image's green channel, for normal maps made with Y pointing down", "이미지의 녹색 채널을 뒤집습니다 (Y가 아래를 향하도록 만든 노멀 맵용)"),
("Flow", "흐름"),
@@ -653,6 +655,7 @@ pub const TABLE: &[(&str, &str)] = &[
("Replacement color", "대체 색상"),
("Report a bug...", "버그 신고..."),
("Rescan the library folder", "라이브러리 폴더를 다시 검색합니다"),
("Reset", "초기화"),
("Reset UI", "UI 초기화"),
("Reset all", "모두 초기화"),
("Reset to {shortcut}", "{shortcut}(으)로 초기화"),
+3
View File
@@ -80,6 +80,7 @@ pub const TABLE: &[(&str, &str)] = &[
("Apply", "Aplicar"),
("ArtCraft website...", "Site da ArtCraft..."),
("Assets", "Recursos"),
("Auto", "Auto"),
("Automatic (from the mesh UVs)", "Automático (das UVs da malha)"),
("Autosave every", "Salvar automaticamente a cada"),
(
@@ -323,6 +324,7 @@ pub const TABLE: &[(&str, &str)] = &[
("Filters", "Filtros"),
("Fine noise", "Ruído fino"),
("Fingerprints", "Impressões digitais"),
("Fit the input range to the histogram", "Ajustar o intervalo de entrada ao histograma"),
("Flatten layer", "Achatar camada"),
(
"Flips the image's green channel, for normal maps made with Y pointing down",
@@ -668,6 +670,7 @@ pub const TABLE: &[(&str, &str)] = &[
("Replacement color", "Cor de substituição"),
("Report a bug...", "Relatar um bug..."),
("Rescan the library folder", "Reexaminar a pasta da biblioteca"),
("Reset", "Redefinir"),
("Reset UI", "Redefinir interface"),
("Reset all", "Redefinir tudo"),
("Reset to {shortcut}", "Redefinir para {shortcut}"),
+3
View File
@@ -71,6 +71,7 @@ pub const TABLE: &[(&str, &str)] = &[
("Apply", "应用"),
("ArtCraft website...", "ArtCraft 网站..."),
("Assets", "资产"),
("Auto", "自动"),
("Automatic (from the mesh UVs)", "自动(基于网格 UV)"),
("Autosave every", "自动保存间隔"),
(
@@ -290,6 +291,7 @@ pub const TABLE: &[(&str, &str)] = &[
("Filters", "滤镜"),
("Fine noise", "细噪波"),
("Fingerprints", "指纹"),
("Fit the input range to the histogram", "使输入范围适合直方图"),
("Flatten layer", "合并图层"),
("Flips the image's green channel, for normal maps made with Y pointing down", "翻转图像的绿色通道,用于 Y 轴朝下制作的法线贴图"),
("Flow", "流量"),
@@ -614,6 +616,7 @@ pub const TABLE: &[(&str, &str)] = &[
("Replacement color", "替换后的颜色"),
("Report a bug...", "报告错误..."),
("Rescan the library folder", "重新扫描库文件夹"),
("Reset", "重置"),
("Reset UI", "重置界面"),
("Reset all", "全部重置"),
("Reset to {shortcut}", "重置为 {shortcut}"),
+313
View File
@@ -0,0 +1,313 @@
//! The levels editor: draggable handles over a histogram and an output gradient, double-click to type a value
use egui::{Color32, CornerRadius, CursorIcon, Id, Pos2, Rect, Response, Sense, Stroke, Ui, WidgetInfo, pos2, vec2};
use texturecraft_engine::core::Levels;
use crate::levels_handle::LevelsHandle;
use crate::theme::Tokens;
const HISTOGRAM_HEIGHT: f32 = 56.0;
const HANDLE_HEIGHT: f32 = 11.0;
const HANDLE_HALF_WIDTH: f32 = 5.0;
/// Height of a handle's straight sides; the rest is its tip pointing at the track
const HANDLE_SIDE_HEIGHT: f32 = 6.0;
/// Extra width on each side of a handle that still grabs it
const HANDLE_GRAB_MARGIN: f32 = 2.0;
const GRADIENT_HEIGHT: f32 = 8.0;
const GAP_BELOW_HISTOGRAM: f32 = 3.0;
const VALUE_ROW_HEIGHT: f32 = 16.0;
const VALUE_FONT_SIZE: f32 = 10.5;
/// Width of the box a value is typed into
const TYPED_VALUE_WIDTH: f32 = 52.0;
/// Padding of the histogram well around its bars
const WELL_PADDING: f32 = 3.0;
/// Gray of the gamma handle, between the black input-low and white input-high handles
const GAMMA_HANDLE_GRAY: u8 = 128;
/// Grid lines across the histogram, at these fractions of its width
const GRID_FRACTIONS: [f32; 3] = [0.25, 0.5, 0.75];
/// Decimals of a value typed in or printed beside a handle (printed without trailing zeros)
const VALUE_DECIMALS: usize = 3;
/// Space kept around a printed value; a value closer to one already printed is left out
const VALUE_SPACING: f32 = 2.0;
/// Text margin inside the box a value is typed into
const TYPED_VALUE_MARGIN: egui::Vec2 = vec2(2.0, 1.0);
/// Opacity of the shade over the histogram outside the input range
const OUTSIDE_RANGE_SHADE: f32 = 0.7;
/// Opacity of the line at gamma, fainter than the input range's accent lines
const GAMMA_LINE_OPACITY: f32 = 0.6;
/// Edits `levels` over histogram `counts`; `Some(merge)` per change, `merge` true for a drag's later frames
pub fn levels_editor(ui: &mut Ui, id_salt: impl std::hash::Hash + std::fmt::Debug, counts: Option<&[u32]>, levels: &mut Levels) -> Option<bool> {
let height = VALUE_ROW_HEIGHT * 2.0 + HANDLE_HEIGHT * 2.0 + HISTOGRAM_HEIGHT + GAP_BELOW_HISTOGRAM + GRADIENT_HEIGHT;
let (rect, _) = ui.allocate_exact_size(vec2(ui.available_width(), height), Sense::hover());
let histogram_top = rect.top() + VALUE_ROW_HEIGHT + HANDLE_HEIGHT;
let gradient_top = output_handles_top(rect) - GRADIENT_HEIGHT;
let track = track(rect);
let id = ui.make_persistent_id(("levels_editor", id_salt));
// Gamma goes last so it stays grabbable between input handles that close in on it
let handles = [LevelsHandle::InputLow, LevelsHandle::InputHigh, LevelsHandle::Gamma, LevelsHandle::OutputLow, LevelsHandle::OutputHigh];
let mut edit = None;
let mut responses = Vec::with_capacity(handles.len());
for handle in handles {
let x = track_x(&track, handle.position(levels));
let top = handle_top(rect, handle);
let grab_half_width = HANDLE_HALF_WIDTH + HANDLE_GRAB_MARGIN;
let hit = Rect::from_x_y_ranges(x - grab_half_width..=x + grab_half_width, top..=top + HANDLE_HEIGHT);
let response = ui.interact(hit, id.with(handle), Sense::click_and_drag()).on_hover_cursor(CursorIcon::PointingHand);
if response.drag_started() {
ui.data_mut(|data| data.remove_temp::<bool>(response.id));
}
if response.dragged()
&& let Some(pointer) = response.interact_pointer_pos()
{
let mut next = *levels;
handle.set_position(&mut next, track_position(&track, pointer.x));
if next != *levels {
*levels = next;
edit = Some(continues_drag(ui, response.id));
}
}
let value = handle.value(levels);
response.widget_info(|| WidgetInfo::slider(true, f64::from(value), handle.label()));
responses.push((handle, response));
}
let typing_id = id.with("typing");
let double_clicked = responses.iter().find(|(_, response)| response.double_clicked()).map(|(handle, _)| *handle);
if let Some(handle) = double_clicked {
start_typing(ui, typing_id, handle, levels);
}
let typing = ui.data(|data| data.get_temp::<(LevelsHandle, String)>(typing_id));
let well = Rect::from_x_y_ranges(rect.x_range().shrink(HANDLE_HALF_WIDTH), histogram_top..=histogram_top + HISTOGRAM_HEIGHT);
paint_histogram(ui, well, counts.unwrap_or_default(), levels);
paint_output_gradient(ui, Rect::from_x_y_ranges(track, gradient_top..=gradient_top + GRADIENT_HEIGHT));
paint_handles_and_values(ui, rect, &responses, levels, typing.as_ref().map(|(handle, _)| *handle));
let typed = typing.and_then(|(handle, text)| typed_value(ui, rect, typing_id, (handle, text), double_clicked.is_some(), levels));
edit.or(typed)
}
fn handle_top(rect: Rect, handle: LevelsHandle) -> f32 {
if LevelsHandle::INPUT.contains(&handle) { rect.top() + VALUE_ROW_HEIGHT } else { output_handles_top(rect) }
}
fn output_handles_top(rect: Rect) -> f32 {
rect.bottom() - VALUE_ROW_HEIGHT - HANDLE_HEIGHT
}
/// The x range the handles move along in the editor's `rect`, lined up with the histogram bars
fn track(rect: Rect) -> egui::Rangef {
rect.x_range().shrink(HANDLE_HALF_WIDTH + WELL_PADDING)
}
fn track_x(track: &egui::Rangef, position: f32) -> f32 {
track.min + track.span() * position.clamp(0.0, 1.0)
}
fn track_position(track: &egui::Rangef, x: f32) -> f32 {
((x - track.min) / track.span().max(1.0)).clamp(0.0, 1.0)
}
/// True once the drag of `id` has already changed a value, so its later changes share that undo step
fn continues_drag(ui: &Ui, id: Id) -> bool {
ui.data_mut(|data| std::mem::replace(data.get_temp_mut_or_default::<bool>(id), true))
}
/// `value` with [`VALUE_DECIMALS`] decimals, trailing zeros dropped ("1", "0.25", "0.634")
fn shown_value(value: f32) -> String {
let fixed = format!("{value:.VALUE_DECIMALS$}");
fixed.trim_end_matches('0').trim_end_matches('.').to_string()
}
/// Where `handle`'s value of `size` goes: over an input handle, under an output one, inside `rect`
fn value_rect(rect: Rect, handle: LevelsHandle, levels: &Levels, size: egui::Vec2) -> Rect {
let x = track_x(&track(rect), handle.position(levels));
let top = handle_top(rect, handle);
let placed = if LevelsHandle::INPUT.contains(&handle) {
egui::Align2::CENTER_BOTTOM.anchor_size(pos2(x, top), size)
} else {
egui::Align2::CENTER_TOP.anchor_size(pos2(x, top + HANDLE_HEIGHT), size)
};
let shift = (rect.left() - placed.left()).max(0.0) + (rect.right() - placed.right()).min(0.0);
placed.translate(vec2(shift, 0.0))
}
/// The histogram in its well: quarter lines, the outside of the input range dimmed, lines at the handles
fn paint_histogram(ui: &Ui, well: Rect, counts: &[u32], levels: &Levels) {
let tokens = Tokens::get(ui.ctx());
let painter = ui.painter_at(well);
painter.rect(well, CornerRadius::same(tokens.radius), tokens.field, Stroke::new(1.0, tokens.field_border), egui::StrokeKind::Inside);
let inner = well.shrink(WELL_PADDING);
let vertical_line = |x: f32, color: Color32| painter.line_segment([pos2(x, inner.top()), pos2(x, inner.bottom())], Stroke::new(1.0, color));
for fraction in GRID_FRACTIONS {
vertical_line(track_x(&inner.x_range(), fraction), tokens.field_border);
}
let fullest = counts.iter().copied().max().unwrap_or(0).max(1) as f32;
let bar_width = inner.width() / counts.len().max(1) as f32;
for (index, count) in counts.iter().enumerate() {
let bar_height = inner.height() * *count as f32 / fullest;
let x = inner.left() + index as f32 * bar_width;
painter.rect_filled(Rect::from_min_max(pos2(x, inner.bottom() - bar_height), pos2(x + bar_width, inner.bottom())), 0.0, tokens.text_dim);
}
let x_at = |handle: LevelsHandle| track_x(&inner.x_range(), handle.position(levels));
let (low, high) = (x_at(LevelsHandle::InputLow), x_at(LevelsHandle::InputHigh));
let shade = tokens.field.gamma_multiply(OUTSIDE_RANGE_SHADE);
painter.rect_filled(Rect::from_x_y_ranges(inner.left()..=low, inner.y_range()), 0.0, shade);
painter.rect_filled(Rect::from_x_y_ranges(high..=inner.right(), inner.y_range()), 0.0, shade);
vertical_line(low, tokens.accent);
vertical_line(high, tokens.accent);
vertical_line(x_at(LevelsHandle::Gamma), tokens.text_dim.gamma_multiply(GAMMA_LINE_OPACITY));
}
/// A black-to-white strip: the output values the output handles pick from
fn paint_output_gradient(ui: &Ui, strip: Rect) {
let mut mesh = egui::Mesh::default();
for (corner, color) in
[(strip.left_top(), Color32::BLACK), (strip.right_top(), Color32::WHITE), (strip.right_bottom(), Color32::WHITE), (strip.left_bottom(), Color32::BLACK)]
{
mesh.colored_vertex(corner, color);
}
mesh.add_triangle(0, 1, 2);
mesh.add_triangle(0, 2, 3);
let painter = ui.painter();
painter.add(mesh);
painter.rect_stroke(strip, 0.0, Stroke::new(1.0, Tokens::get(ui.ctx()).field_border), egui::StrokeKind::Outside);
}
/// Each handle filled with its gray and its value beside it, the active one first and overlapping values left out
fn paint_handles_and_values(ui: &Ui, rect: Rect, responses: &[(LevelsHandle, Response)], levels: &Levels, typing: Option<LevelsHandle>) {
let track = track(rect);
let tokens = Tokens::get(ui.ctx());
let painter = ui.painter();
let font = egui::FontId::proportional(VALUE_FONT_SIZE);
let is_active = |response: &Response| response.dragged() || response.hovered();
let mut printed: Vec<Rect> = Vec::new();
let mut by_priority: Vec<&(LevelsHandle, Response)> = responses.iter().collect();
by_priority.sort_by_key(|(_, response)| !is_active(response));
for &(handle, ref response) in by_priority {
let x = track_x(&track, handle.position(levels));
let fill = match handle {
LevelsHandle::InputLow => Color32::BLACK,
LevelsHandle::Gamma => Color32::from_gray(GAMMA_HANDLE_GRAY),
LevelsHandle::InputHigh => Color32::WHITE,
LevelsHandle::OutputLow | LevelsHandle::OutputHigh => Color32::from_gray((handle.value(levels).clamp(0.0, 1.0) * 255.0).round() as u8),
};
let outline = if response.dragged() {
tokens.accent
} else if response.hovered() {
tokens.text_strong
} else {
tokens.text
};
let points_down = LevelsHandle::INPUT.contains(&handle);
painter.add(egui::Shape::convex_polygon(handle_outline(x, handle_top(rect, handle), points_down), fill, Stroke::new(1.0, outline)));
if typing == Some(handle) {
continue;
}
let color = if is_active(response) { tokens.text_strong } else { tokens.text_dim };
let galley = painter.layout_no_wrap(shown_value(handle.value(levels)), font.clone(), color);
let text_rect = value_rect(rect, handle, levels, galley.size());
if printed.iter().any(|other| other.expand(VALUE_SPACING).intersects(text_rect)) {
continue;
}
painter.galley(text_rect.min, galley, color);
printed.push(text_rect);
}
}
/// A pentagon pointer centred on `x`: flat side away from the track, tip touching it
fn handle_outline(x: f32, top: f32, points_down: bool) -> Vec<Pos2> {
let bottom = top + HANDLE_HEIGHT;
let (flat, side_end, tip) = if points_down { (top, top + HANDLE_SIDE_HEIGHT, bottom) } else { (bottom, bottom - HANDLE_SIDE_HEIGHT, top) };
vec![
pos2(x - HANDLE_HALF_WIDTH, flat),
pos2(x + HANDLE_HALF_WIDTH, flat),
pos2(x + HANDLE_HALF_WIDTH, side_end),
pos2(x, tip),
pos2(x - HANDLE_HALF_WIDTH, side_end),
]
}
/// Opens the box that types `handle`'s value, holding its current value
fn start_typing(ui: &Ui, typing_id: Id, handle: LevelsHandle, levels: &Levels) {
let text = format!("{:.VALUE_DECIMALS$}", handle.value(levels));
ui.data_mut(|data| data.insert_temp(typing_id, (handle, text)));
}
/// The floating box a value is typed into: Enter or a click elsewhere applies it as one undo step, Escape drops it
fn typed_value(ui: &Ui, rect: Rect, typing_id: Id, (handle, mut text): (LevelsHandle, String), opened: bool, levels: &mut Levels) -> Option<bool> {
let field_id = typing_id.with("field");
let field = value_rect(rect, handle, levels, vec2(TYPED_VALUE_WIDTH, VALUE_ROW_HEIGHT));
// Floating over the editor, so opening it never moves the rest of the panel
let response = egui::Area::new(typing_id.with("area"))
.order(egui::Order::Foreground)
.fixed_pos(field.min)
.show(ui.ctx(), |ui| {
let text_edit = egui::TextEdit::singleline(&mut text)
.id(field_id)
.font(egui::FontId::proportional(VALUE_FONT_SIZE))
.align(egui::Align2::CENTER_CENTER)
.margin(TYPED_VALUE_MARGIN);
ui.add_sized(field.size(), text_edit)
})
.inner;
// The app can consume Escape before the box sees it, so read the raw event
let escape = ui.input(|input| input.raw.events.iter().any(|event| matches!(event, egui::Event::Key { key: egui::Key::Escape, pressed: true, .. })));
if opened {
// Typing replaces the value; selected only now, as the unfocused box collapses a selection
let mut state = egui::text_edit::TextEditState::load(ui.ctx(), field_id).unwrap_or_default();
state.cursor.set_char_range(Some(egui::text::CCursorRange::select_all_str(&text)));
state.store(ui.ctx(), field_id);
response.request_focus();
return None;
}
if response.has_focus() && !escape {
ui.data_mut(|data| data.insert_temp(typing_id, (handle, text)));
return None;
}
ui.data_mut(|data| data.remove::<(LevelsHandle, String)>(typing_id));
ui.memory_mut(|memory| memory.surrender_focus(field_id));
// A box left open while the editor was hidden is dropped, not applied later
if !response.lost_focus() {
return None;
}
let typed = text.trim().parse::<f32>().ok().filter(|value| value.is_finite());
let (false, Some(typed)) = (escape, typed) else { return None };
let mut next = *levels;
handle.set_value(&mut next, typed);
if next == *levels {
return None;
}
*levels = next;
Some(false)
}
+91
View File
@@ -0,0 +1,91 @@
//! The five handles of the levels editor and how each one reads and moves a [`Levels`]
use texturecraft_engine::core::Levels;
use crate::i18n::tr;
/// Narrowest gap the handles and typed values leave between the low and high handle of a pair
const MIN_HANDLE_GAP: f32 = 0.01;
/// Gamma range of the handle and typed values: the engine's own, so the handle nearly reaches either input handle
const GAMMA_RANGE: std::ops::RangeInclusive<f32> = 0.01..=10.0;
/// One draggable value of a levels effect
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
pub enum LevelsHandle {
InputLow,
Gamma,
InputHigh,
OutputLow,
OutputHigh,
}
impl LevelsHandle {
/// The handles above the histogram, left to right at the default levels
pub const INPUT: [LevelsHandle; 3] = [LevelsHandle::InputLow, LevelsHandle::Gamma, LevelsHandle::InputHigh];
pub fn label(self) -> &'static str {
match self {
LevelsHandle::InputLow => tr("Input low"),
LevelsHandle::Gamma => tr("Gamma"),
LevelsHandle::InputHigh => tr("Input high"),
LevelsHandle::OutputLow => tr("Output low"),
LevelsHandle::OutputHigh => tr("Output high"),
}
}
pub fn value(self, levels: &Levels) -> f32 {
match self {
LevelsHandle::InputLow => levels.in_low,
LevelsHandle::Gamma => levels.gamma,
LevelsHandle::InputHigh => levels.in_high,
LevelsHandle::OutputLow => levels.out_low,
LevelsHandle::OutputHigh => levels.out_high,
}
}
/// Where the handle sits along its track (0 left, 1 right); gamma 1 is halfway between the input handles
pub fn position(self, levels: &Levels) -> f32 {
match self {
LevelsHandle::Gamma => levels.in_low + input_span(levels) * 0.5f32.powf(levels.gamma),
_ => self.value(levels),
}
.clamp(0.0, 1.0)
}
/// Moves the handle to `position` along its track (see [`Self::position`])
pub fn set_position(self, levels: &mut Levels, position: f32) {
let value = match self {
LevelsHandle::Gamma => {
let span = input_span(levels).max(f32::EPSILON);
let fraction = ((position - levels.in_low) / span).clamp(f32::EPSILON, 1.0 - f32::EPSILON);
fraction.ln() / 0.5f32.ln()
}
_ => position,
};
self.set_value(levels, value);
}
/// Sets the handle's value without crossing a neighbour: input low < gamma < input high, outputs keep their sides
pub fn set_value(self, levels: &mut Levels, value: f32) {
if !value.is_finite() {
return;
}
// The gap keeps each output handle on its side; min/max, not clamp, as a project's bounds can cross
let inverted = levels.out_low > levels.out_high;
match self {
LevelsHandle::InputLow => levels.in_low = value.min(levels.in_high - MIN_HANDLE_GAP).max(0.0),
LevelsHandle::Gamma => levels.gamma = value.clamp(*GAMMA_RANGE.start(), *GAMMA_RANGE.end()),
LevelsHandle::InputHigh => levels.in_high = value.max(levels.in_low + MIN_HANDLE_GAP).min(1.0),
LevelsHandle::OutputLow if inverted => levels.out_low = value.max(levels.out_high + MIN_HANDLE_GAP).min(1.0),
LevelsHandle::OutputLow => levels.out_low = value.min(levels.out_high - MIN_HANDLE_GAP).max(0.0),
LevelsHandle::OutputHigh if inverted => levels.out_high = value.min(levels.out_low - MIN_HANDLE_GAP).max(0.0),
LevelsHandle::OutputHigh => levels.out_high = value.max(levels.out_low + MIN_HANDLE_GAP).min(1.0),
}
}
}
fn input_span(levels: &Levels) -> f32 {
(levels.in_high - levels.in_low).max(0.0)
}
+130
View File
@@ -0,0 +1,130 @@
//! Properties of a levels effect: the levels editor, then the channel picker (content), Reset, Auto and Invert
use std::sync::Arc;
use egui::Ui;
use serde_json::json;
use texturecraft_engine::core::{Channel, ChannelKind, Layer, LayerId, Levels};
use crate::TextureCraftApp;
use crate::i18n::tr;
use crate::levels_editor::levels_editor;
use crate::theme::caption;
/// Buckets of the histogram, over 0..1
const HISTOGRAM_BUCKETS: usize = 64;
/// Share of the counted texels a bucket needs to hold for Auto to keep it in the input range
const AUTO_MIN_SHARE: f64 = 0.001;
/// The properties of levels effect `effect_id` of `layer`; every edit goes through `effect.set`
pub(crate) fn levels_properties(app: &mut TextureCraftApp, ui: &mut Ui, layer: &Layer, effect_id: LayerId, levels: &Levels) {
ui.label(caption(tr("Levels")));
let is_content = layer.content_effects.iter().any(|effect| effect.id == effect_id);
let channels: Vec<Channel> =
if is_content { layer.channels.keys().copied().filter(|channel| channel.kind() != ChannelKind::NormalMap).collect() } else { Vec::new() };
let picked = egui::Id::unique(("levels_channel", effect_id.0));
let channel = ui
.data(|data| data.get_temp(picked))
.filter(|channel| channels.contains(channel))
.or(channels.first().copied())
.or(layer.channels.keys().next().copied())
.unwrap_or(Channel::BaseColor);
let counts = histogram_counts(app, ui, effect_id, channel);
let mut edited = *levels;
let mut edit = levels_editor(ui, effect_id, counts.as_ref().map(|counts| counts.as_slice()), &mut edited);
ui.horizontal(|ui| {
if !channels.is_empty() {
egui::ComboBox::from_id_salt(picked)
.selected_text(tr(channel.label()))
.show_ui(ui, |ui| {
for option in channels {
if ui.selectable_label(option == channel, tr(option.label())).clicked() {
ui.data_mut(|data| data.insert_temp(picked, option));
}
}
})
.response
.on_hover_text(tr("Channel"));
}
// Right to left: the last button comes first
ui.with_layout(egui::Layout::right_to_left(egui::Align::Center), |ui| {
if ui.button(tr("Invert")).clicked() {
std::mem::swap(&mut edited.out_low, &mut edited.out_high);
edit = Some(false);
}
let auto_range = counts.as_ref().and_then(|counts| auto_input_range(counts));
let auto = ui.add_enabled(auto_range.is_some(), egui::Button::new(tr("Auto"))).on_hover_text(tr("Fit the input range to the histogram"));
if auto.clicked()
&& let Some((low, high)) = auto_range
{
(edited.in_low, edited.in_high) = (low, high);
edit = Some(false);
}
if ui.add_enabled(edited != Levels::default(), egui::Button::new(tr("Reset"))).clicked() {
edited = Levels::default();
edit = Some(false);
}
});
});
// Auto or Invert with nothing to change would add an empty undo step
if let Some(merge) = edit
&& edited != *levels
{
let Levels { in_low, in_high, gamma, out_low, out_high } = edited;
app.run(
"effect.set",
json!({"effect": effect_id.0, "inLow": in_low, "inHigh": in_high, "gamma": gamma, "outLow": out_low, "outHigh": out_high, "merge": merge}),
);
}
}
/// The histogram levels effect `effect_id` remaps, recomputed after a change once no pointer button is held
fn histogram_counts(app: &TextureCraftApp, ui: &Ui, effect_id: LayerId, channel: Channel) -> Option<Arc<Vec<u32>>> {
let key = egui::Id::unique(("levels_histogram", effect_id.0, channel));
let revision = app.session.revision;
match ui.data(|data| data.get_temp::<(u64, Arc<Vec<u32>>)>(key)) {
Some((cached, counts)) if cached == revision || ui.input(|input| input.pointer.any_down()) => Some(counts),
_ => app.session.effect_histogram(effect_id, channel, HISTOGRAM_BUCKETS).map(|counts| {
let counts = Arc::new(counts);
ui.data_mut(|data| data.insert_temp(key, (revision, counts.clone())));
counts
}),
}
}
/// The input range Auto picks: the first to the last bucket holding more than [`AUTO_MIN_SHARE`] of the texels
fn auto_input_range(counts: &[u32]) -> Option<(f32, f32)> {
let total: u64 = counts.iter().map(|&count| u64::from(count)).sum();
let holds_enough = |count: &u32| f64::from(*count) > total as f64 * AUTO_MIN_SHARE;
let first = counts.iter().position(holds_enough)?;
let last = counts.iter().rposition(holds_enough)?;
let buckets = counts.len() as f32;
Some((first as f32 / buckets, (last + 1) as f32 / buckets))
}
#[cfg(test)]
mod tests {
use super::{HISTOGRAM_BUCKETS, auto_input_range};
#[test]
fn auto_skips_buckets_under_the_share() {
let mut counts = vec![0u32; HISTOGRAM_BUCKETS];
counts[3] = 1;
counts[10] = 5_000;
counts[40] = 5_000;
counts[60] = 1;
assert_eq!(auto_input_range(&counts), Some((10.0 / HISTOGRAM_BUCKETS as f32, 41.0 / HISTOGRAM_BUCKETS as f32)));
}
#[test]
fn auto_has_nothing_to_fit_in_an_empty_histogram() {
assert_eq!(auto_input_range(&[0; HISTOGRAM_BUCKETS]), None);
assert_eq!(auto_input_range(&[]), None);
}
}
+3
View File
@@ -16,6 +16,9 @@ pub mod fonts;
pub mod gpu;
pub mod i18n;
pub mod keymap;
mod levels_editor;
mod levels_handle;
mod levels_properties;
mod mask_preview_image;
mod mask_shape;
pub mod menus;
-25
View File
@@ -142,31 +142,6 @@ fn track(ui: &Ui, resp: &Response, x: std::ops::RangeInclusive<f32>, y: f32, t:
p.circle(egui::pos2(xk, y), knob, tk.panel, Stroke::new(1.5, ring));
}
/// A histogram of `counts` (buckets over 0..1, scaled to the fullest) in a field-colored well
/// the width of the panel, the part of 0..1 outside `range` dimmed.
pub fn histogram(ui: &mut Ui, counts: &[u32], range: (f32, f32)) -> Response {
let tk = Tokens::get(ui.ctx());
let (rect, resp) = ui.allocate_exact_size(vec2(ui.available_width(), 56.0), Sense::hover());
let p = ui.painter_at(rect);
p.rect(rect, CornerRadius::same(tk.radius), tk.field, Stroke::new(1.0, tk.field_border), egui::StrokeKind::Inside);
let inner = rect.shrink(3.0);
let max = counts.iter().copied().max().unwrap_or(0).max(1) as f32;
let w = inner.width() / counts.len().max(1) as f32;
for (i, c) in counts.iter().enumerate() {
let h = inner.height() * *c as f32 / max;
let x = inner.left() + i as f32 * w;
p.rect_filled(egui::Rect::from_min_max(egui::pos2(x, inner.bottom() - h), egui::pos2(x + w, inner.bottom())), 0.0, tk.text_dim);
}
let x = |t: f32| inner.left() + inner.width() * t.clamp(0.0, 1.0);
let shade = tk.field.gamma_multiply(0.7);
p.rect_filled(egui::Rect::from_x_y_ranges(inner.left()..=x(range.0), inner.y_range()), 0.0, shade);
p.rect_filled(egui::Rect::from_x_y_ranges(x(range.1)..=inner.right(), inner.y_range()), 0.0, shade);
for t in [range.0, range.1] {
p.line_segment([egui::pos2(x(t), inner.top()), egui::pos2(x(t), inner.bottom())], Stroke::new(1.0, tk.accent));
}
resp
}
/// One line of `text` cut with "…" to fit `max_width`, for list rows that shrink with their panel.
pub fn elided(painter: &egui::Painter, text: impl Into<String>, size: f32, color: Color32, max_width: f32) -> std::sync::Arc<egui::Galley> {
let mut job = egui::text::LayoutJob::simple_singleline(text.into(), egui::FontId::proportional(size), color);
+3 -3
View File
@@ -78,10 +78,10 @@ fn dragging_a_generator_slider_applies_live_as_one_undo_step() {
assert_eq!(h.state().session.history_labels().len(), steps + 1, "one undo step for the drag");
}
/// The combo box in the row of the "Channel" label.
/// The combo box in the row of the levels editor's Reset button.
fn channel_picker<'a>(h: &'a Harness<'_, TextureCraftApp>) -> egui_kittest::Node<'a> {
let row = h.get_by_label("Channel").rect().center().y;
h.get_all(by().role(Role::ComboBox)).find(|n| (n.rect().center().y - row).abs() < 4.0).unwrap()
let row = h.get_by_label("Reset").rect().center().y;
h.get_all(by().role(Role::ComboBox)).find(|node| (node.rect().center().y - row).abs() < 4.0).unwrap()
}
/// A content levels effect offers a channel for its histogram; picking one keeps it selected.
+247
View File
@@ -0,0 +1,247 @@
//! The levels editor in Properties: handles, typed values and Reset, Auto and Invert edit the effect
use egui::accesskit::Role;
use egui_kittest::Harness;
use egui_kittest::kittest::{NodeT, Queryable, by};
use serde_json::{Value, json};
use texturecraft_engine::core::{Channel, EffectKind, LayerId, Levels};
use texturecraft_engine::{Session, execute};
use texturecraft_ui_egui::TextureCraftApp;
/// Histogram buckets and Auto's share, as in levels_properties.rs
const HISTOGRAM_BUCKETS: usize = 64;
const AUTO_MIN_SHARE: f64 = 0.001;
/// A clouds mask under a levels effect added by `command` with `params`, selected, and its id
fn levels_harness(command: &str, params: Value) -> (Harness<'static, TextureCraftApp>, LayerId) {
let mut session = texturecraft_engine::sample_session(256, 64).unwrap();
for (id, params) in [
("layer.add.fill", json!({"color": [0.8, 0.3, 0.1]})),
("mask.add.black", Value::Null),
("effect.add.fill", json!({"target": "mask", "procedural": "clouds"})),
(command, params),
] {
execute(&mut session, id, &params).unwrap();
}
let effect = levels_effect(&session);
open(session, effect)
}
fn open(mut session: Session, effect: LayerId) -> (Harness<'static, TextureCraftApp>, LayerId) {
let (layer, _) = session.doc.project.effect(effect).unwrap();
execute(&mut session, "layer.select", &json!({"layer": layer.0, "target": effect.0})).unwrap();
// Frames of a 60 Hz screen: kittest's default quarter second spreads a double-click past egui's delay
let mut harness = Harness::builder().with_size(egui::vec2(1600.0, 1400.0)).with_step_dt(1.0 / 60.0).build_eframe(|cc| TextureCraftApp::new(cc, session));
harness.run_steps(4);
(harness, effect)
}
/// The newest levels effect in the project
fn levels_effect(session: &Session) -> LayerId {
let layers = session.doc.project.layers.values();
let effects = layers.flat_map(|layer| layer.content_effects.iter().chain(layer.mask.iter().flat_map(|mask| mask.effects.iter())));
effects.filter(|effect| matches!(effect.kind, EffectKind::Levels(_))).map(|effect| effect.id).max_by_key(|id| id.0).unwrap()
}
fn levels(harness: &Harness<'_, TextureCraftApp>, effect: LayerId) -> Levels {
match &harness.state().session.doc.project.effect(effect).unwrap().1.kind {
EffectKind::Levels(levels) => *levels,
other => panic!("a levels effect, found {other:?}"),
}
}
fn undo_steps(harness: &Harness<'_, TextureCraftApp>) -> usize {
harness.state().session.history_labels().len()
}
fn handle(harness: &Harness<'_, TextureCraftApp>, label: &str) -> egui::Pos2 {
harness.get_by_role_and_label(Role::Slider, label).rect().center()
}
/// The button labelled `label` (an effect in the stack can share its name)
fn button<'a>(harness: &'a Harness<'_, TextureCraftApp>, label: &'a str) -> egui_kittest::Node<'a> {
harness.get_by_role_and_label(Role::Button, label)
}
/// Presses at `from`, moves in a few steps to `to` (one frame each, like a hand) and releases
fn drag(harness: &mut Harness<'_, TextureCraftApp>, from: egui::Pos2, to: egui::Pos2) {
harness.drag_at(from);
harness.run_steps(2);
for step in 1..=4 {
harness.hover_at(from + (to - from) * (step as f32 / 4.0));
harness.run_steps(1);
}
harness.drop_at(to);
harness.run_steps(3);
}
fn set_levels(harness: &mut Harness<'_, TextureCraftApp>, effect: LayerId, mut params: Value) {
params["effect"] = json!(effect.0);
execute(&mut harness.state_mut().session, "effect.set", &params).unwrap();
harness.run_steps(3);
}
#[test]
fn dragging_each_handle_edits_its_value_in_one_undo_step() {
let (mut harness, effect) = levels_harness("effect.add.levels", json!({"target": "mask"}));
for (label, offset_x) in [("Input low", 80.0), ("Input high", -80.0), ("Gamma", 30.0), ("Output low", 60.0), ("Output high", -60.0)] {
let before = levels(&harness, effect);
let steps = undo_steps(&harness);
let at = handle(&harness, label);
drag(&mut harness, at, at + egui::vec2(offset_x, 0.0));
let after = levels(&harness, effect);
let changed: Vec<&str> = [
("Input low", before.in_low != after.in_low),
("Input high", before.in_high != after.in_high),
("Gamma", before.gamma != after.gamma),
("Output low", before.out_low != after.out_low),
("Output high", before.out_high != after.out_high),
]
.into_iter()
.filter_map(|(name, changed)| changed.then_some(name))
.collect();
assert_eq!(changed, [label], "dragging {label} changes only it: {before:?} -> {after:?}");
assert_eq!(undo_steps(&harness), steps + 1, "dragging {label} is one undo step");
}
let dragged = levels(&harness, effect);
assert!(dragged.in_low > 0.0 && dragged.in_high < 1.0 && dragged.out_low > 0.0 && dragged.out_high < 1.0, "{dragged:?}");
assert!(dragged.gamma < 1.0, "gamma right of the middle darkens: {}", dragged.gamma);
}
#[test]
fn handles_stop_at_their_neighbours() {
let (mut harness, effect) = levels_harness("effect.add.levels", json!({"target": "mask", "inLow": 0.2, "inHigh": 0.6, "outLow": 0.3, "outHigh": 0.7}));
let far_right = egui::vec2(1000.0, 0.0);
for label in ["Input low", "Gamma", "Output low"] {
let at = handle(&harness, label);
drag(&mut harness, at, at + far_right);
}
let edited = levels(&harness, effect);
assert!((edited.in_low - 0.59).abs() < 1e-4, "input low stops below input high: {edited:?}");
assert_eq!(edited.gamma, 0.01, "gamma stops at its lowest value");
let gap = handle(&harness, "Input high").x - handle(&harness, "Gamma").x;
assert!((0.0..1.0).contains(&gap), "the gamma handle reaches input high over this narrow range: {gap} pt apart");
assert!((edited.out_low - 0.69).abs() < 1e-4, "output low stops below output high: {edited:?}");
}
#[test]
fn output_handles_keep_their_side_once_inverted() {
let (mut harness, effect) = levels_harness("effect.add.levels", json!({"target": "mask", "outLow": 0.2, "outHigh": 0.8}));
button(&harness, "Invert").click();
harness.run_steps(3);
let inverted = levels(&harness, effect);
assert_eq!((inverted.out_low, inverted.out_high), (0.8, 0.2));
let at = handle(&harness, "Output high");
drag(&mut harness, at, at + egui::vec2(1000.0, 0.0));
let edited = levels(&harness, effect);
assert!((edited.out_high - 0.79).abs() < 1e-4, "output high stops below output low: {edited:?}");
}
#[test]
fn reset_and_invert_are_one_undo_step_each() {
let (mut harness, effect) = levels_harness("effect.add.levels", json!({"target": "mask"}));
assert!(button(&harness, "Reset").accesskit_node().is_disabled(), "nothing to reset at the defaults");
set_levels(&mut harness, effect, json!({"inLow": 0.1, "inHigh": 0.9, "gamma": 2.0, "outLow": 0.2, "outHigh": 0.7}));
let steps = undo_steps(&harness);
button(&harness, "Invert").click();
harness.run_steps(3);
assert_eq!(levels(&harness, effect), Levels { in_low: 0.1, in_high: 0.9, gamma: 2.0, out_low: 0.7, out_high: 0.2 });
assert_eq!(undo_steps(&harness), steps + 1);
button(&harness, "Reset").click();
harness.run_steps(3);
assert_eq!(levels(&harness, effect), Levels::default());
assert_eq!(undo_steps(&harness), steps + 2);
}
#[test]
fn auto_fits_the_input_range_to_the_histogram() {
let (mut harness, effect) = levels_harness("effect.add.levels", json!({"target": "mask", "gamma": 1.5}));
let counts = harness.state().session.effect_histogram(effect, Channel::BaseColor, HISTOGRAM_BUCKETS).unwrap();
let total: u32 = counts.iter().sum();
let holds = |count: &u32| f64::from(*count) > f64::from(total) * AUTO_MIN_SHARE;
let low = counts.iter().position(holds).unwrap() as f32 / HISTOGRAM_BUCKETS as f32;
let high = (counts.iter().rposition(holds).unwrap() + 1) as f32 / HISTOGRAM_BUCKETS as f32;
assert!(low > 0.0 || high < 1.0, "the clouds don't fill the whole range: {low}..{high}");
button(&harness, "Auto").click();
harness.run_steps(3);
let edited = levels(&harness, effect);
assert_eq!((edited.in_low, edited.in_high), (low, high));
assert_eq!(edited.gamma, 1.5, "Auto leaves gamma");
let steps = undo_steps(&harness);
button(&harness, "Auto").click();
harness.run_steps(3);
assert_eq!(undo_steps(&harness), steps, "Auto again changes nothing, so it adds no undo step");
}
/// Double-clicks `label`'s handle, then types `text` into the box that opens with the value selected
fn type_value(harness: &mut Harness<'_, TextureCraftApp>, label: &str, text: &str) {
let at = handle(harness, label);
harness.event(egui::Event::PointerMoved(at));
for pressed in [true, false, true, false] {
harness.event(egui::Event::PointerButton { pos: at, button: egui::PointerButton::Primary, pressed, modifiers: egui::Modifiers::NONE });
}
harness.run_steps(2);
for character in text.chars() {
harness.event(egui::Event::Text(character.to_string()));
harness.run_steps(1);
}
}
#[test]
fn a_value_typed_after_double_clicking_a_handle_applies() {
let (mut harness, effect) = levels_harness("effect.add.levels", json!({"target": "mask"}));
let steps = undo_steps(&harness);
type_value(&mut harness, "Gamma", "2.5");
harness.key_press(egui::Key::Enter);
harness.run_steps(3);
assert_eq!(levels(&harness, effect).gamma, 2.5);
assert_eq!(undo_steps(&harness), steps + 1);
}
#[test]
fn the_typing_box_moves_nothing_in_the_panel() {
let (mut harness, _) = levels_harness("effect.add.levels", json!({"target": "mask"}));
let buttons = |harness: &Harness<'_, TextureCraftApp>| ["Reset", "Auto", "Invert"].map(|label| button(harness, label).rect());
let before = buttons(&harness);
type_value(&mut harness, "Output low", "");
assert!(harness.query_all(by().role(Role::TextInput)).any(|node| node.is_focused()), "the box is open");
assert_eq!(buttons(&harness), before);
}
#[test]
fn escape_drops_a_typed_value() {
let (mut harness, effect) = levels_harness("effect.add.levels", json!({"target": "mask"}));
let steps = undo_steps(&harness);
type_value(&mut harness, "Output low", "0.4");
harness.key_press(egui::Key::Escape);
harness.run_steps(3);
assert_eq!(levels(&harness, effect), Levels::default());
assert_eq!(undo_steps(&harness), steps);
assert!(harness.query_by_value("0.4").is_none(), "the box closed");
}
#[test]
fn a_typed_value_keeps_input_low_below_input_high() {
let (mut harness, effect) = levels_harness("effect.add.levels", json!({"target": "mask", "inHigh": 0.5}));
type_value(&mut harness, "Input low", "0.9");
harness.key_press(egui::Key::Enter);
harness.run_steps(3);
assert!((levels(&harness, effect).in_low - 0.49).abs() < 1e-4, "{:?}", levels(&harness, effect));
}
#[test]
fn the_levels_filter_shows_the_same_editor() {
let (harness, _) = levels_harness("effect.add.filter", json!({"target": "mask", "filter": "levels"}));
for label in ["Input low", "Gamma", "Input high", "Output low", "Output high"] {
harness.get_by_role_and_label(Role::Slider, label);
}
for button in ["Reset", "Auto", "Invert"] {
harness.get_by_role_and_label(Role::Button, button);
}
}