feat: add production UI gallery and inspector system
CI / Format, lint, test, build (push) Waiting to run
CI / Format, lint, test, build (push) Waiting to run
This commit is contained in:
1 parent
cf6eaba534
commit
53dc1e44d8
95 files changed
+11003
-1652
No files matched your search
@@ -31,6 +31,7 @@ bevy_egui.workspace = true
|
||||
bevy-inspector-egui.workspace = true
|
||||
egui_dock.workspace = true
|
||||
egui_phosphor_icons.workspace = true
|
||||
editor_ui.workspace = true
|
||||
bevy_ufbx.workspace = true
|
||||
content_pipeline.workspace = true
|
||||
ufbx = "0.9"
|
||||
|
||||
@@ -62,33 +62,53 @@ fn color_control_impl(
|
||||
) -> ColorPickerResponse {
|
||||
let palette = super::palette(ui);
|
||||
let id = ui.make_persistent_id(("penpot_color_picker", salt));
|
||||
let (rect, response) = ui.allocate_exact_size(egui::vec2(130.0, 22.0), egui::Sense::click());
|
||||
let swatch_rect = egui::Rect::from_min_size(rect.min, egui::vec2(24.0, 22.0));
|
||||
let hex_rect =
|
||||
egui::Rect::from_min_size(rect.min + egui::vec2(30.0, 0.0), egui::vec2(100.0, 22.0));
|
||||
let width = ui.available_width().max(1.0);
|
||||
let (rect, response) = ui.allocate_exact_size(egui::vec2(width, 22.0), egui::Sense::click());
|
||||
let swatch_width = 44.0_f32.min(width);
|
||||
let swatch_rect = egui::Rect::from_min_size(rect.min, egui::vec2(swatch_width, 22.0));
|
||||
let gap = if width > swatch_width + 6.0 { 6.0 } else { 0.0 };
|
||||
let hex_rect = egui::Rect::from_min_size(
|
||||
rect.min + egui::vec2(swatch_width + gap, 0.0),
|
||||
egui::vec2((width - swatch_width - gap).max(0.0), 22.0),
|
||||
);
|
||||
popup::checker(ui.painter(), swatch_rect, palette.control, palette.elevated);
|
||||
ui.painter()
|
||||
.rect_filled(swatch_rect.shrink(1.0), 4.0, color32(*rgba));
|
||||
let inner_swatch = swatch_rect.shrink(1.0);
|
||||
let rgb_rect = egui::Rect::from_min_max(
|
||||
inner_swatch.min,
|
||||
egui::pos2(inner_swatch.center().x, inner_swatch.max.y),
|
||||
);
|
||||
let alpha_rect = egui::Rect::from_min_max(
|
||||
egui::pos2(inner_swatch.center().x, inner_swatch.min.y),
|
||||
inner_swatch.max,
|
||||
);
|
||||
ui.painter().rect_filled(
|
||||
rgb_rect,
|
||||
3.0,
|
||||
egui::Color32::from_rgb(byte(rgba[0]), byte(rgba[1]), byte(rgba[2])),
|
||||
);
|
||||
ui.painter().rect_filled(alpha_rect, 3.0, color32(*rgba));
|
||||
ui.painter().rect_stroke(
|
||||
swatch_rect,
|
||||
4.0,
|
||||
egui::Stroke::new(1.0_f32, palette.border_strong),
|
||||
egui::StrokeKind::Inside,
|
||||
);
|
||||
ui.painter().rect(
|
||||
hex_rect,
|
||||
4.0,
|
||||
palette.control,
|
||||
egui::Stroke::new(1.0_f32, palette.border),
|
||||
egui::StrokeKind::Inside,
|
||||
);
|
||||
ui.painter().text(
|
||||
hex_rect.left_center() + egui::vec2(9.0, 0.0),
|
||||
egui::Align2::LEFT_CENTER,
|
||||
hex(*rgba),
|
||||
TypeRole::Body.font(),
|
||||
palette.text_primary,
|
||||
);
|
||||
if hex_rect.width() > 0.0 {
|
||||
ui.painter().rect(
|
||||
hex_rect,
|
||||
4.0,
|
||||
palette.control,
|
||||
egui::Stroke::new(1.0_f32, palette.border),
|
||||
egui::StrokeKind::Inside,
|
||||
);
|
||||
ui.painter().text(
|
||||
hex_rect.left_center() + egui::vec2(9.0, 0.0),
|
||||
egui::Align2::LEFT_CENTER,
|
||||
hex(*rgba),
|
||||
TypeRole::Body.font(),
|
||||
palette.text_primary,
|
||||
);
|
||||
}
|
||||
|
||||
if response.clicked() {
|
||||
let opened_at = ui.input(|input| input.time);
|
||||
|
||||
@@ -7,12 +7,10 @@ use std::ops::RangeInclusive;
|
||||
use super::palette;
|
||||
use super::typography::TypeRole;
|
||||
|
||||
const SCALAR_CONTROL_WIDTH: f32 = 132.0;
|
||||
const SCALAR_TRACK_X: f32 = 0.0;
|
||||
const SCALAR_TRACK_WIDTH: f32 = 78.0;
|
||||
const SCALAR_TRACK_X: f32 = 6.0;
|
||||
const SCALAR_NUMBER_GAP: f32 = 6.0;
|
||||
const SCALAR_TRACK_INTERACTION_HEIGHT: f32 = 10.0;
|
||||
const SCALAR_NUMBER_X: f32 = 84.0;
|
||||
const SCALAR_NUMBER_WIDTH: f32 = 48.0;
|
||||
const SCALAR_NUMBER_WIDTH: f32 = 33.0;
|
||||
const SCALAR_THUMB_RADIUS: f32 = 4.0;
|
||||
|
||||
pub(crate) fn section_frame(ui: &egui::Ui) -> egui::Frame {
|
||||
@@ -50,7 +48,7 @@ pub(crate) fn section_header_with_summary(
|
||||
} else {
|
||||
icons::CARET_RIGHT.as_str()
|
||||
},
|
||||
egui::FontId::new(10.0, egui::FontFamily::Name("phosphor-regular".into())),
|
||||
egui::FontId::new(10.0, egui::FontFamily::Name("phosphor-bold".into())),
|
||||
palette.text_secondary,
|
||||
);
|
||||
ui.painter().text(
|
||||
@@ -90,10 +88,7 @@ pub(crate) fn icon_label(
|
||||
icon.as_str(),
|
||||
0.0,
|
||||
egui::TextFormat {
|
||||
font_id: egui::FontId::new(
|
||||
icon_size,
|
||||
egui::FontFamily::Name("phosphor-regular".into()),
|
||||
),
|
||||
font_id: egui::FontId::new(icon_size, egui::FontFamily::Name("phosphor-bold".into())),
|
||||
color,
|
||||
..Default::default()
|
||||
},
|
||||
@@ -123,7 +118,7 @@ pub(crate) fn icon_button(
|
||||
enabled,
|
||||
egui::Button::new(egui::RichText::new(icon.as_str()).font(egui::FontId::new(
|
||||
14.0,
|
||||
egui::FontFamily::Name("phosphor-regular".into()),
|
||||
egui::FontFamily::Name("phosphor-bold".into()),
|
||||
)))
|
||||
.min_size(egui::vec2(24.0, 24.0))
|
||||
.fill(palette.control)
|
||||
@@ -133,12 +128,35 @@ pub(crate) fn icon_button(
|
||||
response.on_hover_text(tooltip)
|
||||
}
|
||||
|
||||
pub(crate) fn status(ui: &mut egui::Ui, color: egui::Color32, label: &str, tooltip: &str) {
|
||||
pub(crate) fn status(
|
||||
ui: &mut egui::Ui,
|
||||
icon: Icon,
|
||||
color: egui::Color32,
|
||||
label: &str,
|
||||
tooltip: &str,
|
||||
) {
|
||||
let palette = palette(ui);
|
||||
let (dot, response) = ui.allocate_exact_size(egui::vec2(8.0, 14.0), egui::Sense::hover());
|
||||
ui.painter().circle_filled(dot.center(), 4.0, color);
|
||||
let mut job = egui::text::LayoutJob::default();
|
||||
job.append(
|
||||
icon.as_str(),
|
||||
0.0,
|
||||
egui::TextFormat {
|
||||
font_id: egui::FontId::new(12.0, egui::FontFamily::Name("phosphor-bold".into())),
|
||||
color,
|
||||
..Default::default()
|
||||
},
|
||||
);
|
||||
job.append(
|
||||
label,
|
||||
5.0,
|
||||
egui::TextFormat {
|
||||
font_id: TypeRole::Body.font(),
|
||||
color: palette.text_secondary,
|
||||
..Default::default()
|
||||
},
|
||||
);
|
||||
let response = ui.add(egui::Label::new(job).sense(egui::Sense::hover()));
|
||||
response.on_hover_text(tooltip);
|
||||
ui.label(TypeRole::Body.text(label).color(palette.text_secondary));
|
||||
}
|
||||
|
||||
pub(crate) fn switch(ui: &mut egui::Ui, value: &mut bool) -> egui::Response {
|
||||
@@ -260,12 +278,15 @@ pub(crate) fn scalar_control(
|
||||
) -> egui::Response {
|
||||
let palette = palette(ui);
|
||||
let before = *value;
|
||||
let width = SCALAR_CONTROL_WIDTH.min(ui.available_width().max(1.0));
|
||||
// The final Penpot component deliberately stretches only the track at the compact
|
||||
// breakpoint: 93.8 px at the 569 px reference and 160.3 px at the 369 px reference.
|
||||
// The numeric field remains a stable 33 px in both modes.
|
||||
let width = ui.available_width().max(1.0);
|
||||
let (rect, base_response) =
|
||||
ui.allocate_exact_size(egui::vec2(width, 22.0), egui::Sense::hover());
|
||||
let number_width = SCALAR_NUMBER_WIDTH.min(width);
|
||||
let number_x = SCALAR_NUMBER_X.min((width - number_width).max(0.0));
|
||||
let track_width = SCALAR_TRACK_WIDTH.min((number_x - 6.0).max(1.0));
|
||||
let number_x = (width - number_width).max(0.0);
|
||||
let track_width = (number_x - SCALAR_TRACK_X - SCALAR_NUMBER_GAP).max(1.0);
|
||||
let slider_rect = egui::Rect::from_min_size(
|
||||
rect.min + egui::vec2(SCALAR_TRACK_X, 6.0),
|
||||
egui::vec2(track_width, SCALAR_TRACK_INTERACTION_HEIGHT),
|
||||
@@ -337,8 +358,15 @@ mod scalar_tests {
|
||||
|
||||
#[test]
|
||||
fn penpot_scalar_geometry_matches_the_current_export() {
|
||||
assert!((SCALAR_NUMBER_X - (SCALAR_TRACK_X + SCALAR_TRACK_WIDTH) - 6.0).abs() < 0.001);
|
||||
assert_eq!(SCALAR_CONTROL_WIDTH, SCALAR_NUMBER_X + SCALAR_NUMBER_WIDTH);
|
||||
let wide_width = 132.8;
|
||||
let wide_number_x = wide_width - SCALAR_NUMBER_WIDTH;
|
||||
let wide_track = wide_number_x - SCALAR_TRACK_X - SCALAR_NUMBER_GAP;
|
||||
assert!((wide_track - 93.8).abs() < 0.001);
|
||||
|
||||
let compact_width = 199.3;
|
||||
let compact_number_x = compact_width - SCALAR_NUMBER_WIDTH;
|
||||
let compact_track = compact_number_x - SCALAR_TRACK_X - SCALAR_NUMBER_GAP;
|
||||
assert!((compact_track - 160.3).abs() < 0.001);
|
||||
assert_eq!(SCALAR_TRACK_INTERACTION_HEIGHT, 10.0);
|
||||
assert_eq!(SCALAR_THUMB_RADIUS, 4.0);
|
||||
}
|
||||
|
||||
@@ -3,7 +3,14 @@
|
||||
use super::{COMPACT_PARAMETER_ROW_HEIGHT, PARAMETER_ROW_HEIGHT};
|
||||
use bevy_egui::egui;
|
||||
|
||||
pub(crate) const WIDE_SECTION_WIDTH: f32 = 569.0;
|
||||
/// Minimum live section width that can safely retain the exported wide-row geometry.
|
||||
///
|
||||
/// The Penpot reference section itself is 569 px wide. In the native Inspector, dock chrome,
|
||||
/// component-card borders, and the floating scrollbar consume up to ten pixels before the
|
||||
/// material parameter body is allocated. Treat that 559 px contained canvas as wide so a 640 px
|
||||
/// Inspector renders the authoritative wide reference instead of incorrectly switching to the
|
||||
/// 420 px two-line rows.
|
||||
pub(crate) const WIDE_SECTION_WIDTH: f32 = 559.0;
|
||||
pub(crate) const RESPONSIVE_BREAKPOINT: f32 = WIDE_SECTION_WIDTH;
|
||||
/// The actor component chrome can consume up to twelve pixels of the exported 372 px compact
|
||||
/// canvas. At 360 px the complete texture row still fits: 12 px inset + 336 px group + 12 px inset.
|
||||
@@ -20,6 +27,7 @@ pub(crate) struct PropertyRowRects {
|
||||
pub row: egui::Rect,
|
||||
pub label: egui::Rect,
|
||||
pub value: egui::Rect,
|
||||
pub color_value: egui::Rect,
|
||||
pub channel: egui::Rect,
|
||||
pub texture_group: egui::Rect,
|
||||
pub texture_field: egui::Rect,
|
||||
@@ -60,8 +68,12 @@ impl PropertyGridGeometry {
|
||||
egui::vec2(82.0, 22.0),
|
||||
),
|
||||
value: egui::Rect::from_min_size(
|
||||
row.min + egui::vec2(96.0, 5.0),
|
||||
egui::vec2(132.0, 22.0),
|
||||
row.min + egui::vec2(103.35, 5.0),
|
||||
egui::vec2(132.8, 22.0),
|
||||
),
|
||||
color_value: egui::Rect::from_min_size(
|
||||
row.min + egui::vec2(107.95, 5.0),
|
||||
egui::vec2(182.55, 22.0),
|
||||
),
|
||||
channel: egui::Rect::from_min_size(
|
||||
row.min + egui::vec2(234.0, 5.0),
|
||||
@@ -86,8 +98,10 @@ impl PropertyGridGeometry {
|
||||
|
||||
let channel_width = 48.0_f32.min(inner_width);
|
||||
let channel_x = inset + inner_width - channel_width;
|
||||
let value_x = (inset + 84.0).min(channel_x);
|
||||
let value_x = (inset + 91.35).min(channel_x);
|
||||
let value_width = (channel_x - value_x - 6.35).max(1.0);
|
||||
let color_value_x = (inset + 95.95).min(channel_x);
|
||||
let color_value_width = (inset + inner_width - color_value_x).max(1.0);
|
||||
let texture_group = egui::Rect::from_min_size(
|
||||
row.min + egui::vec2(inset, 31.0),
|
||||
egui::vec2(inner_width, 22.0),
|
||||
@@ -109,6 +123,10 @@ impl PropertyGridGeometry {
|
||||
row.min + egui::vec2(value_x, 5.0),
|
||||
egui::vec2(value_width, 22.0),
|
||||
),
|
||||
color_value: egui::Rect::from_min_size(
|
||||
row.min + egui::vec2(color_value_x, 5.0),
|
||||
egui::vec2(color_value_width, 22.0),
|
||||
),
|
||||
channel: egui::Rect::from_min_size(
|
||||
row.min + egui::vec2(channel_x, 5.0),
|
||||
egui::vec2(channel_width, 22.0),
|
||||
@@ -151,8 +169,15 @@ mod tests {
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn penpot_below_reference_width_reflows_without_compression() {
|
||||
let geometry = PropertyGridGeometry::for_width(568.0);
|
||||
fn native_wide_containment_threshold_keeps_reference_rows() {
|
||||
let geometry = PropertyGridGeometry::for_width(559.0);
|
||||
assert!(!geometry.stacked);
|
||||
assert_eq!(geometry.row_height, 32.0);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn below_native_wide_containment_threshold_reflows_without_compression() {
|
||||
let geometry = PropertyGridGeometry::for_width(558.0);
|
||||
assert!(geometry.stacked);
|
||||
assert_eq!(geometry.row_height, 58.0);
|
||||
}
|
||||
@@ -162,9 +187,11 @@ mod tests {
|
||||
let row = egui::Rect::from_min_size(egui::Pos2::ZERO, egui::vec2(569.0, 32.0));
|
||||
let rects = PropertyGridGeometry::for_width(569.0).row_rects(row);
|
||||
assert_eq!(rects.label.min, egui::pos2(12.0, 5.0));
|
||||
assert_eq!(rects.value.min, egui::pos2(96.0, 5.0));
|
||||
assert!((rects.value.width() - 132.0).abs() < 0.001);
|
||||
assert_eq!(rects.value.min, egui::pos2(103.35, 5.0));
|
||||
assert!((rects.value.width() - 132.8).abs() < 0.001);
|
||||
assert_eq!(rects.value.height(), 22.0);
|
||||
assert_eq!(rects.color_value.min, egui::pos2(107.95, 5.0));
|
||||
assert!((rects.color_value.width() - 182.55).abs() < 0.001);
|
||||
assert_eq!(
|
||||
rects.channel,
|
||||
egui::Rect::from_min_size(egui::pos2(234.0, 5.0), egui::vec2(48.0, 22.0))
|
||||
@@ -184,7 +211,10 @@ mod tests {
|
||||
let row = egui::Rect::from_min_size(egui::Pos2::ZERO, egui::vec2(369.0, 58.0));
|
||||
let rects = PropertyGridGeometry::for_width(369.0).row_rects(row);
|
||||
assert_eq!(rects.label.min, egui::pos2(12.0, 5.0));
|
||||
assert_eq!(rects.value.min, egui::pos2(96.0, 5.0));
|
||||
assert_eq!(rects.value.min, egui::pos2(103.35, 5.0));
|
||||
assert!((rects.value.width() - 199.3).abs() < 0.001);
|
||||
assert_eq!(rects.color_value.min, egui::pos2(107.95, 5.0));
|
||||
assert!((rects.color_value.width() - 249.05).abs() < 0.001);
|
||||
assert_eq!(
|
||||
rects.channel,
|
||||
egui::Rect::from_min_size(egui::pos2(309.0, 5.0), egui::vec2(48.0, 22.0))
|
||||
@@ -207,6 +237,7 @@ mod tests {
|
||||
for rect in [
|
||||
rects.label,
|
||||
rects.value,
|
||||
rects.color_value,
|
||||
rects.channel,
|
||||
rects.texture_group,
|
||||
rects.texture_field,
|
||||
@@ -239,6 +270,7 @@ mod tests {
|
||||
let wide = PropertyGridGeometry::for_width(669.0).row_rects(wide_row);
|
||||
assert_eq!(wide.label, reference.label);
|
||||
assert_eq!(wide.value, reference.value);
|
||||
assert_eq!(wide.color_value, reference.color_value);
|
||||
assert_eq!(wide.channel, reference.channel);
|
||||
assert_eq!(
|
||||
wide.texture_field.width(),
|
||||
|
||||
@@ -2,10 +2,6 @@
|
||||
|
||||
use bevy::prelude::*;
|
||||
use bevy_egui::{EguiContext, PrimaryEguiContext};
|
||||
use std::sync::Arc;
|
||||
|
||||
pub(crate) const SOURCE_SANS_REGULAR: &str = "blacksite-source-sans-regular";
|
||||
pub(crate) const SOURCE_SANS_BOLD: &str = "blacksite-source-sans-bold";
|
||||
|
||||
pub struct EditorFontsPlugin;
|
||||
|
||||
@@ -23,55 +19,5 @@ fn configure_editor_fonts(mut contexts: Query<&mut EguiContext, Added<PrimaryEgu
|
||||
}
|
||||
|
||||
pub(crate) fn editor_font_definitions() -> bevy_egui::egui::FontDefinitions {
|
||||
let mut fonts = bevy_egui::egui::FontDefinitions::default();
|
||||
egui_phosphor_icons::add_fonts(&mut fonts);
|
||||
|
||||
fonts.font_data.insert(
|
||||
SOURCE_SANS_REGULAR.to_owned(),
|
||||
Arc::new(bevy_egui::egui::FontData::from_static(include_bytes!(
|
||||
"../../assets/fonts/source-sans/SourceSansPro-Regular.ttf"
|
||||
))),
|
||||
);
|
||||
fonts.font_data.insert(
|
||||
SOURCE_SANS_BOLD.to_owned(),
|
||||
Arc::new(bevy_egui::egui::FontData::from_static(include_bytes!(
|
||||
"../../assets/fonts/source-sans/SourceSansPro-Bold.ttf"
|
||||
))),
|
||||
);
|
||||
|
||||
let proportional = fonts
|
||||
.families
|
||||
.entry(bevy_egui::egui::FontFamily::Proportional)
|
||||
.or_default();
|
||||
proportional.insert(0, SOURCE_SANS_REGULAR.to_owned());
|
||||
fonts.families.insert(
|
||||
bevy_egui::egui::FontFamily::Name(SOURCE_SANS_REGULAR.into()),
|
||||
vec![SOURCE_SANS_REGULAR.to_owned()],
|
||||
);
|
||||
fonts.families.insert(
|
||||
bevy_egui::egui::FontFamily::Name(SOURCE_SANS_BOLD.into()),
|
||||
vec![SOURCE_SANS_BOLD.to_owned(), SOURCE_SANS_REGULAR.to_owned()],
|
||||
);
|
||||
|
||||
// Phosphor families contain icon glyphs only. Text fallbacks give egui a
|
||||
// replacement glyph for malformed/missing icons without changing icon lookup.
|
||||
let text_fallbacks = fonts
|
||||
.families
|
||||
.get(&bevy_egui::egui::FontFamily::Proportional)
|
||||
.cloned()
|
||||
.unwrap_or_default();
|
||||
for (family, font_names) in &mut fonts.families {
|
||||
let bevy_egui::egui::FontFamily::Name(name) = family else {
|
||||
continue;
|
||||
};
|
||||
if !name.starts_with("phosphor-") {
|
||||
continue;
|
||||
}
|
||||
for fallback in &text_fallbacks {
|
||||
if !font_names.contains(fallback) {
|
||||
font_names.push(fallback.clone());
|
||||
}
|
||||
}
|
||||
}
|
||||
fonts
|
||||
editor_ui::fonts::font_definitions()
|
||||
}
|
||||
@@ -1,12 +1,5 @@
|
||||
use super::*;
|
||||
|
||||
const COMPONENT_HEADER_HEIGHT: f32 = 50.0;
|
||||
const COMPONENT_RAIL_X: f32 = 7.0;
|
||||
const COMPONENT_CARET_CENTER_X: f32 = 26.0;
|
||||
const COMPONENT_ICON_CENTER_X: f32 = 51.0;
|
||||
const COMPONENT_IDENTITY_X: f32 = 69.0;
|
||||
const COMPONENT_ACTIONS_WIDTH: f32 = 104.0;
|
||||
|
||||
pub(super) fn material_shader_ui(ui: &mut egui::Ui, material: &mut MaterialDesc) -> bool {
|
||||
let mut changed = false;
|
||||
property_row(ui, "Shader", |ui| {
|
||||
@@ -137,201 +130,41 @@ pub(crate) fn component_card(
|
||||
context: &ComponentCardContext,
|
||||
add_contents: impl FnOnce(&mut egui::Ui),
|
||||
) -> ComponentCardResponse {
|
||||
let mut response = ComponentCardResponse {
|
||||
let options = editor_ui::inspector::ComponentCardOptions {
|
||||
type_name: context.options.type_name,
|
||||
..Default::default()
|
||||
title: context.options.title,
|
||||
icon: context.options.icon,
|
||||
active_toggle: context.options.active_toggle,
|
||||
removable: context.options.removable,
|
||||
reorderable: context.options.reorderable,
|
||||
resettable: context.options.resettable,
|
||||
copyable: context.options.copyable,
|
||||
summary: context.options.summary,
|
||||
body_margin: context.options.body_margin,
|
||||
};
|
||||
crate::ui::design_system::scope(ui, |ui| {
|
||||
egui::Frame::new()
|
||||
.fill(WIDGET_BG)
|
||||
.stroke(egui::Stroke::new(1.0_f32, BORDER))
|
||||
.corner_radius(egui::CornerRadius::same(5))
|
||||
.show(ui, |ui| {
|
||||
let width = ui.available_width().max(1.0);
|
||||
let (header, header_response) = ui.allocate_exact_size(
|
||||
egui::vec2(width, COMPONENT_HEADER_HEIGHT),
|
||||
egui::Sense::click(),
|
||||
);
|
||||
ui.painter().rect_filled(
|
||||
egui::Rect::from_min_size(
|
||||
header.min + egui::vec2(COMPONENT_RAIL_X, 7.0),
|
||||
egui::vec2(3.0, 36.0),
|
||||
),
|
||||
2.0,
|
||||
crate::ui::theme::SELECTION,
|
||||
);
|
||||
let caret_rect = egui::Rect::from_center_size(
|
||||
egui::pos2(header.left() + COMPONENT_CARET_CENTER_X, header.center().y),
|
||||
egui::vec2(20.0, 28.0),
|
||||
);
|
||||
if ui
|
||||
.put(
|
||||
caret_rect,
|
||||
egui::Button::new(phosphor_icon(
|
||||
if context.collapsed {
|
||||
icons::CARET_RIGHT
|
||||
} else {
|
||||
icons::CARET_DOWN
|
||||
},
|
||||
12.0,
|
||||
))
|
||||
.frame(false),
|
||||
)
|
||||
.on_hover_text(if context.collapsed {
|
||||
"Expand component"
|
||||
} else {
|
||||
"Collapse component"
|
||||
})
|
||||
.clicked()
|
||||
{
|
||||
response.collapsed = Some(!context.collapsed);
|
||||
}
|
||||
ui.painter().text(
|
||||
egui::pos2(header.left() + COMPONENT_ICON_CENTER_X, header.center().y),
|
||||
egui::Align2::CENTER_CENTER,
|
||||
context.options.icon.as_str(),
|
||||
egui::FontId::new(18.0, egui::FontFamily::Name("phosphor-regular".into())),
|
||||
TEXT_DIM,
|
||||
);
|
||||
ui.painter().text(
|
||||
egui::pos2(header.left() + COMPONENT_IDENTITY_X, header.top() + 18.0),
|
||||
egui::Align2::LEFT_CENTER,
|
||||
context.options.title,
|
||||
crate::ui::design_system::typography::TypeRole::Title.font(),
|
||||
crate::ui::theme::TEXT,
|
||||
);
|
||||
ui.painter().text(
|
||||
egui::pos2(header.left() + COMPONENT_IDENTITY_X, header.top() + 34.0),
|
||||
egui::Align2::LEFT_CENTER,
|
||||
context.options.summary,
|
||||
crate::ui::design_system::typography::TypeRole::Small.font(),
|
||||
TEXT_MUTED,
|
||||
);
|
||||
let actions_rect = egui::Rect::from_min_size(
|
||||
egui::pos2(
|
||||
header.right() - COMPONENT_ACTIONS_WIDTH - 8.0,
|
||||
header.top() + 11.0,
|
||||
),
|
||||
egui::vec2(COMPONENT_ACTIONS_WIDTH, 28.0),
|
||||
);
|
||||
ui.scope_builder(egui::UiBuilder::new().max_rect(actions_rect), |ui| {
|
||||
ui.with_layout(egui::Layout::right_to_left(egui::Align::Center), |ui| {
|
||||
component_actions_menu(ui, context, &mut response);
|
||||
let label = if context.active { "Active" } else { "Off" };
|
||||
let color = if context.active {
|
||||
crate::ui::theme::SUCCESS
|
||||
} else {
|
||||
TEXT_MUTED
|
||||
};
|
||||
let active = ui
|
||||
.horizontal(|ui| {
|
||||
let dot = if context.options.active_toggle {
|
||||
status_dot_button(ui, color, "Toggle component")
|
||||
} else {
|
||||
status_dot(ui, color, "Component active");
|
||||
ui.allocate_response(egui::Vec2::ZERO, egui::Sense::hover())
|
||||
};
|
||||
ui.label(
|
||||
crate::ui::design_system::typography::TypeRole::Small
|
||||
.text(label)
|
||||
.color(TEXT_DIM),
|
||||
);
|
||||
dot
|
||||
})
|
||||
.inner;
|
||||
if context.options.active_toggle && active.clicked() {
|
||||
response.active = Some(!context.active);
|
||||
}
|
||||
});
|
||||
});
|
||||
if header_response.clicked()
|
||||
&& ui
|
||||
.input(|input| input.pointer.interact_pos())
|
||||
.is_some_and(|pointer| {
|
||||
!caret_rect.contains(pointer) && !actions_rect.contains(pointer)
|
||||
})
|
||||
{
|
||||
response.collapsed = Some(!context.collapsed);
|
||||
}
|
||||
if !context.collapsed {
|
||||
egui::Frame::new()
|
||||
.inner_margin(egui::Margin {
|
||||
left: context.options.body_margin,
|
||||
right: context.options.body_margin,
|
||||
top: 10,
|
||||
bottom: context.options.body_margin,
|
||||
})
|
||||
.show(ui, |ui| {
|
||||
ui.set_max_width(ui.available_width());
|
||||
add_contents(ui);
|
||||
});
|
||||
}
|
||||
});
|
||||
});
|
||||
ui.add_space(6.0);
|
||||
response
|
||||
}
|
||||
|
||||
fn component_actions_menu(
|
||||
ui: &mut egui::Ui,
|
||||
context: &ComponentCardContext,
|
||||
response: &mut ComponentCardResponse,
|
||||
) {
|
||||
let menu = ui.menu_button(
|
||||
phosphor_icon(icons::DOTS_THREE_VERTICAL, 16.0).color(TEXT_DIM),
|
||||
|ui| {
|
||||
ui.set_min_width(160.0);
|
||||
if ui
|
||||
.add_enabled(context.options.resettable, egui::Button::new("Reset"))
|
||||
.clicked()
|
||||
{
|
||||
response.reset = true;
|
||||
ui.close();
|
||||
}
|
||||
if ui
|
||||
.add_enabled(context.options.copyable, egui::Button::new("Copy Values"))
|
||||
.clicked()
|
||||
{
|
||||
response.copy = true;
|
||||
ui.close();
|
||||
}
|
||||
if ui
|
||||
.add_enabled(context.pasteable, egui::Button::new("Paste Values"))
|
||||
.clicked()
|
||||
{
|
||||
response.paste = true;
|
||||
ui.close();
|
||||
}
|
||||
ui.separator();
|
||||
if ui
|
||||
.add_enabled(context.can_move_up, egui::Button::new("Move Up"))
|
||||
.clicked()
|
||||
{
|
||||
response.move_up = true;
|
||||
ui.close();
|
||||
}
|
||||
if ui
|
||||
.add_enabled(context.can_move_down, egui::Button::new("Move Down"))
|
||||
.clicked()
|
||||
{
|
||||
response.move_down = true;
|
||||
ui.close();
|
||||
}
|
||||
ui.separator();
|
||||
ui.add_enabled(false, egui::Button::new("Open Documentation"));
|
||||
if ui
|
||||
.add_enabled(
|
||||
context.options.removable,
|
||||
egui::Button::new(egui::RichText::new("Remove").color(crate::ui::theme::ERROR)),
|
||||
)
|
||||
.clicked()
|
||||
{
|
||||
response.remove = true;
|
||||
ui.close();
|
||||
}
|
||||
let shared = editor_ui::inspector::component_card(
|
||||
ui,
|
||||
&editor_ui::inspector::ComponentCardViewModel {
|
||||
options,
|
||||
active: context.active,
|
||||
collapsed: context.collapsed,
|
||||
pasteable: context.pasteable,
|
||||
can_move_up: context.can_move_up,
|
||||
can_move_down: context.can_move_down,
|
||||
},
|
||||
add_contents,
|
||||
);
|
||||
menu.response.on_hover_text("Component actions");
|
||||
ComponentCardResponse {
|
||||
type_name: shared.type_name,
|
||||
collapsed: shared.collapsed,
|
||||
active: shared.active,
|
||||
reset: shared.reset,
|
||||
copy: shared.copy,
|
||||
paste: shared.paste,
|
||||
move_up: shared.move_up,
|
||||
move_down: shared.move_down,
|
||||
remove: shared.remove,
|
||||
}
|
||||
}
|
||||
|
||||
pub(crate) fn property_row<R>(
|
||||
@@ -501,18 +334,3 @@ pub fn material_editor_ui(world: &mut World, ui: &mut egui::Ui, entity: Entity)
|
||||
set_material_with_history(world, entity, material);
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod component_header_geometry_tests {
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn current_penpot_inspector_header_geometry_is_exact() {
|
||||
assert_eq!(COMPONENT_HEADER_HEIGHT, 50.0);
|
||||
assert_eq!(COMPONENT_RAIL_X, 7.0);
|
||||
assert_eq!(COMPONENT_CARET_CENTER_X, 26.0);
|
||||
assert_eq!(COMPONENT_ICON_CENTER_X, 51.0);
|
||||
assert_eq!(COMPONENT_IDENTITY_X, 69.0);
|
||||
assert_eq!(COMPONENT_ACTIONS_WIDTH, 104.0);
|
||||
}
|
||||
}
|
||||
@@ -10,27 +10,6 @@ pub(super) fn ensure_slot_id(entry: &mut StaticMeshRendererEntry, index: usize)
|
||||
}
|
||||
}
|
||||
|
||||
pub(super) fn status_dot(ui: &mut egui::Ui, color: egui::Color32, tooltip: &str) {
|
||||
let (rect, response) = ui.allocate_exact_size(egui::vec2(18.0, 20.0), egui::Sense::hover());
|
||||
ui.painter().circle_filled(rect.center(), 4.0, color);
|
||||
response.on_hover_text(tooltip);
|
||||
}
|
||||
|
||||
pub(super) fn status_dot_button(
|
||||
ui: &mut egui::Ui,
|
||||
color: egui::Color32,
|
||||
tooltip: &str,
|
||||
) -> egui::Response {
|
||||
let (rect, response) = ui.allocate_exact_size(egui::vec2(18.0, 20.0), egui::Sense::click());
|
||||
let color = if response.hovered() {
|
||||
color.linear_multiply(1.2)
|
||||
} else {
|
||||
color
|
||||
};
|
||||
ui.painter().circle_filled(rect.center(), 4.0, color);
|
||||
response.on_hover_text(tooltip)
|
||||
}
|
||||
|
||||
pub(super) fn material_drop_invalid_reason(
|
||||
world: &World,
|
||||
valid_material_candidate: bool,
|
||||
@@ -62,15 +41,26 @@ pub(super) struct MaterialSlotWidgetResponse {
|
||||
pub(super) accepted_drop: bool,
|
||||
}
|
||||
|
||||
pub(super) struct MaterialSlotWidgetContext<'a> {
|
||||
pub(super) candidates: &'a [AssetRefCandidate],
|
||||
pub(super) drop_candidate: Option<&'a AssetRefCandidate>,
|
||||
pub(super) invalid_drop_reason: Option<&'static str>,
|
||||
pub(super) expanded_header_when_parameters_closed: bool,
|
||||
}
|
||||
|
||||
pub(super) fn material_slot_widget_ui(
|
||||
world: &mut World,
|
||||
ui: &mut egui::Ui,
|
||||
entity: Entity,
|
||||
slot: &mut shared::MaterialSlot,
|
||||
candidates: &[AssetRefCandidate],
|
||||
drop_candidate: Option<&AssetRefCandidate>,
|
||||
invalid_drop_reason: Option<&'static str>,
|
||||
context: MaterialSlotWidgetContext<'_>,
|
||||
) -> MaterialSlotWidgetResponse {
|
||||
let MaterialSlotWidgetContext {
|
||||
candidates,
|
||||
drop_candidate,
|
||||
invalid_drop_reason,
|
||||
expanded_header_when_parameters_closed,
|
||||
} = context;
|
||||
let mut response = MaterialSlotWidgetResponse::default();
|
||||
let actor_widget_id = stable_actor_widget_id(world, entity);
|
||||
let project_default = world
|
||||
@@ -165,6 +155,8 @@ pub(super) fn material_slot_widget_ui(
|
||||
crate::ui::materials::MaterialThumbnailPresentation::Failed
|
||||
} else if let Some(texture) = texture_id {
|
||||
crate::ui::materials::MaterialThumbnailPresentation::Ready(texture)
|
||||
} else if effective.is_none() {
|
||||
crate::ui::materials::MaterialThumbnailPresentation::Empty
|
||||
} else {
|
||||
crate::ui::materials::MaterialThumbnailPresentation::Pending
|
||||
};
|
||||
@@ -227,6 +219,8 @@ pub(super) fn material_slot_widget_ui(
|
||||
can_clear: slot.material.is_some(),
|
||||
can_extract: is_imported_source,
|
||||
can_create_instance: is_project_material,
|
||||
parameters_initially_open: true,
|
||||
expanded_header_when_parameters_closed,
|
||||
};
|
||||
|
||||
let widget_slot_id = slot.id.0.clone();
|
||||
|
||||
@@ -81,9 +81,12 @@ pub(super) fn skinned_mesh_renderer_ui(world: &mut World, ui: &mut egui::Ui, ent
|
||||
ui,
|
||||
entity,
|
||||
slot,
|
||||
&material_candidates,
|
||||
material_drop_candidate.as_ref(),
|
||||
invalid_material_drop,
|
||||
MaterialSlotWidgetContext {
|
||||
candidates: &material_candidates,
|
||||
drop_candidate: material_drop_candidate.as_ref(),
|
||||
invalid_drop_reason: invalid_material_drop,
|
||||
expanded_header_when_parameters_closed: true,
|
||||
},
|
||||
);
|
||||
changed |= widget.changed;
|
||||
accepted_drop |= widget.accepted_drop;
|
||||
@@ -172,7 +175,7 @@ pub(super) fn static_mesh_renderer_ui(world: &mut World, ui: &mut egui::Ui, enti
|
||||
let card = component_card_context(world, entity, options);
|
||||
let card_response = component_card(ui, &card, |ui| {
|
||||
let add_slot = renderer_array_header(ui, renderer.slots.len());
|
||||
ui.add_space(10.0);
|
||||
ui.add_space(26.0);
|
||||
if renderer.slots.is_empty() {
|
||||
ui.label(egui::RichText::new("No renderer slots").color(TEXT_DIM));
|
||||
}
|
||||
@@ -190,65 +193,97 @@ pub(super) fn static_mesh_renderer_ui(world: &mut World, ui: &mut egui::Ui, enti
|
||||
renderer_panel(ui, |ui| {
|
||||
renderer_panel_header(
|
||||
ui,
|
||||
index,
|
||||
&entry.name,
|
||||
thumbnail,
|
||||
RendererPanelHeaderViewModel {
|
||||
index,
|
||||
label: &entry.name,
|
||||
path: entry
|
||||
.mesh
|
||||
.source_path
|
||||
.as_deref()
|
||||
.unwrap_or(&entry.mesh.sub_asset_id),
|
||||
slot_count: 1,
|
||||
texture_id: thumbnail,
|
||||
},
|
||||
&mut renderer_open,
|
||||
|ui| {
|
||||
status_dot(ui, egui::Color32::from_rgb(74, 181, 104), "Slot active");
|
||||
if icon_button_small(ui, icons::TRASH, "Remove slot").clicked() {
|
||||
editor_ui::design_system::controls::icon_button(
|
||||
ui,
|
||||
icons::DOTS_THREE_VERTICAL,
|
||||
"Renderer actions",
|
||||
true,
|
||||
);
|
||||
if editor_ui::design_system::controls::icon_button(
|
||||
ui,
|
||||
icons::TRASH,
|
||||
"Remove slot",
|
||||
true,
|
||||
)
|
||||
.clicked()
|
||||
{
|
||||
remove_entry = Some(index);
|
||||
}
|
||||
ui.label(phosphor_icon(icons::DOTS_THREE_VERTICAL, 16.0).color(TEXT_DIM));
|
||||
editor_ui::design_system::controls::icon_button(
|
||||
ui,
|
||||
icons::CROSSHAIR,
|
||||
"Locate mesh",
|
||||
true,
|
||||
);
|
||||
editor_ui::design_system::controls::icon_button(
|
||||
ui,
|
||||
icons::FOLDER_OPEN,
|
||||
"Browse mesh",
|
||||
true,
|
||||
);
|
||||
},
|
||||
);
|
||||
if !renderer_open {
|
||||
return;
|
||||
}
|
||||
let mut draw_fields = |ui: &mut egui::Ui, entry: &mut StaticMeshRendererEntry| {
|
||||
renderer_properties_header(ui);
|
||||
property_row(ui, "Name", |ui| {
|
||||
changed |= ui
|
||||
.add_sized(
|
||||
[text_field_width(ui), 20.0],
|
||||
egui::TextEdit::singleline(&mut entry.name),
|
||||
)
|
||||
.changed();
|
||||
});
|
||||
let mesh_response = asset_selector_row(
|
||||
ui,
|
||||
"Mesh",
|
||||
icons::CUBE,
|
||||
Some(&entry.mesh),
|
||||
None,
|
||||
false,
|
||||
&mesh_candidates,
|
||||
None,
|
||||
None,
|
||||
AssetSelectorActions::Full,
|
||||
);
|
||||
if let Some(selected) = mesh_response.selected {
|
||||
entry.mesh = selected;
|
||||
changed = true;
|
||||
}
|
||||
if mesh_response.locate {
|
||||
locate_asset_ref(world, Some(&entry.mesh), &mesh_candidates);
|
||||
}
|
||||
|
||||
ui.horizontal_wrapped(|ui| {
|
||||
changed |= ui.checkbox(&mut entry.visible, "Visible").changed();
|
||||
changed |= ui
|
||||
.checkbox(&mut entry.cast_shadows, "Cast shadows")
|
||||
.changed();
|
||||
changed |= ui
|
||||
.checkbox(&mut entry.receive_shadows, "Receive shadows")
|
||||
.changed();
|
||||
});
|
||||
};
|
||||
|
||||
egui::Frame::new()
|
||||
.inner_margin(egui::Margin::symmetric(12, 10))
|
||||
.show(ui, |ui| draw_fields(ui, entry));
|
||||
.show(ui, |ui| {
|
||||
renderer_properties_header(ui);
|
||||
ui.add_space(2.0);
|
||||
property_row(ui, "Name", |ui| {
|
||||
changed |= ui
|
||||
.add_sized(
|
||||
[text_field_width(ui), 20.0],
|
||||
egui::TextEdit::singleline(&mut entry.name),
|
||||
)
|
||||
.changed();
|
||||
});
|
||||
ui.add_space(4.0);
|
||||
let mesh_response = asset_selector_row(
|
||||
ui,
|
||||
"Mesh",
|
||||
icons::CUBE,
|
||||
Some(&entry.mesh),
|
||||
None,
|
||||
false,
|
||||
&mesh_candidates,
|
||||
None,
|
||||
None,
|
||||
AssetSelectorActions::Full,
|
||||
);
|
||||
if let Some(selected) = mesh_response.selected {
|
||||
entry.mesh = selected;
|
||||
changed = true;
|
||||
}
|
||||
if mesh_response.locate {
|
||||
locate_asset_ref(world, Some(&entry.mesh), &mesh_candidates);
|
||||
}
|
||||
ui.add_space(4.0);
|
||||
ui.horizontal_wrapped(|ui| {
|
||||
changed |= ui.checkbox(&mut entry.visible, "Visible").changed();
|
||||
changed |= ui
|
||||
.checkbox(&mut entry.cast_shadows, "Cast shadows")
|
||||
.changed();
|
||||
changed |= ui
|
||||
.checkbox(&mut entry.receive_shadows, "Receive shadows")
|
||||
.changed();
|
||||
});
|
||||
ui.add_space(4.0);
|
||||
});
|
||||
renderer_material_slots_header(ui, 1);
|
||||
if let Some(slot) = material_set.slot_mut(&entry.material_slot_id) {
|
||||
let widget = renderer_material_slot_row(ui, index, |ui| {
|
||||
@@ -257,9 +292,12 @@ pub(super) fn static_mesh_renderer_ui(world: &mut World, ui: &mut egui::Ui, enti
|
||||
ui,
|
||||
entity,
|
||||
slot,
|
||||
&material_candidates,
|
||||
material_drop_candidate.as_ref(),
|
||||
invalid_material_drop,
|
||||
MaterialSlotWidgetContext {
|
||||
candidates: &material_candidates,
|
||||
drop_candidate: material_drop_candidate.as_ref(),
|
||||
invalid_drop_reason: invalid_material_drop,
|
||||
expanded_header_when_parameters_closed: true,
|
||||
},
|
||||
)
|
||||
});
|
||||
changed |= widget.changed;
|
||||
@@ -317,109 +355,3 @@ pub(super) fn static_mesh_renderer_ui(world: &mut World, ui: &mut egui::Ui, enti
|
||||
set_static_mesh_renderer_with_history(world, entity, renderer);
|
||||
}
|
||||
}
|
||||
|
||||
fn renderer_array_header(ui: &mut egui::Ui, count: usize) -> bool {
|
||||
let palette = crate::ui::design_system::palette(ui);
|
||||
let (rect, _) = ui.allocate_exact_size(
|
||||
egui::vec2(ui.available_width().max(1.0), 40.0),
|
||||
egui::Sense::hover(),
|
||||
);
|
||||
ui.painter().rect_filled(rect, 4.0, palette.elevated);
|
||||
ui.painter().text(
|
||||
rect.left_center() + egui::vec2(12.0, 0.0),
|
||||
egui::Align2::LEFT_CENTER,
|
||||
icons::SQUARES_FOUR.as_str(),
|
||||
egui::FontId::new(16.0, egui::FontFamily::Name("phosphor-regular".into())),
|
||||
palette.text_secondary,
|
||||
);
|
||||
ui.painter().text(
|
||||
rect.left_center() + egui::vec2(36.0, 0.0),
|
||||
egui::Align2::LEFT_CENTER,
|
||||
"Mesh renderers",
|
||||
crate::ui::design_system::typography::TypeRole::Section.font(),
|
||||
palette.text_primary,
|
||||
);
|
||||
ui.painter().text(
|
||||
rect.left_center() + egui::vec2(132.0, 0.0),
|
||||
egui::Align2::LEFT_CENTER,
|
||||
format!("{count}"),
|
||||
crate::ui::design_system::typography::TypeRole::Small.font(),
|
||||
palette.text_muted,
|
||||
);
|
||||
let add_rect = egui::Rect::from_min_size(
|
||||
egui::pos2(rect.right() - 116.0, rect.top() + 7.0),
|
||||
egui::vec2(104.0, 26.0),
|
||||
);
|
||||
ui.put(
|
||||
add_rect,
|
||||
egui::Button::new(crate::ui::design_system::controls::icon_label(
|
||||
icons::PLUS,
|
||||
"Add renderer",
|
||||
crate::ui::design_system::typography::TypeRole::Body,
|
||||
12.0,
|
||||
palette.text_primary,
|
||||
)),
|
||||
)
|
||||
.clicked()
|
||||
}
|
||||
|
||||
fn renderer_material_slots_header(ui: &mut egui::Ui, count: usize) {
|
||||
let palette = crate::ui::design_system::palette(ui);
|
||||
let (rect, _) = ui.allocate_exact_size(
|
||||
egui::vec2(ui.available_width().max(1.0), 38.0),
|
||||
egui::Sense::hover(),
|
||||
);
|
||||
ui.painter().text(
|
||||
rect.left_center() + egui::vec2(10.0, 0.0),
|
||||
egui::Align2::LEFT_CENTER,
|
||||
"Material slots",
|
||||
crate::ui::design_system::typography::TypeRole::Section.font(),
|
||||
palette.text_primary,
|
||||
);
|
||||
ui.painter().text(
|
||||
rect.right_center() - egui::vec2(10.0, 0.0),
|
||||
egui::Align2::RIGHT_CENTER,
|
||||
format!("{count}"),
|
||||
crate::ui::design_system::typography::TypeRole::Small.font(),
|
||||
palette.text_muted,
|
||||
);
|
||||
}
|
||||
|
||||
fn renderer_properties_header(ui: &mut egui::Ui) {
|
||||
let palette = crate::ui::design_system::palette(ui);
|
||||
let (rect, _) = ui.allocate_exact_size(
|
||||
egui::vec2(ui.available_width().max(1.0), 18.0),
|
||||
egui::Sense::hover(),
|
||||
);
|
||||
ui.painter().text(
|
||||
rect.left_center(),
|
||||
egui::Align2::LEFT_CENTER,
|
||||
"Renderer properties",
|
||||
crate::ui::design_system::typography::TypeRole::Caption.font(),
|
||||
palette.text_muted,
|
||||
);
|
||||
}
|
||||
|
||||
fn renderer_material_slot_row<R>(
|
||||
ui: &mut egui::Ui,
|
||||
index: usize,
|
||||
add_contents: impl FnOnce(&mut egui::Ui) -> R,
|
||||
) -> R {
|
||||
let palette = crate::ui::design_system::palette(ui);
|
||||
ui.horizontal_top(|ui| {
|
||||
let (index_rect, _) = ui.allocate_exact_size(egui::vec2(31.0, 60.0), egui::Sense::hover());
|
||||
ui.painter().text(
|
||||
index_rect.center_top() + egui::vec2(0.0, 18.0),
|
||||
egui::Align2::CENTER_CENTER,
|
||||
index.to_string(),
|
||||
crate::ui::design_system::typography::TypeRole::Body.font(),
|
||||
palette.text_muted,
|
||||
);
|
||||
ui.vertical(|ui| {
|
||||
ui.set_width(ui.available_width().max(1.0));
|
||||
add_contents(ui)
|
||||
})
|
||||
.inner
|
||||
})
|
||||
.inner
|
||||
}
|
||||
@@ -65,9 +65,12 @@ pub(super) fn primitive_editor_ui(world: &mut World, ui: &mut egui::Ui, entity:
|
||||
ui,
|
||||
entity,
|
||||
&mut primitive.surface,
|
||||
&material_candidates,
|
||||
material_drop_candidate.as_ref(),
|
||||
invalid_material_drop,
|
||||
MaterialSlotWidgetContext {
|
||||
candidates: &material_candidates,
|
||||
drop_candidate: material_drop_candidate.as_ref(),
|
||||
invalid_drop_reason: invalid_material_drop,
|
||||
expanded_header_when_parameters_closed: false,
|
||||
},
|
||||
)
|
||||
});
|
||||
changed |= widget.changed;
|
||||
|
||||
@@ -1,124 +1,5 @@
|
||||
//! Penpot renderer-panel chrome shared by static renderer entries.
|
||||
|
||||
use super::*;
|
||||
|
||||
const EXPANDED_RENDERER_HEADER_HEIGHT: f32 = 84.0;
|
||||
const COLLAPSED_RENDERER_HEADER_HEIGHT: f32 = 58.0;
|
||||
|
||||
pub(super) fn renderer_panel(ui: &mut egui::Ui, add_contents: impl FnOnce(&mut egui::Ui)) {
|
||||
egui::Frame::new()
|
||||
.fill(WIDGET_BG.linear_multiply(0.82))
|
||||
.stroke(egui::Stroke::new(1.0_f32, BORDER))
|
||||
.corner_radius(egui::CornerRadius::same(5))
|
||||
.show(ui, |ui| {
|
||||
ui.set_max_width(ui.available_width());
|
||||
add_contents(ui);
|
||||
});
|
||||
ui.add_space(10.0);
|
||||
}
|
||||
|
||||
pub(super) fn renderer_panel_header(
|
||||
ui: &mut egui::Ui,
|
||||
index: usize,
|
||||
slot_name: &str,
|
||||
texture_id: Option<egui::TextureId>,
|
||||
open: &mut bool,
|
||||
add_actions: impl FnOnce(&mut egui::Ui),
|
||||
) {
|
||||
let palette = crate::ui::design_system::palette(ui);
|
||||
let height = if *open {
|
||||
EXPANDED_RENDERER_HEADER_HEIGHT
|
||||
} else {
|
||||
COLLAPSED_RENDERER_HEADER_HEIGHT
|
||||
};
|
||||
let (rect, header_response) = ui.allocate_exact_size(
|
||||
egui::vec2(ui.available_width().max(1.0), height),
|
||||
egui::Sense::click(),
|
||||
);
|
||||
ui.painter().rect_filled(
|
||||
egui::Rect::from_min_size(
|
||||
rect.min + egui::vec2(6.0, 8.0),
|
||||
egui::vec2(3.0, height - 16.0),
|
||||
),
|
||||
2.0,
|
||||
palette.accent,
|
||||
);
|
||||
ui.painter().text(
|
||||
rect.left_center() + egui::vec2(20.0, 0.0),
|
||||
egui::Align2::CENTER_CENTER,
|
||||
if *open {
|
||||
icons::CARET_DOWN.as_str()
|
||||
} else {
|
||||
icons::CARET_RIGHT.as_str()
|
||||
},
|
||||
egui::FontId::new(12.0, egui::FontFamily::Name("phosphor-regular".into())),
|
||||
palette.text_secondary,
|
||||
);
|
||||
let preview_size = if *open { 58.0 } else { 40.0 };
|
||||
let preview = egui::Rect::from_center_size(
|
||||
egui::pos2(rect.left() + 63.0, rect.center().y),
|
||||
egui::vec2(preview_size, preview_size),
|
||||
);
|
||||
ui.painter().rect(
|
||||
preview,
|
||||
4.0,
|
||||
PANEL_BG_DARK,
|
||||
egui::Stroke::new(1.0_f32, BORDER),
|
||||
egui::StrokeKind::Inside,
|
||||
);
|
||||
if let Some(texture_id) = texture_id {
|
||||
ui.painter().image(
|
||||
texture_id,
|
||||
preview.shrink(3.0),
|
||||
egui::Rect::from_min_max(egui::Pos2::ZERO, egui::pos2(1.0, 1.0)),
|
||||
egui::Color32::WHITE,
|
||||
);
|
||||
}
|
||||
let label = if slot_name.trim().is_empty() {
|
||||
"Mesh renderer"
|
||||
} else {
|
||||
slot_name.trim()
|
||||
};
|
||||
ui.painter().text(
|
||||
egui::pos2(rect.left() + 104.0, rect.center().y - 8.0),
|
||||
egui::Align2::LEFT_CENTER,
|
||||
label,
|
||||
crate::ui::design_system::typography::TypeRole::Title.font(),
|
||||
palette.text_primary,
|
||||
);
|
||||
ui.painter().text(
|
||||
egui::pos2(rect.left() + 104.0, rect.center().y + 10.0),
|
||||
egui::Align2::LEFT_CENTER,
|
||||
format!("Renderer {index}"),
|
||||
crate::ui::design_system::typography::TypeRole::Small.font(),
|
||||
palette.text_muted,
|
||||
);
|
||||
let action_rect = egui::Rect::from_min_size(
|
||||
egui::pos2(rect.right() - 150.0, rect.center().y - 14.0),
|
||||
egui::vec2(140.0, 28.0),
|
||||
);
|
||||
ui.scope_builder(egui::UiBuilder::new().max_rect(action_rect), |ui| {
|
||||
ui.with_layout(
|
||||
egui::Layout::right_to_left(egui::Align::Center),
|
||||
add_actions,
|
||||
);
|
||||
});
|
||||
if header_response.clicked()
|
||||
&& ui
|
||||
.input(|input| input.pointer.interact_pos())
|
||||
.is_some_and(|pointer| !preview.contains(pointer) && !action_rect.contains(pointer))
|
||||
{
|
||||
*open = !*open;
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn renderer_headers_match_current_penpot_heights() {
|
||||
assert_eq!(EXPANDED_RENDERER_HEADER_HEIGHT, 84.0);
|
||||
assert_eq!(COLLAPSED_RENDERER_HEADER_HEIGHT, 58.0);
|
||||
}
|
||||
}
|
||||
pub(super) use editor_ui::renderer::{
|
||||
renderer_array_header, renderer_material_slot_row, renderer_material_slots_header,
|
||||
renderer_panel, renderer_panel_header, renderer_properties_header,
|
||||
RendererPanelHeaderViewModel,
|
||||
};
|
||||
@@ -55,7 +55,7 @@ pub(super) fn unsupported_advanced_preview(ui: &mut egui::Ui) {
|
||||
} else {
|
||||
icons::CARET_RIGHT.as_str()
|
||||
},
|
||||
egui::FontId::new(10.0, egui::FontFamily::Name("phosphor-regular".into())),
|
||||
egui::FontId::new(10.0, egui::FontFamily::Name("phosphor-bold".into())),
|
||||
palette.text_secondary,
|
||||
);
|
||||
ui.painter().text(
|
||||
|
||||
@@ -23,7 +23,7 @@ pub(crate) fn material_asset_editor(
|
||||
.and_then(|selection| {
|
||||
texture_assets
|
||||
.iter()
|
||||
.find(|candidate| candidate.selection == *selection)
|
||||
.find(|candidate| material_locate_matches_selection(&candidate.locate, selection))
|
||||
})
|
||||
.cloned();
|
||||
let original = draft_asset.clone();
|
||||
@@ -53,7 +53,7 @@ pub(crate) fn material_asset_editor(
|
||||
&mut draft_asset.render_state,
|
||||
Some(&mut draft_asset.inputs),
|
||||
);
|
||||
ui.add_space(8.0);
|
||||
ui.add_space(4.0);
|
||||
let input_response = material_input_schema_editor(
|
||||
ui,
|
||||
&input_schema,
|
||||
@@ -62,8 +62,10 @@ pub(crate) fn material_asset_editor(
|
||||
texture_drop_candidate.as_ref(),
|
||||
);
|
||||
accepted_texture_drop |= input_response.accepted_drop;
|
||||
if let Some(selection) = input_response.locate {
|
||||
world.resource_mut::<EditorAssets>().select(selection);
|
||||
if let Some(target) = input_response.locate {
|
||||
world
|
||||
.resource_mut::<EditorAssets>()
|
||||
.select(material_locate_selection(target));
|
||||
crate::ui::request_editor_tab(world, crate::ui::EditorTab::AssetBrowser);
|
||||
}
|
||||
if input_response.browse_library {
|
||||
@@ -112,117 +114,3 @@ fn material_source_diagnostics_ui(ui: &mut egui::Ui, provenance: &shared::Materi
|
||||
});
|
||||
ui.small("Reimport comparison never overwrites an edited project material automatically.");
|
||||
}
|
||||
|
||||
pub(super) fn material_surface_options_ui(
|
||||
ui: &mut egui::Ui,
|
||||
state: &mut shared::MaterialRenderState,
|
||||
packed_inputs: Option<&mut shared::MaterialInputSet>,
|
||||
) {
|
||||
let palette = crate::ui::design_system::palette(ui);
|
||||
let width = ui.available_width().max(1.0);
|
||||
let height = match super::layout::ResponsiveMaterialLayout::for_width(width) {
|
||||
super::layout::ResponsiveMaterialLayout::Reference => {
|
||||
crate::ui::design_system::SURFACE_SECTION_HEIGHT
|
||||
}
|
||||
super::layout::ResponsiveMaterialLayout::Compact => {
|
||||
crate::ui::design_system::COMPACT_SURFACE_SECTION_HEIGHT
|
||||
}
|
||||
super::layout::ResponsiveMaterialLayout::Transient => 100.0,
|
||||
};
|
||||
let (rect, _) = ui.allocate_exact_size(egui::vec2(width, height), egui::Sense::hover());
|
||||
ui.painter().rect(
|
||||
rect,
|
||||
5.0,
|
||||
palette.section,
|
||||
egui::Stroke::new(1.0_f32, palette.border),
|
||||
egui::StrokeKind::Inside,
|
||||
);
|
||||
let geometry = super::layout::SurfaceSectionGeometry::for_rect(rect);
|
||||
ui.painter().text(
|
||||
geometry.title.left_center(),
|
||||
egui::Align2::LEFT_CENTER,
|
||||
"Surface",
|
||||
crate::ui::design_system::typography::TypeRole::Section.font(),
|
||||
palette.text_primary,
|
||||
);
|
||||
clipped_rect_ui(ui, geometry.blend, |ui| {
|
||||
surface_blend_controls(ui, state);
|
||||
});
|
||||
if let Some(inputs) = packed_inputs {
|
||||
clipped_rect_ui(ui, geometry.packed, |ui| {
|
||||
packed_mode_controls(ui, inputs);
|
||||
});
|
||||
}
|
||||
ui.painter().text(
|
||||
geometry.double_sided.left_center() + egui::vec2(7.0, 0.0),
|
||||
egui::Align2::LEFT_CENTER,
|
||||
"Double Sided",
|
||||
crate::ui::design_system::typography::TypeRole::Body.font(),
|
||||
palette.text_secondary,
|
||||
);
|
||||
let switch_rect = egui::Rect::from_min_size(
|
||||
geometry.double_sided.min + egui::vec2(76.0, 3.0),
|
||||
egui::vec2(31.0, 16.0),
|
||||
);
|
||||
clipped_rect_ui(ui, switch_rect, |ui| {
|
||||
crate::ui::design_system::controls::switch(ui, &mut state.double_sided)
|
||||
.on_hover_text("Render both sides of the surface");
|
||||
});
|
||||
}
|
||||
|
||||
fn packed_mode_controls(ui: &mut egui::Ui, inputs: &mut shared::MaterialInputSet) {
|
||||
let arm = super::inputs::packed_map_mode(inputs) == super::inputs::PackedMapMode::Arm;
|
||||
match crate::ui::design_system::controls::two_option_segmented(ui, "Separate", "ORM", arm) {
|
||||
Some(false) => super::inputs::apply_separate_texture_preset(inputs),
|
||||
Some(true) => super::inputs::apply_arm_texture_preset(inputs),
|
||||
None => {}
|
||||
}
|
||||
}
|
||||
|
||||
fn surface_blend_controls(ui: &mut egui::Ui, state: &mut shared::MaterialRenderState) {
|
||||
let width = ui.available_width().max(1.0);
|
||||
let show_cutoff = state.alpha_mode == MaterialAlphaMode::Cutout;
|
||||
let combo_width = if show_cutoff {
|
||||
(width - 58.0).max(1.0)
|
||||
} else {
|
||||
width
|
||||
};
|
||||
let combo_rect = egui::Rect::from_min_size(ui.min_rect().min, egui::vec2(combo_width, 24.0));
|
||||
clipped_rect_ui(ui, combo_rect, |ui| {
|
||||
egui::ComboBox::from_id_salt("material_alpha_mode")
|
||||
.selected_text(match state.alpha_mode {
|
||||
MaterialAlphaMode::Opaque => "Opaque",
|
||||
MaterialAlphaMode::Cutout => "Cutout",
|
||||
})
|
||||
.width(combo_width)
|
||||
.show_ui(ui, |ui| {
|
||||
ui.selectable_value(&mut state.alpha_mode, MaterialAlphaMode::Opaque, "Opaque");
|
||||
ui.selectable_value(&mut state.alpha_mode, MaterialAlphaMode::Cutout, "Cutout");
|
||||
});
|
||||
});
|
||||
if show_cutoff {
|
||||
let cutoff_rect = egui::Rect::from_min_size(
|
||||
ui.min_rect().min + egui::vec2(combo_width + 4.0, 1.0),
|
||||
egui::vec2(54.0_f32.min(width - combo_width - 4.0), 22.0),
|
||||
);
|
||||
ui.put(
|
||||
cutoff_rect,
|
||||
egui::DragValue::new(&mut state.alpha_cutoff)
|
||||
.range(0.0..=1.0)
|
||||
.speed(0.01),
|
||||
)
|
||||
.on_hover_text("Alpha cutoff");
|
||||
}
|
||||
}
|
||||
|
||||
fn clipped_rect_ui<R>(
|
||||
ui: &mut egui::Ui,
|
||||
rect: egui::Rect,
|
||||
add_contents: impl FnOnce(&mut egui::Ui) -> R,
|
||||
) -> R {
|
||||
ui.scope_builder(egui::UiBuilder::new().max_rect(rect), |ui| {
|
||||
ui.set_clip_rect(rect.intersect(ui.clip_rect()));
|
||||
add_contents(ui)
|
||||
})
|
||||
.inner
|
||||
}
|
||||
@@ -269,7 +269,7 @@ pub(super) fn material_texture_candidates(world: &mut World) -> Vec<MaterialText
|
||||
label: asset.label.clone(),
|
||||
detail: path.to_string(),
|
||||
reference,
|
||||
selection: AssetSelection::File(path.to_string()),
|
||||
locate: MaterialLocateTarget::File(path.to_string()),
|
||||
thumbnail: thumbnails.as_ref().map_or(
|
||||
MaterialThumbnailPresentation::Pending,
|
||||
|cache| {
|
||||
@@ -325,11 +325,10 @@ pub(super) fn material_texture_candidates(world: &mut World) -> Vec<MaterialText
|
||||
label: label.clone(),
|
||||
detail: format!("{} | {source_path}", asset.label),
|
||||
reference,
|
||||
selection: AssetSelection::SubAsset {
|
||||
locate: MaterialLocateTarget::SubAsset {
|
||||
parent_path: parent_path.to_string(),
|
||||
sub_asset_id,
|
||||
label,
|
||||
kind: AssetSubAssetKind::Texture,
|
||||
source_path: Some(source_path.clone()),
|
||||
},
|
||||
thumbnail: MaterialThumbnailPresentation::Pending,
|
||||
|
||||
@@ -220,12 +220,21 @@ pub(super) fn material_input_rows(
|
||||
);
|
||||
let rects = geometry.row_rects(row_rect);
|
||||
rect_ui(ui, rects.label, |ui| material_input_label(ui, property));
|
||||
rect_ui(ui, rects.value, |ui| {
|
||||
material_input_value_ui(ui, property, companion, inputs)
|
||||
});
|
||||
rect_ui(ui, rects.channel, |ui| {
|
||||
material_input_channel_ui(ui, property, inputs)
|
||||
});
|
||||
let is_color = matches!(property.property_type, ShaderPropertyType::Color);
|
||||
rect_ui(
|
||||
ui,
|
||||
if is_color {
|
||||
rects.color_value
|
||||
} else {
|
||||
rects.value
|
||||
},
|
||||
|ui| material_input_value_ui(ui, property, companion, inputs),
|
||||
);
|
||||
if !is_color {
|
||||
rect_ui(ui, rects.channel, |ui| {
|
||||
material_input_channel_ui(ui, property, inputs)
|
||||
});
|
||||
}
|
||||
if material_input_uses_texture(property) {
|
||||
let texture = rect_ui(ui, rects.texture_group, |ui| {
|
||||
material_input_texture_ui(
|
||||
@@ -518,7 +527,7 @@ fn readonly_channel(ui: &mut egui::Ui, channel: &str) {
|
||||
rect.right_center() - egui::vec2(8.0, 0.0),
|
||||
egui::Align2::CENTER_CENTER,
|
||||
egui_phosphor_icons::icons::CARET_DOWN.as_str(),
|
||||
egui::FontId::new(9.0, egui::FontFamily::Name("phosphor-regular".into())),
|
||||
egui::FontId::new(9.0, egui::FontFamily::Name("phosphor-bold".into())),
|
||||
palette.text_muted,
|
||||
);
|
||||
response.on_hover_text("Channel is fixed by this material input");
|
||||
|
||||
@@ -29,7 +29,7 @@ pub(crate) fn material_instance_asset_editor(
|
||||
.and_then(|selection| {
|
||||
texture_assets
|
||||
.iter()
|
||||
.find(|candidate| candidate.selection == *selection)
|
||||
.find(|candidate| material_locate_matches_selection(&candidate.locate, selection))
|
||||
})
|
||||
.cloned();
|
||||
let original = draft.clone();
|
||||
@@ -58,13 +58,9 @@ pub(crate) fn material_instance_asset_editor(
|
||||
}
|
||||
ui.add_enabled_ui(false, |ui| {
|
||||
let mut render_state = base_asset.render_state;
|
||||
super::asset_editor::material_surface_options_ui(
|
||||
ui,
|
||||
&mut render_state,
|
||||
Some(&mut draft.overrides),
|
||||
);
|
||||
material_surface_options_ui(ui, &mut render_state, Some(&mut draft.overrides));
|
||||
});
|
||||
ui.add_space(8.0);
|
||||
ui.add_space(4.0);
|
||||
let input_response = super::instance_inputs::material_instance_input_schema_editor(
|
||||
ui,
|
||||
&schema,
|
||||
@@ -73,8 +69,10 @@ pub(crate) fn material_instance_asset_editor(
|
||||
&texture_assets,
|
||||
texture_drop_candidate.as_ref(),
|
||||
);
|
||||
if let Some(selection) = input_response.locate.clone() {
|
||||
world.resource_mut::<EditorAssets>().select(selection);
|
||||
if let Some(target) = input_response.locate.clone() {
|
||||
world
|
||||
.resource_mut::<EditorAssets>()
|
||||
.select(material_locate_selection(target));
|
||||
crate::ui::request_editor_tab(world, crate::ui::EditorTab::AssetBrowser);
|
||||
}
|
||||
if input_response.browse_library {
|
||||
|
||||
@@ -14,7 +14,7 @@ pub(super) fn material_instance_input_schema_editor(
|
||||
let mut effective = normalized_base.clone();
|
||||
overlay_inputs(&mut effective, overrides);
|
||||
|
||||
let response = super::inputs::material_input_schema_editor_with_inheritance(
|
||||
let response = material_input_schema_editor_with_inheritance(
|
||||
ui,
|
||||
schema,
|
||||
&mut effective,
|
||||
@@ -110,6 +110,7 @@ fn upsert_texture(textures: &mut Vec<MaterialTextureBinding>, texture: MaterialT
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
use shared::MaterialParameterValue;
|
||||
|
||||
#[test]
|
||||
fn instance_editor_retains_only_values_different_from_base() {
|
||||
|
||||
@@ -7,14 +7,12 @@
|
||||
use std::collections::HashSet;
|
||||
use std::path::Path;
|
||||
|
||||
use bevy::prelude::{Vec2, Vec3, World};
|
||||
use bevy::prelude::World;
|
||||
use bevy_egui::egui;
|
||||
use egui_phosphor_icons::{icons, Icon};
|
||||
use shared::{
|
||||
standard_lit_input_schema, ColorDesc, EditorAssetRef, MaterialAlphaMode, MaterialAsset,
|
||||
MaterialInputDesc, MaterialInputSchema, MaterialInputSet, MaterialInstanceAsset,
|
||||
MaterialParameter, MaterialParameterValue, MaterialRef, MaterialShaderKind,
|
||||
MaterialTextureBinding, ShaderPropertyType, ShaderSchemaAsset, TextureChannel,
|
||||
standard_lit_input_schema, EditorAssetRef, MaterialAsset, MaterialInputSchema,
|
||||
MaterialInputSet, MaterialInstanceAsset, MaterialParameter, MaterialRef, MaterialShaderKind,
|
||||
MaterialTextureBinding, ShaderPropertyType, ShaderSchemaAsset,
|
||||
};
|
||||
|
||||
use crate::asset_db::{ensure_asset_record, find_asset_by_path, save_registry};
|
||||
@@ -29,17 +27,10 @@ use crate::ui::document_status::authored_document_status_ui;
|
||||
|
||||
use super::theme::{ERROR, TEXT_DIM, TEXT_MUTED, WARNING};
|
||||
|
||||
mod advanced_preview;
|
||||
mod asset_editor;
|
||||
mod editor;
|
||||
mod inputs;
|
||||
mod instance_editor;
|
||||
mod instance_inputs;
|
||||
mod layout;
|
||||
mod panel;
|
||||
mod pickers;
|
||||
mod texture_inputs;
|
||||
mod uv_transform;
|
||||
|
||||
pub(crate) use asset_editor::material_asset_editor;
|
||||
pub(crate) use editor::{
|
||||
@@ -47,67 +38,57 @@ pub(crate) use editor::{
|
||||
material_shader_label, set_material_shader_kind,
|
||||
};
|
||||
use editor::{material_shader_settings, material_texture_candidates, shader_schema_assets};
|
||||
pub(crate) use inputs::material_input_schema_editor;
|
||||
use inputs::*;
|
||||
pub(crate) use instance_editor::material_instance_asset_editor;
|
||||
pub(crate) use panel::{
|
||||
material_slot_panel, materials_section, MaterialHealth, MaterialLayerBadge,
|
||||
MaterialPickerCandidate, MaterialSlotAction, MaterialSlotPanelViewModel,
|
||||
MaterialsSectionViewModel,
|
||||
pub(crate) use editor_ui::materials::{
|
||||
compact_text_edit, default_value_for_shader_property, ensure_material_texture_binding,
|
||||
material_input_schema_editor, material_input_schema_editor_with_inheritance,
|
||||
material_slot_panel, material_surface_options_ui, materials_section, optional_path_edit,
|
||||
parameter_value_matches_property, shader_kind_picker, MaterialHealth,
|
||||
MaterialInputEditorResponse, MaterialLayerBadge, MaterialLocateTarget, MaterialPickerCandidate,
|
||||
MaterialSlotAction, MaterialSlotPanelViewModel, MaterialTextureCandidate,
|
||||
MaterialThumbnailPresentation, MaterialsSectionViewModel,
|
||||
};
|
||||
use texture_inputs::*;
|
||||
|
||||
const PHOSPHOR: &str = "phosphor-regular";
|
||||
|
||||
#[derive(Clone, Debug)]
|
||||
pub(crate) struct MaterialTextureCandidate {
|
||||
label: String,
|
||||
detail: String,
|
||||
reference: EditorAssetRef,
|
||||
selection: AssetSelection,
|
||||
thumbnail: MaterialThumbnailPresentation,
|
||||
}
|
||||
|
||||
#[derive(Clone, Copy, Debug, PartialEq)]
|
||||
pub(crate) enum MaterialThumbnailPresentation {
|
||||
Ready(egui::TextureId),
|
||||
Pending,
|
||||
Failed,
|
||||
}
|
||||
|
||||
#[derive(Clone, Copy)]
|
||||
enum TextureSlotSelection<'a> {
|
||||
Reference(Option<&'a EditorAssetRef>),
|
||||
}
|
||||
|
||||
#[derive(Default)]
|
||||
struct TextureSlotResponse {
|
||||
selected: Option<MaterialTextureCandidate>,
|
||||
locate: Option<AssetSelection>,
|
||||
clear: bool,
|
||||
accepted_drop: bool,
|
||||
browse_library: bool,
|
||||
}
|
||||
|
||||
#[derive(Default)]
|
||||
pub(crate) struct MaterialInputEditorResponse {
|
||||
pub accepted_drop: bool,
|
||||
pub locate: Option<AssetSelection>,
|
||||
pub browse_library: bool,
|
||||
}
|
||||
|
||||
fn fit_width(ui: &egui::Ui, min: f32, max: f32) -> f32 {
|
||||
let available = ui.available_width().max(1.0);
|
||||
available.min(max).max(min.min(available))
|
||||
}
|
||||
|
||||
fn icon_text(icon: Icon, size: f32) -> egui::RichText {
|
||||
egui::RichText::new(icon.as_str()).font(egui::FontId::new(
|
||||
size,
|
||||
egui::FontFamily::Name(PHOSPHOR.into()),
|
||||
))
|
||||
}
|
||||
pub(crate) use instance_editor::material_instance_asset_editor;
|
||||
|
||||
fn natural_cmp(left: &str, right: &str) -> std::cmp::Ordering {
|
||||
left.to_ascii_lowercase().cmp(&right.to_ascii_lowercase())
|
||||
}
|
||||
|
||||
fn material_locate_selection(target: MaterialLocateTarget) -> AssetSelection {
|
||||
match target {
|
||||
MaterialLocateTarget::File(path) => AssetSelection::File(path),
|
||||
MaterialLocateTarget::SubAsset {
|
||||
parent_path,
|
||||
sub_asset_id,
|
||||
label,
|
||||
source_path,
|
||||
} => AssetSelection::SubAsset {
|
||||
parent_path,
|
||||
sub_asset_id,
|
||||
label,
|
||||
kind: AssetSubAssetKind::Texture,
|
||||
source_path,
|
||||
},
|
||||
}
|
||||
}
|
||||
|
||||
fn material_locate_matches_selection(
|
||||
target: &MaterialLocateTarget,
|
||||
selection: &AssetSelection,
|
||||
) -> bool {
|
||||
match (target, selection) {
|
||||
(MaterialLocateTarget::File(left), AssetSelection::File(right)) => left == right,
|
||||
(
|
||||
MaterialLocateTarget::SubAsset {
|
||||
parent_path: left_parent,
|
||||
sub_asset_id: left_sub_asset,
|
||||
..
|
||||
},
|
||||
AssetSelection::SubAsset {
|
||||
parent_path: right_parent,
|
||||
sub_asset_id: right_sub_asset,
|
||||
..
|
||||
},
|
||||
) => left_parent == right_parent && left_sub_asset == right_sub_asset,
|
||||
_ => false,
|
||||
}
|
||||
}
|
||||
@@ -6,14 +6,18 @@ use shared::{EditorAssetRef, MaterialShaderKind};
|
||||
|
||||
use super::layout::MaterialPanelGeometry;
|
||||
use super::MaterialThumbnailPresentation;
|
||||
use crate::ui::design_system::controls::{icon_button, icon_label, status};
|
||||
use crate::ui::design_system::controls::status;
|
||||
use crate::ui::design_system::typography::TypeRole;
|
||||
use crate::ui::design_system::{self, DesignPalette, HEADER_HEIGHT};
|
||||
use crate::ui::widgets::phosphor_icon;
|
||||
|
||||
mod header_actions;
|
||||
|
||||
use header_actions::{expanded_status_actions, overflow_menu, SLOT_STATUS_ACTION_WIDTH};
|
||||
|
||||
const SLOT_ACCENT_X: f32 = 8.0;
|
||||
const SLOT_CARET_CENTER_X: f32 = 23.0;
|
||||
const SLOT_PREVIEW_X: f32 = 35.0;
|
||||
const SHADER_CONTROL_WIDTH: f32 = 220.0;
|
||||
|
||||
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
|
||||
pub(crate) enum MaterialLayerBadge {
|
||||
@@ -73,6 +77,16 @@ impl MaterialHealth {
|
||||
),
|
||||
}
|
||||
}
|
||||
|
||||
fn icon(self) -> egui_phosphor_icons::Icon {
|
||||
match self {
|
||||
Self::Healthy => icons::CHECK_CIRCLE,
|
||||
Self::Dirty => icons::PENCIL_SIMPLE,
|
||||
Self::Processing => icons::CIRCLE_NOTCH,
|
||||
Self::Broken => icons::WARNING_CIRCLE,
|
||||
Self::ReadOnly => icons::LOCK_SIMPLE,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone)]
|
||||
@@ -275,16 +289,19 @@ fn slot_header(
|
||||
egui::pos2(rect.left() + SLOT_CARET_CENTER_X, rect.center().y),
|
||||
egui::vec2(18.0, 28.0),
|
||||
);
|
||||
let caret_icon = if *open {
|
||||
icons::CARET_DOWN
|
||||
} else {
|
||||
icons::CARET_RIGHT
|
||||
};
|
||||
let caret = ui.put(
|
||||
caret_rect,
|
||||
egui::Button::new(phosphor_icon(
|
||||
if *open {
|
||||
icons::CARET_DOWN
|
||||
} else {
|
||||
icons::CARET_RIGHT
|
||||
},
|
||||
12.0,
|
||||
))
|
||||
egui::Button::new(
|
||||
egui::RichText::new(caret_icon.as_str()).font(egui::FontId::new(
|
||||
12.0,
|
||||
egui::FontFamily::Name("phosphor-bold".into()),
|
||||
)),
|
||||
)
|
||||
.frame(false),
|
||||
);
|
||||
if caret.clicked() {
|
||||
@@ -299,7 +316,7 @@ fn slot_header(
|
||||
egui::vec2(preview_size, preview_size),
|
||||
);
|
||||
let preview = material_thumbnail_at(ui, view, preview_rect);
|
||||
let action_width = 140.0;
|
||||
let action_width = SLOT_STATUS_ACTION_WIDTH;
|
||||
let identity_left = preview_rect.right() + 6.0;
|
||||
let actions_left = rect.right() - action_width - 8.0;
|
||||
let identity_right = (identity_left + design_system::MATERIAL_IDENTITY_WIDTH)
|
||||
@@ -323,42 +340,20 @@ fn slot_header(
|
||||
})
|
||||
.inner;
|
||||
let actions_rect = egui::Rect::from_min_size(
|
||||
egui::pos2(actions_left, rect.top() + 7.0),
|
||||
egui::vec2(action_width, height - 14.0),
|
||||
egui::pos2(actions_left, rect.top() + if *open { 9.0 } else { 7.0 }),
|
||||
egui::vec2(action_width, if *open { 64.0 } else { height - 14.0 }),
|
||||
);
|
||||
ui.scope_builder(egui::UiBuilder::new().max_rect(actions_rect), |ui| {
|
||||
if *open {
|
||||
ui.with_layout(egui::Layout::top_down(egui::Align::Max), |ui| {
|
||||
let (color, label, tooltip) = view.health.presentation(palette);
|
||||
ui.horizontal(|ui| status(ui, color, label, tooltip));
|
||||
ui.with_layout(egui::Layout::right_to_left(egui::Align::Center), |ui| {
|
||||
overflow_menu(ui, view, actions, diagnostics_ui);
|
||||
if view.can_clear
|
||||
&& icon_button(ui, icons::X, "Clear actor assignment", true).clicked()
|
||||
{
|
||||
actions.push(MaterialSlotAction::Clear);
|
||||
}
|
||||
if view.can_locate
|
||||
&& icon_button(ui, icons::CROSSHAIR, "Locate in Content Browser", true)
|
||||
.clicked()
|
||||
{
|
||||
actions.push(MaterialSlotAction::Locate);
|
||||
}
|
||||
if icon_button(ui, icons::FOLDER_OPEN, "Browse project materials", true)
|
||||
.clicked()
|
||||
{
|
||||
actions.push(MaterialSlotAction::BrowseLibrary);
|
||||
}
|
||||
});
|
||||
});
|
||||
} else {
|
||||
if *open {
|
||||
expanded_status_actions(ui, actions_rect, view, actions, diagnostics_ui, palette);
|
||||
} else {
|
||||
ui.scope_builder(egui::UiBuilder::new().max_rect(actions_rect), |ui| {
|
||||
ui.with_layout(egui::Layout::right_to_left(egui::Align::Center), |ui| {
|
||||
overflow_menu(ui, view, actions, diagnostics_ui);
|
||||
let (color, label, tooltip) = view.health.presentation(palette);
|
||||
ui.horizontal(|ui| status(ui, color, label, tooltip));
|
||||
ui.horizontal(|ui| status(ui, view.health.icon(), color, label, tooltip));
|
||||
});
|
||||
}
|
||||
});
|
||||
});
|
||||
}
|
||||
if response.clicked() {
|
||||
if let Some(pointer) = ui.input(|input| input.pointer.interact_pos()) {
|
||||
if !caret_rect.contains(pointer)
|
||||
@@ -482,7 +477,7 @@ fn material_identity(
|
||||
if let Some(mut kind) = view.shader_kind {
|
||||
egui::ComboBox::from_id_salt("material_identity_shader_kind")
|
||||
.selected_text(&view.shader)
|
||||
.width(150.0_f32.min(ui.available_width().max(1.0)))
|
||||
.width(SHADER_CONTROL_WIDTH.min(ui.available_width().max(1.0)))
|
||||
.show_ui(ui, |ui| {
|
||||
ui.selectable_value(&mut kind, MaterialShaderKind::StandardLit, "Standard Lit");
|
||||
ui.selectable_value(&mut kind, MaterialShaderKind::Unlit, "Unlit");
|
||||
@@ -494,7 +489,10 @@ fn material_identity(
|
||||
}
|
||||
} else {
|
||||
ui.add_sized(
|
||||
[150.0_f32.min(ui.available_width().max(1.0)), 22.0],
|
||||
[
|
||||
SHADER_CONTROL_WIDTH.min(ui.available_width().max(1.0)),
|
||||
22.0,
|
||||
],
|
||||
egui::Label::new(
|
||||
TypeRole::Body
|
||||
.text(&view.shader)
|
||||
@@ -572,72 +570,6 @@ fn material_thumbnail_at(
|
||||
response.on_hover_text(format!("Open {} material picker", view.label))
|
||||
}
|
||||
|
||||
fn overflow_menu(
|
||||
ui: &mut egui::Ui,
|
||||
view: &MaterialSlotPanelViewModel,
|
||||
actions: &mut Vec<MaterialSlotAction>,
|
||||
diagnostics_ui: impl FnOnce(&mut egui::Ui),
|
||||
) {
|
||||
let palette = design_system::palette(ui);
|
||||
ui.menu_button(phosphor_icon(icons::DOTS_THREE, 16.0), |ui| {
|
||||
if view.can_locate && menu_action(ui, icons::CROSSHAIR, "Locate", palette.text_primary) {
|
||||
actions.push(MaterialSlotAction::Locate);
|
||||
ui.close();
|
||||
}
|
||||
if menu_action(
|
||||
ui,
|
||||
icons::FOLDER_OPEN,
|
||||
"Browse Asset Library",
|
||||
palette.text_primary,
|
||||
) {
|
||||
actions.push(MaterialSlotAction::BrowseLibrary);
|
||||
ui.close();
|
||||
}
|
||||
if view.can_clear && menu_action(ui, icons::X, "Clear material", palette.text_primary) {
|
||||
actions.push(MaterialSlotAction::Clear);
|
||||
ui.close();
|
||||
}
|
||||
if view.can_create_instance
|
||||
&& menu_action(
|
||||
ui,
|
||||
icons::COPY,
|
||||
"Create Instance and Assign",
|
||||
palette.text_primary,
|
||||
)
|
||||
{
|
||||
actions.push(MaterialSlotAction::CreateInstance);
|
||||
ui.close();
|
||||
}
|
||||
if view.can_extract
|
||||
&& menu_action(ui, icons::EXPORT, "Extract Editable…", palette.text_primary)
|
||||
{
|
||||
actions.push(MaterialSlotAction::ExtractEditable);
|
||||
ui.close();
|
||||
}
|
||||
ui.separator();
|
||||
ui.label(TypeRole::Section.text("Source & Diagnostics"));
|
||||
diagnostics_ui(ui);
|
||||
})
|
||||
.response
|
||||
.on_hover_text("Material actions and diagnostics");
|
||||
}
|
||||
|
||||
fn menu_action(
|
||||
ui: &mut egui::Ui,
|
||||
icon: egui_phosphor_icons::Icon,
|
||||
label: &str,
|
||||
color: egui::Color32,
|
||||
) -> bool {
|
||||
ui.add(egui::Button::new(icon_label(
|
||||
icon,
|
||||
label,
|
||||
TypeRole::Control,
|
||||
14.0,
|
||||
color,
|
||||
)))
|
||||
.clicked()
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
@@ -671,6 +603,8 @@ mod tests {
|
||||
assert_eq!(SLOT_CARET_CENTER_X, 23.0);
|
||||
assert_eq!(SLOT_PREVIEW_X, 35.0);
|
||||
assert_eq!(SLOT_PREVIEW_X - (SLOT_CARET_CENTER_X + 6.0), 6.0);
|
||||
assert_eq!(SLOT_STATUS_ACTION_WIDTH, 140.0);
|
||||
assert_eq!(SHADER_CONTROL_WIDTH, 220.0);
|
||||
}
|
||||
|
||||
#[test]
|
||||
@@ -740,4 +674,13 @@ mod tests {
|
||||
assert!(!view.health.presentation(palette).1.is_empty());
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn penpot_material_statuses_use_semantic_phosphor_icons() {
|
||||
assert_eq!(MaterialHealth::Healthy.icon(), icons::CHECK_CIRCLE);
|
||||
assert_eq!(MaterialHealth::Dirty.icon(), icons::PENCIL_SIMPLE);
|
||||
assert_eq!(MaterialHealth::Processing.icon(), icons::CIRCLE_NOTCH);
|
||||
assert_eq!(MaterialHealth::Broken.icon(), icons::WARNING_CIRCLE);
|
||||
assert_eq!(MaterialHealth::ReadOnly.icon(), icons::LOCK_SIMPLE);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,216 @@
|
||||
//! Exact Penpot status/action geometry for an expanded material-slot header.
|
||||
|
||||
use bevy_egui::egui;
|
||||
use egui_phosphor_icons::icons;
|
||||
|
||||
use super::{MaterialSlotAction, MaterialSlotPanelViewModel};
|
||||
use crate::ui::design_system::controls::{icon_button, icon_label, status};
|
||||
use crate::ui::design_system::typography::TypeRole;
|
||||
use crate::ui::design_system::{self, DesignPalette};
|
||||
|
||||
pub(super) const SLOT_STATUS_ACTION_WIDTH: f32 = 140.0;
|
||||
|
||||
#[derive(Debug, Clone, Copy, PartialEq)]
|
||||
struct ExpandedHeaderActionGeometry {
|
||||
status: egui::Rect,
|
||||
menu: egui::Rect,
|
||||
browse: egui::Rect,
|
||||
locate: egui::Rect,
|
||||
clear: egui::Rect,
|
||||
}
|
||||
|
||||
fn geometry(rect: egui::Rect) -> ExpandedHeaderActionGeometry {
|
||||
let status_row = egui::Rect::from_min_size(
|
||||
rect.min + egui::vec2(0.0, 5.333),
|
||||
egui::vec2(SLOT_STATUS_ACTION_WIDTH, 24.0),
|
||||
);
|
||||
let menu = egui::Rect::from_min_size(
|
||||
status_row.min + egui::vec2(116.0, 0.0),
|
||||
egui::vec2(24.0, 24.0),
|
||||
);
|
||||
let action_row = rect.min + egui::vec2(0.0, 34.667);
|
||||
ExpandedHeaderActionGeometry {
|
||||
status: egui::Rect::from_min_max(
|
||||
status_row.min,
|
||||
egui::pos2(menu.left() - 5.0, status_row.bottom()),
|
||||
),
|
||||
menu,
|
||||
browse: egui::Rect::from_min_size(
|
||||
action_row + egui::vec2(56.0, 0.0),
|
||||
egui::vec2(24.0, 24.0),
|
||||
),
|
||||
locate: egui::Rect::from_min_size(
|
||||
action_row + egui::vec2(86.0, 0.0),
|
||||
egui::vec2(24.0, 24.0),
|
||||
),
|
||||
clear: egui::Rect::from_min_size(
|
||||
action_row + egui::vec2(116.0, 0.0),
|
||||
egui::vec2(24.0, 24.0),
|
||||
),
|
||||
}
|
||||
}
|
||||
|
||||
pub(super) fn expanded_status_actions(
|
||||
ui: &mut egui::Ui,
|
||||
rect: egui::Rect,
|
||||
view: &MaterialSlotPanelViewModel,
|
||||
actions: &mut Vec<MaterialSlotAction>,
|
||||
diagnostics_ui: impl FnOnce(&mut egui::Ui),
|
||||
palette: DesignPalette,
|
||||
) {
|
||||
let geometry = geometry(rect);
|
||||
rect_scope(ui, geometry.status, |ui| {
|
||||
ui.with_layout(egui::Layout::right_to_left(egui::Align::Center), |ui| {
|
||||
let (color, label, tooltip) = view.health.presentation(palette);
|
||||
status(ui, view.health.icon(), color, label, tooltip);
|
||||
});
|
||||
});
|
||||
rect_scope(ui, geometry.menu, |ui| {
|
||||
overflow_menu(ui, view, actions, diagnostics_ui);
|
||||
});
|
||||
|
||||
for (button_rect, action, enabled, icon, tooltip) in [
|
||||
(
|
||||
geometry.browse,
|
||||
MaterialSlotAction::BrowseLibrary,
|
||||
true,
|
||||
icons::FOLDER_OPEN,
|
||||
"Browse project materials",
|
||||
),
|
||||
(
|
||||
geometry.locate,
|
||||
MaterialSlotAction::Locate,
|
||||
view.can_locate,
|
||||
icons::CROSSHAIR,
|
||||
"Locate in Content Browser",
|
||||
),
|
||||
(
|
||||
geometry.clear,
|
||||
MaterialSlotAction::Clear,
|
||||
view.can_clear,
|
||||
icons::X,
|
||||
"Clear actor assignment",
|
||||
),
|
||||
] {
|
||||
if !enabled {
|
||||
continue;
|
||||
}
|
||||
let clicked = rect_scope(ui, button_rect, |ui| {
|
||||
icon_button(ui, icon, tooltip, true).clicked()
|
||||
});
|
||||
if clicked {
|
||||
actions.push(action);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
pub(super) fn overflow_menu(
|
||||
ui: &mut egui::Ui,
|
||||
view: &MaterialSlotPanelViewModel,
|
||||
actions: &mut Vec<MaterialSlotAction>,
|
||||
diagnostics_ui: impl FnOnce(&mut egui::Ui),
|
||||
) {
|
||||
let palette = design_system::palette(ui);
|
||||
ui.menu_button(
|
||||
egui::RichText::new(icons::DOTS_THREE.as_str()).font(egui::FontId::new(
|
||||
16.0,
|
||||
egui::FontFamily::Name("phosphor-bold".into()),
|
||||
)),
|
||||
|ui| {
|
||||
if view.can_locate && menu_action(ui, icons::CROSSHAIR, "Locate", palette.text_primary)
|
||||
{
|
||||
actions.push(MaterialSlotAction::Locate);
|
||||
ui.close();
|
||||
}
|
||||
if menu_action(
|
||||
ui,
|
||||
icons::FOLDER_OPEN,
|
||||
"Browse Asset Library",
|
||||
palette.text_primary,
|
||||
) {
|
||||
actions.push(MaterialSlotAction::BrowseLibrary);
|
||||
ui.close();
|
||||
}
|
||||
if view.can_clear && menu_action(ui, icons::X, "Clear material", palette.text_primary) {
|
||||
actions.push(MaterialSlotAction::Clear);
|
||||
ui.close();
|
||||
}
|
||||
if view.can_create_instance
|
||||
&& menu_action(
|
||||
ui,
|
||||
icons::COPY,
|
||||
"Create Instance and Assign",
|
||||
palette.text_primary,
|
||||
)
|
||||
{
|
||||
actions.push(MaterialSlotAction::CreateInstance);
|
||||
ui.close();
|
||||
}
|
||||
if view.can_extract
|
||||
&& menu_action(ui, icons::EXPORT, "Extract Editable…", palette.text_primary)
|
||||
{
|
||||
actions.push(MaterialSlotAction::ExtractEditable);
|
||||
ui.close();
|
||||
}
|
||||
ui.separator();
|
||||
ui.label(TypeRole::Section.text("Source & Diagnostics"));
|
||||
diagnostics_ui(ui);
|
||||
},
|
||||
)
|
||||
.response
|
||||
.on_hover_text("Material actions and diagnostics");
|
||||
}
|
||||
|
||||
fn menu_action(
|
||||
ui: &mut egui::Ui,
|
||||
icon: egui_phosphor_icons::Icon,
|
||||
label: &str,
|
||||
color: egui::Color32,
|
||||
) -> bool {
|
||||
ui.add(egui::Button::new(icon_label(
|
||||
icon,
|
||||
label,
|
||||
TypeRole::Control,
|
||||
14.0,
|
||||
color,
|
||||
)))
|
||||
.clicked()
|
||||
}
|
||||
|
||||
fn rect_scope<R>(
|
||||
ui: &mut egui::Ui,
|
||||
rect: egui::Rect,
|
||||
add_contents: impl FnOnce(&mut egui::Ui) -> R,
|
||||
) -> R {
|
||||
ui.scope_builder(egui::UiBuilder::new().max_rect(rect), |ui| {
|
||||
ui.set_clip_rect(rect.intersect(ui.clip_rect()));
|
||||
add_contents(ui)
|
||||
})
|
||||
.inner
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn expanded_status_and_actions_match_the_penpot_header_geometry() {
|
||||
let rect = egui::Rect::from_min_size(egui::pos2(448.0, 9.0), egui::vec2(140.0, 64.0));
|
||||
let geometry = geometry(rect);
|
||||
assert_eq!(geometry.menu.min, egui::pos2(564.0, 14.333));
|
||||
assert_eq!(geometry.browse.min, egui::pos2(504.0, 43.667));
|
||||
assert_eq!(geometry.locate.min, egui::pos2(534.0, 43.667));
|
||||
assert_eq!(geometry.clear.min, egui::pos2(564.0, 43.667));
|
||||
assert_eq!(geometry.menu.size(), egui::vec2(24.0, 24.0));
|
||||
assert_eq!(geometry.clear.size(), egui::vec2(24.0, 24.0));
|
||||
for child in [
|
||||
geometry.status,
|
||||
geometry.menu,
|
||||
geometry.browse,
|
||||
geometry.locate,
|
||||
geometry.clear,
|
||||
] {
|
||||
assert!(rect.contains_rect(child));
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -261,7 +261,7 @@ fn paint_thumbnail(ui: &egui::Ui, rect: egui::Rect, thumbnail: MaterialThumbnail
|
||||
rect.center(),
|
||||
egui::Align2::CENTER_CENTER,
|
||||
icons::CIRCLE_NOTCH.as_str(),
|
||||
egui::FontId::new(14.0, egui::FontFamily::Name("phosphor-regular".into())),
|
||||
egui::FontId::new(14.0, egui::FontFamily::Name("phosphor-bold".into())),
|
||||
palette.text_muted,
|
||||
);
|
||||
}
|
||||
@@ -270,7 +270,7 @@ fn paint_thumbnail(ui: &egui::Ui, rect: egui::Rect, thumbnail: MaterialThumbnail
|
||||
rect.center(),
|
||||
egui::Align2::CENTER_CENTER,
|
||||
icons::WARNING.as_str(),
|
||||
egui::FontId::new(14.0, egui::FontFamily::Name("phosphor-regular".into())),
|
||||
egui::FontId::new(14.0, egui::FontFamily::Name("phosphor-bold".into())),
|
||||
palette.error,
|
||||
);
|
||||
}
|
||||
|
||||
@@ -372,7 +372,7 @@ fn paint_field_icon(
|
||||
rect.center(),
|
||||
egui::Align2::CENTER_CENTER,
|
||||
icon.as_str(),
|
||||
egui::FontId::new(12.0, egui::FontFamily::Name("phosphor-regular".into())),
|
||||
egui::FontId::new(12.0, egui::FontFamily::Name("phosphor-bold".into())),
|
||||
color,
|
||||
);
|
||||
}
|
||||
|
||||
@@ -92,7 +92,7 @@ fn vec2_group(
|
||||
reset_rect,
|
||||
egui::Button::new(
|
||||
egui::RichText::new(icons::ARROW_COUNTER_CLOCKWISE.as_str()).font(
|
||||
egui::FontId::new(14.0, egui::FontFamily::Name("phosphor-regular".into())),
|
||||
egui::FontId::new(14.0, egui::FontFamily::Name("phosphor-bold".into())),
|
||||
),
|
||||
),
|
||||
);
|
||||
|
||||
@@ -5,7 +5,7 @@ mod asset_card;
|
||||
mod audio_inspector;
|
||||
mod build;
|
||||
pub mod component_registry;
|
||||
pub(crate) mod design_system;
|
||||
pub(crate) use editor_ui::design_system;
|
||||
mod diagnostics;
|
||||
mod dock_tabs;
|
||||
pub(crate) mod document_status;
|
||||
|
||||
@@ -0,0 +1,12 @@
|
||||
[package]
|
||||
name = "editor_ui"
|
||||
version.workspace = true
|
||||
edition.workspace = true
|
||||
license.workspace = true
|
||||
description = "Lightweight production egui components and design system for Blacksite editor surfaces"
|
||||
|
||||
[dependencies]
|
||||
bevy_math = "0.19"
|
||||
egui.workspace = true
|
||||
egui_phosphor_icons.workspace = true
|
||||
material_schema.workspace = true
|
||||
@@ -0,0 +1,93 @@
|
||||
Copyright 2010-2024 Adobe (http://www.adobe.com/), with Reserved Font Name 'Source'. All Rights Reserved. Source is a trademark of Adobe in the United States and/or other countries.
|
||||
|
||||
This Font Software is licensed under the SIL Open Font License, Version 1.1.
|
||||
|
||||
This license is copied below, and is also available with a FAQ at: http://scripts.sil.org/OFL
|
||||
|
||||
|
||||
-----------------------------------------------------------
|
||||
SIL OPEN FONT LICENSE Version 1.1 - 26 February 2007
|
||||
-----------------------------------------------------------
|
||||
|
||||
PREAMBLE
|
||||
The goals of the Open Font License (OFL) are to stimulate worldwide
|
||||
development of collaborative font projects, to support the font creation
|
||||
efforts of academic and linguistic communities, and to provide a free and
|
||||
open framework in which fonts may be shared and improved in partnership
|
||||
with others.
|
||||
|
||||
The OFL allows the licensed fonts to be used, studied, modified and
|
||||
redistributed freely as long as they are not sold by themselves. The
|
||||
fonts, including any derivative works, can be bundled, embedded,
|
||||
redistributed and/or sold with any software provided that any reserved
|
||||
names are not used by derivative works. The fonts and derivatives,
|
||||
however, cannot be released under any other type of license. The
|
||||
requirement for fonts to remain under this license does not apply
|
||||
to any document created using the fonts or their derivatives.
|
||||
|
||||
DEFINITIONS
|
||||
"Font Software" refers to the set of files released by the Copyright
|
||||
Holder(s) under this license and clearly marked as such. This may
|
||||
include source files, build scripts and documentation.
|
||||
|
||||
"Reserved Font Name" refers to any names specified as such after the
|
||||
copyright statement(s).
|
||||
|
||||
"Original Version" refers to the collection of Font Software components as
|
||||
distributed by the Copyright Holder(s).
|
||||
|
||||
"Modified Version" refers to any derivative made by adding to, deleting,
|
||||
or substituting -- in part or in whole -- any of the components of the
|
||||
Original Version, by changing formats or by porting the Font Software to a
|
||||
new environment.
|
||||
|
||||
"Author" refers to any designer, engineer, programmer, technical
|
||||
writer or other person who contributed to the Font Software.
|
||||
|
||||
PERMISSION & CONDITIONS
|
||||
Permission is hereby granted, free of charge, to any person obtaining
|
||||
a copy of the Font Software, to use, study, copy, merge, embed, modify,
|
||||
redistribute, and sell modified and unmodified copies of the Font
|
||||
Software, subject to the following conditions:
|
||||
|
||||
1) Neither the Font Software nor any of its individual components,
|
||||
in Original or Modified Versions, may be sold by itself.
|
||||
|
||||
2) Original or Modified Versions of the Font Software may be bundled,
|
||||
redistributed and/or sold with any software, provided that each copy
|
||||
contains the above copyright notice and this license. These can be
|
||||
included either as stand-alone text files, human-readable headers or
|
||||
in the appropriate machine-readable metadata fields within text or
|
||||
binary files as long as those fields can be easily viewed by the user.
|
||||
|
||||
3) No Modified Version of the Font Software may use the Reserved Font
|
||||
Name(s) unless explicit written permission is granted by the corresponding
|
||||
Copyright Holder. This restriction only applies to the primary font name as
|
||||
presented to the users.
|
||||
|
||||
4) The name(s) of the Copyright Holder(s) or the Author(s) of the Font
|
||||
Software shall not be used to promote, endorse or advertise any
|
||||
Modified Version, except to acknowledge the contribution(s) of the
|
||||
Copyright Holder(s) and the Author(s) or with their explicit written
|
||||
permission.
|
||||
|
||||
5) The Font Software, modified or unmodified, in part or in whole,
|
||||
must be distributed entirely under this license, and must not be
|
||||
distributed under any other license. The requirement for fonts to
|
||||
remain under this license does not apply to any document created
|
||||
using the Font Software.
|
||||
|
||||
TERMINATION
|
||||
This license becomes null and void if any of the above conditions are
|
||||
not met.
|
||||
|
||||
DISCLAIMER
|
||||
THE FONT SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
|
||||
EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO ANY WARRANTIES OF
|
||||
MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT
|
||||
OF COPYRIGHT, PATENT, TRADEMARK, OR OTHER RIGHT. IN NO EVENT SHALL THE
|
||||
COPYRIGHT HOLDER BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
|
||||
INCLUDING ANY GENERAL, SPECIAL, INDIRECT, INCIDENTAL, OR CONSEQUENTIAL
|
||||
DAMAGES, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
|
||||
FROM, OUT OF THE USE OR INABILITY TO USE THE FONT SOFTWARE OR FROM
|
||||
OTHER DEALINGS IN THE FONT SOFTWARE.
|
||||
Binary file not shown.
Binary file not shown.
@@ -0,0 +1,328 @@
|
||||
//! Penpot 420×350 material color popup with live preview and reversible dismissal.
|
||||
|
||||
mod popup;
|
||||
|
||||
use egui;
|
||||
|
||||
use super::typography::TypeRole;
|
||||
|
||||
pub(super) const POPUP_SIZE: egui::Vec2 = egui::vec2(420.0, 350.0);
|
||||
|
||||
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
|
||||
pub(super) enum PickerMode {
|
||||
Wheel,
|
||||
Sliders,
|
||||
Presets,
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone)]
|
||||
pub(super) struct PickerSession {
|
||||
original: [f32; 4],
|
||||
current: [f32; 4],
|
||||
mode: PickerMode,
|
||||
hex: String,
|
||||
opened_at: f64,
|
||||
owner_rect: egui::Rect,
|
||||
original_intensity: Option<f32>,
|
||||
current_intensity: Option<f32>,
|
||||
}
|
||||
|
||||
#[derive(Debug, Default, Clone, Copy, PartialEq, Eq)]
|
||||
pub struct ColorPickerResponse {
|
||||
pub changed: bool,
|
||||
pub applied: bool,
|
||||
pub cancelled: bool,
|
||||
}
|
||||
|
||||
pub fn color_control(
|
||||
ui: &mut egui::Ui,
|
||||
salt: impl std::hash::Hash,
|
||||
label: &str,
|
||||
rgba: &mut [f32; 4],
|
||||
) -> ColorPickerResponse {
|
||||
color_control_impl(ui, salt, label, rgba, None)
|
||||
}
|
||||
|
||||
pub fn color_control_with_intensity(
|
||||
ui: &mut egui::Ui,
|
||||
salt: impl std::hash::Hash,
|
||||
label: &str,
|
||||
rgba: &mut [f32; 4],
|
||||
intensity: &mut f32,
|
||||
) -> ColorPickerResponse {
|
||||
color_control_impl(ui, salt, label, rgba, Some(intensity))
|
||||
}
|
||||
|
||||
fn color_control_impl(
|
||||
ui: &mut egui::Ui,
|
||||
salt: impl std::hash::Hash,
|
||||
label: &str,
|
||||
rgba: &mut [f32; 4],
|
||||
intensity: Option<&mut f32>,
|
||||
) -> ColorPickerResponse {
|
||||
let palette = super::palette(ui);
|
||||
let id = ui.make_persistent_id(("penpot_color_picker", salt));
|
||||
let width = ui.available_width().max(1.0);
|
||||
let (rect, response) = ui.allocate_exact_size(egui::vec2(width, 22.0), egui::Sense::click());
|
||||
let swatch_width = 44.0_f32.min(width);
|
||||
let swatch_rect = egui::Rect::from_min_size(rect.min, egui::vec2(swatch_width, 22.0));
|
||||
let gap = if width > swatch_width + 6.0 { 6.0 } else { 0.0 };
|
||||
let hex_rect = egui::Rect::from_min_size(
|
||||
rect.min + egui::vec2(swatch_width + gap, 0.0),
|
||||
egui::vec2((width - swatch_width - gap).max(0.0), 22.0),
|
||||
);
|
||||
popup::checker(ui.painter(), swatch_rect, palette.control, palette.elevated);
|
||||
let inner_swatch = swatch_rect.shrink(1.0);
|
||||
let rgb_rect = egui::Rect::from_min_max(
|
||||
inner_swatch.min,
|
||||
egui::pos2(inner_swatch.center().x, inner_swatch.max.y),
|
||||
);
|
||||
let alpha_rect = egui::Rect::from_min_max(
|
||||
egui::pos2(inner_swatch.center().x, inner_swatch.min.y),
|
||||
inner_swatch.max,
|
||||
);
|
||||
ui.painter().rect_filled(
|
||||
rgb_rect,
|
||||
3.0,
|
||||
egui::Color32::from_rgb(byte(rgba[0]), byte(rgba[1]), byte(rgba[2])),
|
||||
);
|
||||
ui.painter().rect_filled(alpha_rect, 3.0, color32(*rgba));
|
||||
ui.painter().rect_stroke(
|
||||
swatch_rect,
|
||||
4.0,
|
||||
egui::Stroke::new(1.0_f32, palette.border_strong),
|
||||
egui::StrokeKind::Inside,
|
||||
);
|
||||
if hex_rect.width() > 0.0 {
|
||||
ui.painter().rect(
|
||||
hex_rect,
|
||||
4.0,
|
||||
palette.control,
|
||||
egui::Stroke::new(1.0_f32, palette.border),
|
||||
egui::StrokeKind::Inside,
|
||||
);
|
||||
ui.painter().text(
|
||||
hex_rect.left_center() + egui::vec2(9.0, 0.0),
|
||||
egui::Align2::LEFT_CENTER,
|
||||
hex(*rgba),
|
||||
TypeRole::Body.font(),
|
||||
palette.text_primary,
|
||||
);
|
||||
}
|
||||
|
||||
if response.clicked() {
|
||||
let opened_at = ui.input(|input| input.time);
|
||||
ui.ctx().data_mut(|data| {
|
||||
data.insert_temp(
|
||||
id,
|
||||
PickerSession {
|
||||
original: *rgba,
|
||||
current: *rgba,
|
||||
mode: PickerMode::Wheel,
|
||||
hex: hex(*rgba),
|
||||
opened_at,
|
||||
owner_rect: ui.clip_rect(),
|
||||
original_intensity: intensity.as_deref().copied(),
|
||||
current_intensity: intensity.as_deref().copied(),
|
||||
},
|
||||
);
|
||||
});
|
||||
}
|
||||
|
||||
let before = *rgba;
|
||||
let mut result = ColorPickerResponse::default();
|
||||
let Some(mut session) = ui.ctx().data_mut(|data| data.get_temp::<PickerSession>(id)) else {
|
||||
return result;
|
||||
};
|
||||
let screen_rect = ui.ctx().content_rect();
|
||||
let popup_rect = centered_popup_rect(session.owner_rect, screen_rect);
|
||||
|
||||
let scrim = egui::Area::new(id.with("modal_scrim"))
|
||||
.order(egui::Order::Foreground)
|
||||
.fixed_pos(session.owner_rect.min)
|
||||
.show(ui.ctx(), |ui| {
|
||||
let (rect, response) =
|
||||
ui.allocate_exact_size(session.owner_rect.size(), egui::Sense::click());
|
||||
ui.painter()
|
||||
.rect_filled(rect, 0.0, egui::Color32::from_black_alpha(132));
|
||||
response
|
||||
})
|
||||
.inner;
|
||||
|
||||
let popup_response = egui::Area::new(id.with("popup"))
|
||||
.order(egui::Order::Foreground)
|
||||
.fixed_pos(popup_rect.min)
|
||||
.show(ui.ctx(), |ui| {
|
||||
ui.set_min_size(POPUP_SIZE);
|
||||
ui.set_max_size(POPUP_SIZE);
|
||||
popup::show(ui, label, &mut session, &mut result)
|
||||
})
|
||||
.response;
|
||||
|
||||
let escape = ui.input(|input| input.key_pressed(egui::Key::Escape));
|
||||
let outside_click = scrim.clicked()
|
||||
|| ui.input(|input| {
|
||||
input.pointer.any_pressed()
|
||||
&& input.time > session.opened_at
|
||||
&& input
|
||||
.pointer
|
||||
.interact_pos()
|
||||
.is_some_and(|position| !popup_response.rect.contains(position))
|
||||
});
|
||||
if escape || outside_click {
|
||||
result.cancelled = true;
|
||||
}
|
||||
|
||||
if result.cancelled {
|
||||
*rgba = session.original;
|
||||
if let (Some(target), Some(original)) = (intensity, session.original_intensity) {
|
||||
*target = original;
|
||||
}
|
||||
ui.ctx().data_mut(|data| data.remove::<PickerSession>(id));
|
||||
} else {
|
||||
*rgba = session.current;
|
||||
if let (Some(target), Some(current)) = (intensity, session.current_intensity) {
|
||||
*target = current;
|
||||
}
|
||||
if result.applied {
|
||||
ui.ctx().data_mut(|data| data.remove::<PickerSession>(id));
|
||||
} else {
|
||||
ui.ctx().data_mut(|data| data.insert_temp(id, session));
|
||||
}
|
||||
}
|
||||
result.changed = *rgba != before;
|
||||
result
|
||||
}
|
||||
|
||||
fn centered_popup_rect(owner: egui::Rect, screen: egui::Rect) -> egui::Rect {
|
||||
const SCREEN_MARGIN: f32 = 12.0;
|
||||
let desired = owner.center() - POPUP_SIZE * 0.5;
|
||||
let minimum = screen.min + egui::vec2(SCREEN_MARGIN, SCREEN_MARGIN);
|
||||
let maximum = screen.max - POPUP_SIZE - egui::vec2(SCREEN_MARGIN, SCREEN_MARGIN);
|
||||
let x = if maximum.x >= minimum.x {
|
||||
desired.x.clamp(minimum.x, maximum.x)
|
||||
} else {
|
||||
screen.center().x - POPUP_SIZE.x * 0.5
|
||||
};
|
||||
let y = if maximum.y >= minimum.y {
|
||||
desired.y.clamp(minimum.y, maximum.y)
|
||||
} else {
|
||||
screen.center().y - POPUP_SIZE.y * 0.5
|
||||
};
|
||||
egui::Rect::from_min_size(egui::pos2(x, y), POPUP_SIZE)
|
||||
}
|
||||
|
||||
pub(super) fn set_current(session: &mut PickerSession, value: [f32; 4]) {
|
||||
session.current = value.map(|component| component.clamp(0.0, 1.0));
|
||||
session.hex = hex(session.current);
|
||||
}
|
||||
|
||||
pub(super) fn color32(value: [f32; 4]) -> egui::Color32 {
|
||||
egui::Color32::from_rgba_unmultiplied(
|
||||
byte(value[0]),
|
||||
byte(value[1]),
|
||||
byte(value[2]),
|
||||
byte(value[3]),
|
||||
)
|
||||
}
|
||||
|
||||
pub(super) fn rgba(value: egui::Color32) -> [f32; 4] {
|
||||
[
|
||||
value.r() as f32 / 255.0,
|
||||
value.g() as f32 / 255.0,
|
||||
value.b() as f32 / 255.0,
|
||||
value.a() as f32 / 255.0,
|
||||
]
|
||||
}
|
||||
|
||||
pub(super) fn byte(value: f32) -> u8 {
|
||||
(value.clamp(0.0, 1.0) * 255.0).round() as u8
|
||||
}
|
||||
|
||||
pub(super) fn hex(value: [f32; 4]) -> String {
|
||||
if byte(value[3]) == 255 {
|
||||
format!(
|
||||
"#{:02X}{:02X}{:02X}",
|
||||
byte(value[0]),
|
||||
byte(value[1]),
|
||||
byte(value[2])
|
||||
)
|
||||
} else {
|
||||
format!(
|
||||
"#{:02X}{:02X}{:02X}{:02X}",
|
||||
byte(value[0]),
|
||||
byte(value[1]),
|
||||
byte(value[2]),
|
||||
byte(value[3])
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
pub(super) fn parse_hex(value: &str) -> Option<[f32; 4]> {
|
||||
let value = value.trim().trim_start_matches('#');
|
||||
if !matches!(value.len(), 6 | 8) {
|
||||
return None;
|
||||
}
|
||||
let rgb = u32::from_str_radix(&value[..6], 16).ok()?;
|
||||
let alpha = if value.len() == 8 {
|
||||
u8::from_str_radix(&value[6..], 16).ok()?
|
||||
} else {
|
||||
255
|
||||
};
|
||||
Some([
|
||||
((rgb >> 16) & 0xFF) as f32 / 255.0,
|
||||
((rgb >> 8) & 0xFF) as f32 / 255.0,
|
||||
(rgb & 0xFF) as f32 / 255.0,
|
||||
alpha as f32 / 255.0,
|
||||
])
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn popup_centers_on_inspector_owner_and_stays_on_screen() {
|
||||
let screen = egui::Rect::from_min_size(egui::Pos2::ZERO, egui::vec2(1440.0, 900.0));
|
||||
let inspector =
|
||||
egui::Rect::from_min_size(egui::pos2(800.0, 40.0), egui::vec2(640.0, 820.0));
|
||||
let popup = centered_popup_rect(inspector, screen);
|
||||
assert_eq!(popup.size(), POPUP_SIZE);
|
||||
assert_eq!(popup.center(), inspector.center());
|
||||
|
||||
let edge = centered_popup_rect(
|
||||
egui::Rect::from_min_size(egui::pos2(0.0, 0.0), egui::vec2(200.0, 200.0)),
|
||||
screen,
|
||||
);
|
||||
assert!(edge.left() >= 12.0);
|
||||
assert!(edge.top() >= 12.0);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn penpot_hex_round_trip_preserves_rgba() {
|
||||
let value = [0.2, 0.4, 0.6, 0.8];
|
||||
let parsed = parse_hex(&hex(value)).expect("valid generated hex");
|
||||
for (left, right) in value.into_iter().zip(parsed) {
|
||||
assert!((left - right).abs() <= 1.0 / 255.0);
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn cancel_restores_opening_value_and_apply_keeps_live_preview() {
|
||||
let original = [0.1, 0.2, 0.3, 1.0];
|
||||
let mut session = PickerSession {
|
||||
original,
|
||||
current: [0.8, 0.7, 0.6, 0.5],
|
||||
mode: PickerMode::Wheel,
|
||||
hex: String::new(),
|
||||
opened_at: 0.0,
|
||||
owner_rect: egui::Rect::ZERO,
|
||||
original_intensity: None,
|
||||
current_intensity: None,
|
||||
};
|
||||
let applied = session.current;
|
||||
set_current(&mut session, applied);
|
||||
assert_eq!(session.original, original);
|
||||
assert_eq!(session.current, applied);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,765 @@
|
||||
//! Fixed-coordinate renderer for the exported Penpot color overlay.
|
||||
|
||||
mod sliders;
|
||||
|
||||
use egui::{self, ecolor::Hsva};
|
||||
use egui_phosphor_icons::{icons, Icon};
|
||||
|
||||
use super::{
|
||||
byte, color32, parse_hex, rgba, set_current, ColorPickerResponse, PickerMode, PickerSession,
|
||||
POPUP_SIZE,
|
||||
};
|
||||
use crate::design_system::typography::TypeRole;
|
||||
|
||||
const RECENTS: [egui::Color32; 8] = colors([
|
||||
0xE7D4B4, 0x53D3E6, 0xCA6CE0, 0xF06B75, 0x55C58A, 0xF3C85B, 0x6F88EF, 0xF3F5F7,
|
||||
]);
|
||||
const PRESETS: [egui::Color32; 24] = colors([
|
||||
0xE7D4B4, 0xF2EEE8, 0xD5B59C, 0xA8795B, 0x734C3C, 0x3B2D29, 0xE45D68, 0xF09A55, 0xE9D05B,
|
||||
0x79C267, 0x45B7A6, 0x4FA9D8, 0x5A78DE, 0x8E68D8, 0xC26BC7, 0xE68DB5, 0xF5F7FA, 0xC4CCD5,
|
||||
0x8995A3, 0x56616E, 0x303842, 0x1D242C, 0x101419, 0x07090C,
|
||||
]);
|
||||
const PLANNED_EYEDROPPER: &str = "Planned — screen sampling pending";
|
||||
|
||||
const fn colors<const N: usize>(values: [u32; N]) -> [egui::Color32; N] {
|
||||
let mut result = [egui::Color32::BLACK; N];
|
||||
let mut index = 0;
|
||||
while index < N {
|
||||
let value = values[index];
|
||||
result[index] = egui::Color32::from_rgb(
|
||||
((value >> 16) & 0xFF) as u8,
|
||||
((value >> 8) & 0xFF) as u8,
|
||||
(value & 0xFF) as u8,
|
||||
);
|
||||
index += 1;
|
||||
}
|
||||
result
|
||||
}
|
||||
|
||||
struct Geometry;
|
||||
|
||||
impl Geometry {
|
||||
const HEADER_HEIGHT: f32 = 38.0;
|
||||
const CONTENT: egui::Rect =
|
||||
egui::Rect::from_min_max(egui::pos2(12.0, 74.0), egui::pos2(408.0, 276.0));
|
||||
const WHEEL_EDITOR: egui::Rect =
|
||||
egui::Rect::from_min_max(egui::pos2(12.0, 74.0), egui::pos2(190.0, 276.0));
|
||||
const VALUES: egui::Rect =
|
||||
egui::Rect::from_min_max(egui::pos2(198.0, 82.0), egui::pos2(396.0, 268.0));
|
||||
const RECENTS: egui::Rect =
|
||||
egui::Rect::from_min_max(egui::pos2(12.0, 282.0), egui::pos2(408.0, 310.0));
|
||||
const FOOTER: egui::Rect =
|
||||
egui::Rect::from_min_max(egui::pos2(12.0, 316.0), egui::pos2(408.0, 342.0));
|
||||
|
||||
fn rect(root: egui::Rect, local: egui::Rect) -> egui::Rect {
|
||||
local.translate(root.min.to_vec2())
|
||||
}
|
||||
|
||||
fn at(root: egui::Rect, x: f32, y: f32, width: f32, height: f32) -> egui::Rect {
|
||||
egui::Rect::from_min_size(root.min + egui::vec2(x, y), egui::vec2(width, height))
|
||||
}
|
||||
}
|
||||
|
||||
pub(super) fn show(
|
||||
ui: &mut egui::Ui,
|
||||
label: &str,
|
||||
session: &mut PickerSession,
|
||||
result: &mut ColorPickerResponse,
|
||||
) -> egui::Response {
|
||||
let palette = crate::design_system::palette(ui);
|
||||
let (root, response) = ui.allocate_exact_size(POPUP_SIZE, egui::Sense::hover());
|
||||
ui.painter().rect(
|
||||
root,
|
||||
7.0,
|
||||
palette.panel,
|
||||
egui::Stroke::new(1.0_f32, palette.border_strong),
|
||||
egui::StrokeKind::Inside,
|
||||
);
|
||||
ui.painter().line_segment(
|
||||
[
|
||||
root.min + egui::vec2(0.0, Geometry::HEADER_HEIGHT),
|
||||
root.min + egui::vec2(root.width(), Geometry::HEADER_HEIGHT),
|
||||
],
|
||||
egui::Stroke::new(1.0_f32, palette.border),
|
||||
);
|
||||
|
||||
header(ui, root, label, session, result);
|
||||
mode_tabs(ui, root, session);
|
||||
intensity_control(ui, root, session);
|
||||
match session.mode {
|
||||
PickerMode::Wheel => wheel_mode(ui, root, session),
|
||||
PickerMode::Sliders => sliders::show(ui, root, session),
|
||||
PickerMode::Presets => presets_mode(ui, root, session),
|
||||
}
|
||||
recent_row(ui, root, session);
|
||||
footer(ui, root, result);
|
||||
response
|
||||
}
|
||||
|
||||
fn intensity_control(ui: &mut egui::Ui, root: egui::Rect, session: &mut PickerSession) {
|
||||
let Some(intensity) = session.current_intensity.as_mut() else {
|
||||
return;
|
||||
};
|
||||
let palette = crate::design_system::palette(ui);
|
||||
text(
|
||||
ui,
|
||||
root.min + egui::vec2(272.0, 55.0),
|
||||
egui::Align2::LEFT_CENTER,
|
||||
"Intensity",
|
||||
TypeRole::Small.font(),
|
||||
palette.text_muted,
|
||||
);
|
||||
ui.put(
|
||||
Geometry::at(root, 326.0, 43.0, 82.0, 24.0),
|
||||
egui::DragValue::new(intensity)
|
||||
.range(0.0..=50_000.0)
|
||||
.speed(10.0),
|
||||
)
|
||||
.on_hover_text("Emissive luminance multiplier in nits");
|
||||
}
|
||||
|
||||
fn header(
|
||||
ui: &mut egui::Ui,
|
||||
root: egui::Rect,
|
||||
label: &str,
|
||||
session: &PickerSession,
|
||||
result: &mut ColorPickerResponse,
|
||||
) {
|
||||
let palette = crate::design_system::palette(ui);
|
||||
text(
|
||||
ui,
|
||||
root.min + egui::vec2(12.0, 19.0),
|
||||
egui::Align2::LEFT_CENTER,
|
||||
label,
|
||||
TypeRole::Section.font(),
|
||||
palette.text_primary,
|
||||
);
|
||||
text(
|
||||
ui,
|
||||
root.min + egui::vec2(84.0, 19.0),
|
||||
egui::Align2::LEFT_CENTER,
|
||||
"sRGB · RGBA",
|
||||
TypeRole::Small.font(),
|
||||
palette.text_muted,
|
||||
);
|
||||
paint_swatch(
|
||||
ui,
|
||||
Geometry::at(root, 348.0, 7.0, 26.0, 24.0),
|
||||
color32(session.current),
|
||||
egui::Sense::hover(),
|
||||
"Current color",
|
||||
);
|
||||
if icon_button(
|
||||
ui,
|
||||
Geometry::at(root, 384.0, 7.0, 24.0, 24.0),
|
||||
icons::X,
|
||||
"Cancel color changes",
|
||||
true,
|
||||
)
|
||||
.clicked()
|
||||
{
|
||||
result.cancelled = true;
|
||||
}
|
||||
}
|
||||
|
||||
fn mode_tabs(ui: &mut egui::Ui, root: egui::Rect, session: &mut PickerSession) {
|
||||
let palette = crate::design_system::palette(ui);
|
||||
for (index, (mode, icon, label, width)) in [
|
||||
(PickerMode::Wheel, icons::CIRCLE, "Wheel", 76.0),
|
||||
(PickerMode::Sliders, icons::SLIDERS, "Sliders", 76.0),
|
||||
(PickerMode::Presets, icons::SQUARES_FOUR, "Presets", 78.0),
|
||||
]
|
||||
.into_iter()
|
||||
.enumerate()
|
||||
{
|
||||
let x = [12.0, 92.0, 172.0][index];
|
||||
let rect = Geometry::at(root, x, 42.0, width, 26.0);
|
||||
let selected = session.mode == mode;
|
||||
let response = ui.put(
|
||||
rect,
|
||||
egui::Button::new(crate::design_system::controls::icon_label(
|
||||
icon,
|
||||
label,
|
||||
TypeRole::Body,
|
||||
12.0,
|
||||
if selected {
|
||||
palette.text_primary
|
||||
} else {
|
||||
palette.text_secondary
|
||||
},
|
||||
))
|
||||
.fill(if selected {
|
||||
palette.accent_dark
|
||||
} else {
|
||||
palette.control
|
||||
})
|
||||
.stroke(egui::Stroke::new(
|
||||
1.0_f32,
|
||||
if selected {
|
||||
palette.accent
|
||||
} else {
|
||||
palette.border
|
||||
},
|
||||
))
|
||||
.corner_radius(4.0),
|
||||
);
|
||||
if selected {
|
||||
ui.painter().rect_filled(
|
||||
egui::Rect::from_center_size(
|
||||
egui::pos2(rect.center().x, rect.bottom() - 1.0),
|
||||
egui::vec2(60.0, 2.0),
|
||||
),
|
||||
1.0,
|
||||
palette.accent,
|
||||
);
|
||||
}
|
||||
if response.clicked() {
|
||||
session.mode = mode;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fn wheel_mode(ui: &mut egui::Ui, root: egui::Rect, session: &mut PickerSession) {
|
||||
let palette = crate::design_system::palette(ui);
|
||||
let ring = Geometry::at(root, 29.0, 88.0, 144.0, 144.0);
|
||||
let sv = Geometry::at(root, 65.0, 124.0, 72.0, 72.0);
|
||||
let editor = Geometry::rect(root, Geometry::WHEEL_EDITOR);
|
||||
let response = ui.interact(
|
||||
editor,
|
||||
ui.make_persistent_id("penpot_color_wheel"),
|
||||
egui::Sense::click_and_drag(),
|
||||
);
|
||||
let mut hsva = Hsva::from_rgba_unmultiplied(
|
||||
session.current[0],
|
||||
session.current[1],
|
||||
session.current[2],
|
||||
session.current[3],
|
||||
);
|
||||
paint_hue_wheel(ui.painter(), ring, hsva.h, palette.text_primary);
|
||||
paint_sv(
|
||||
ui.painter(),
|
||||
sv,
|
||||
hsva.h,
|
||||
hsva.s,
|
||||
hsva.v,
|
||||
palette.text_primary,
|
||||
);
|
||||
if response.clicked() || response.dragged() {
|
||||
if let Some(position) = response.interact_pointer_pos() {
|
||||
let delta = position - ring.center();
|
||||
if sv.contains(position) {
|
||||
hsva.s = ((position.x - sv.left()) / sv.width()).clamp(0.0, 1.0);
|
||||
hsva.v = (1.0 - (position.y - sv.top()) / sv.height()).clamp(0.0, 1.0);
|
||||
} else if (52.0..=76.0).contains(&delta.length()) {
|
||||
hsva.h = (delta.angle() / std::f32::consts::TAU + 0.25).rem_euclid(1.0);
|
||||
}
|
||||
let [r, g, b] = hsva.to_rgb();
|
||||
set_current(session, [r, g, b, hsva.a]);
|
||||
}
|
||||
}
|
||||
text(
|
||||
ui,
|
||||
root.min + egui::vec2(101.0, 252.0),
|
||||
egui::Align2::CENTER_CENTER,
|
||||
"Drag ring or field",
|
||||
TypeRole::Small.font(),
|
||||
palette.text_muted,
|
||||
);
|
||||
values(ui, root, session);
|
||||
}
|
||||
|
||||
fn values(ui: &mut egui::Ui, root: egui::Rect, session: &mut PickerSession) {
|
||||
let palette = crate::design_system::palette(ui);
|
||||
let _values_bounds = Geometry::rect(root, Geometry::VALUES);
|
||||
caption(ui, root, 198.0, 82.0, "CURRENT");
|
||||
caption(ui, root, 302.0, 82.0, "PREVIOUS");
|
||||
paint_swatch(
|
||||
ui,
|
||||
Geometry::at(root, 198.0, 96.0, 94.0, 30.0),
|
||||
color32(session.current),
|
||||
egui::Sense::hover(),
|
||||
"Current live value",
|
||||
);
|
||||
paint_swatch(
|
||||
ui,
|
||||
Geometry::at(root, 302.0, 96.0, 94.0, 30.0),
|
||||
color32(session.original),
|
||||
egui::Sense::hover(),
|
||||
"Value when the picker opened",
|
||||
);
|
||||
|
||||
caption(ui, root, 198.0, 132.0, "HEX");
|
||||
let hex_field = Geometry::at(root, 198.0, 144.0, 166.0, 24.0);
|
||||
field_background(ui, hex_field);
|
||||
let edit_rect = egui::Rect::from_min_max(
|
||||
hex_field.min,
|
||||
egui::pos2(hex_field.right() - 24.0, hex_field.bottom()),
|
||||
);
|
||||
let edit = ui.put(
|
||||
edit_rect.shrink2(egui::vec2(5.0, 2.0)),
|
||||
egui::TextEdit::singleline(&mut session.hex)
|
||||
.font(TypeRole::Body.font())
|
||||
.frame(egui::Frame::NONE),
|
||||
);
|
||||
if edit.lost_focus() && ui.input(|input| input.key_pressed(egui::Key::Enter)) {
|
||||
if let Some(value) = parse_hex(&session.hex) {
|
||||
set_current(session, value);
|
||||
}
|
||||
}
|
||||
if bare_icon(
|
||||
ui,
|
||||
egui::Rect::from_min_size(
|
||||
egui::pos2(hex_field.right() - 24.0, hex_field.top()),
|
||||
egui::vec2(24.0, 24.0),
|
||||
),
|
||||
icons::COPY,
|
||||
"Copy HEX",
|
||||
palette.text_secondary,
|
||||
)
|
||||
.clicked()
|
||||
{
|
||||
ui.ctx().copy_text(session.hex.clone());
|
||||
}
|
||||
let eyedropper = Geometry::at(root, 370.0, 144.0, 26.0, 24.0);
|
||||
field_background(ui, eyedropper);
|
||||
bare_icon(
|
||||
ui,
|
||||
eyedropper,
|
||||
icons::EYEDROPPER,
|
||||
PLANNED_EYEDROPPER,
|
||||
palette.text_muted,
|
||||
);
|
||||
|
||||
caption(ui, root, 198.0, 174.0, "RGBA");
|
||||
let mut bytes = session.current.map(byte);
|
||||
let before_bytes = bytes;
|
||||
for (index, prefix) in ["R ", "G ", "B ", "A "].into_iter().enumerate() {
|
||||
let rect = Geometry::at(root, 198.0 + index as f32 * 49.0, 186.0, 45.0, 24.0);
|
||||
ui.put(
|
||||
rect,
|
||||
egui::DragValue::new(&mut bytes[index])
|
||||
.range(0..=255)
|
||||
.prefix(prefix),
|
||||
);
|
||||
}
|
||||
if bytes != before_bytes {
|
||||
set_current(session, bytes.map(|component| component as f32 / 255.0));
|
||||
}
|
||||
|
||||
caption(ui, root, 198.0, 216.0, "HSV");
|
||||
let mut hsva = Hsva::from_rgba_unmultiplied(
|
||||
session.current[0],
|
||||
session.current[1],
|
||||
session.current[2],
|
||||
session.current[3],
|
||||
);
|
||||
let mut hsv = [hsva.h * 360.0, hsva.s * 100.0, hsva.v * 100.0];
|
||||
let before_hsv = hsv;
|
||||
for (index, suffix) in ["°", "%", "%"].into_iter().enumerate() {
|
||||
let rect = Geometry::at(root, 198.0 + index as f32 * 66.0, 228.0, 61.0, 24.0);
|
||||
ui.put(
|
||||
rect,
|
||||
egui::DragValue::new(&mut hsv[index])
|
||||
.range(if index == 0 { 0.0..=360.0 } else { 0.0..=100.0 })
|
||||
.suffix(suffix)
|
||||
.max_decimals(0),
|
||||
);
|
||||
}
|
||||
if hsv != before_hsv {
|
||||
hsva.h = hsv[0] / 360.0;
|
||||
hsva.s = hsv[1] / 100.0;
|
||||
hsva.v = hsv[2] / 100.0;
|
||||
let [r, g, b] = hsva.to_rgb();
|
||||
set_current(session, [r, g, b, hsva.a]);
|
||||
}
|
||||
|
||||
caption(ui, root, 198.0, 258.0, "ALPHA");
|
||||
alpha_control(ui, Geometry::at(root, 240.0, 256.0, 156.0, 14.0), session);
|
||||
}
|
||||
|
||||
fn presets_mode(ui: &mut egui::Ui, root: egui::Rect, session: &mut PickerSession) {
|
||||
let palette = crate::design_system::palette(ui);
|
||||
let content = Geometry::rect(root, Geometry::CONTENT);
|
||||
ui.painter().rect_filled(content, 4.0, palette.recessed);
|
||||
caption(ui, root, 24.0, 86.0, "MATERIAL PALETTE");
|
||||
for (index, color) in PRESETS.into_iter().enumerate() {
|
||||
let column = index % 8;
|
||||
let row = index / 8;
|
||||
let rect = Geometry::at(
|
||||
root,
|
||||
24.0 + column as f32 * 47.0,
|
||||
104.0 + row as f32 * 52.0,
|
||||
34.0,
|
||||
34.0,
|
||||
);
|
||||
if paint_swatch(ui, rect, color, egui::Sense::click(), "Use preset color").clicked() {
|
||||
set_current(session, rgba(color));
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fn recent_row(ui: &mut egui::Ui, root: egui::Rect, session: &mut PickerSession) {
|
||||
let palette = crate::design_system::palette(ui);
|
||||
let row = Geometry::rect(root, Geometry::RECENTS);
|
||||
ui.painter().rect_filled(row, 4.0, palette.section);
|
||||
text(
|
||||
ui,
|
||||
root.min + egui::vec2(20.0, 296.0),
|
||||
egui::Align2::LEFT_CENTER,
|
||||
"RECENT",
|
||||
TypeRole::Caption.font(),
|
||||
palette.text_muted,
|
||||
);
|
||||
for (index, color) in RECENTS.into_iter().enumerate() {
|
||||
let rect = Geometry::at(root, 74.0 + index as f32 * 36.0, 286.0, 28.0, 20.0);
|
||||
if paint_swatch(ui, rect, color, egui::Sense::click(), "Use recent color").clicked() {
|
||||
set_current(session, rgba(color));
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fn footer(ui: &mut egui::Ui, root: egui::Rect, result: &mut ColorPickerResponse) {
|
||||
let palette = crate::design_system::palette(ui);
|
||||
let footer = Geometry::rect(root, Geometry::FOOTER);
|
||||
text(
|
||||
ui,
|
||||
footer.left_center(),
|
||||
egui::Align2::LEFT_CENTER,
|
||||
"Enter apply · Esc cancel",
|
||||
TypeRole::Small.font(),
|
||||
palette.text_muted,
|
||||
);
|
||||
if labeled_button(
|
||||
ui,
|
||||
Geometry::at(root, 254.0, 316.0, 72.0, 26.0),
|
||||
icons::X,
|
||||
"Cancel",
|
||||
false,
|
||||
)
|
||||
.clicked()
|
||||
{
|
||||
result.cancelled = true;
|
||||
}
|
||||
if labeled_button(
|
||||
ui,
|
||||
Geometry::at(root, 334.0, 316.0, 74.0, 26.0),
|
||||
icons::CHECK,
|
||||
"Apply",
|
||||
true,
|
||||
)
|
||||
.clicked()
|
||||
{
|
||||
result.applied = true;
|
||||
}
|
||||
}
|
||||
|
||||
fn alpha_control(ui: &mut egui::Ui, rect: egui::Rect, session: &mut PickerSession) {
|
||||
let palette = crate::design_system::palette(ui);
|
||||
checker(ui.painter(), rect, palette.control, palette.elevated);
|
||||
let response = ui.interact(
|
||||
rect.expand2(egui::vec2(0.0, 4.0)),
|
||||
ui.make_persistent_id("penpot_color_alpha"),
|
||||
egui::Sense::click_and_drag(),
|
||||
);
|
||||
if response.clicked() || response.dragged() {
|
||||
if let Some(position) = response.interact_pointer_pos() {
|
||||
let mut value = session.current;
|
||||
value[3] = ((position.x - rect.left()) / rect.width()).clamp(0.0, 1.0);
|
||||
set_current(session, value);
|
||||
}
|
||||
}
|
||||
let x = egui::lerp(rect.left()..=rect.right(), session.current[3]);
|
||||
ui.painter().rect_filled(
|
||||
egui::Rect::from_min_max(rect.min, egui::pos2(x, rect.bottom())),
|
||||
2.0,
|
||||
palette.accent.gamma_multiply(0.65),
|
||||
);
|
||||
ui.painter().rect_filled(
|
||||
egui::Rect::from_center_size(egui::pos2(x, rect.center().y), egui::vec2(10.0, 18.0)),
|
||||
3.0,
|
||||
palette.text_primary,
|
||||
);
|
||||
}
|
||||
|
||||
fn paint_hue_wheel(
|
||||
painter: &egui::Painter,
|
||||
rect: egui::Rect,
|
||||
selected_hue: f32,
|
||||
marker_color: egui::Color32,
|
||||
) {
|
||||
let center = rect.center();
|
||||
let outer = 72.0;
|
||||
let inner = 54.0;
|
||||
let mut mesh = egui::Mesh::default();
|
||||
const SEGMENTS: usize = 72;
|
||||
for segment in 0..SEGMENTS {
|
||||
let h0 = segment as f32 / SEGMENTS as f32;
|
||||
let h1 = (segment + 1) as f32 / SEGMENTS as f32;
|
||||
let a0 = (h0 - 0.25) * std::f32::consts::TAU;
|
||||
let a1 = (h1 - 0.25) * std::f32::consts::TAU;
|
||||
let start = mesh.vertices.len() as u32;
|
||||
let c0 = egui::Color32::from(Hsva::new(h0, 1.0, 1.0, 1.0));
|
||||
let c1 = egui::Color32::from(Hsva::new(h1, 1.0, 1.0, 1.0));
|
||||
for (radius, angle, color) in [
|
||||
(inner, a0, c0),
|
||||
(outer, a0, c0),
|
||||
(outer, a1, c1),
|
||||
(inner, a1, c1),
|
||||
] {
|
||||
mesh.colored_vertex(
|
||||
center + egui::vec2(angle.cos(), angle.sin()) * radius,
|
||||
color,
|
||||
);
|
||||
}
|
||||
mesh.add_triangle(start, start + 1, start + 2);
|
||||
mesh.add_triangle(start, start + 2, start + 3);
|
||||
}
|
||||
painter.add(mesh);
|
||||
let angle = (selected_hue - 0.25) * std::f32::consts::TAU;
|
||||
let marker = center + egui::vec2(angle.cos(), angle.sin()) * 63.0;
|
||||
painter.circle_stroke(marker, 5.0, egui::Stroke::new(2.0_f32, marker_color));
|
||||
}
|
||||
|
||||
fn paint_sv(
|
||||
painter: &egui::Painter,
|
||||
rect: egui::Rect,
|
||||
hue: f32,
|
||||
saturation: f32,
|
||||
value: f32,
|
||||
marker_color: egui::Color32,
|
||||
) {
|
||||
let mut mesh = egui::Mesh::default();
|
||||
for (position, color) in [
|
||||
(rect.left_top(), egui::Color32::WHITE),
|
||||
(
|
||||
rect.right_top(),
|
||||
egui::Color32::from(Hsva::new(hue, 1.0, 1.0, 1.0)),
|
||||
),
|
||||
(rect.right_bottom(), egui::Color32::BLACK),
|
||||
(rect.left_bottom(), egui::Color32::BLACK),
|
||||
] {
|
||||
mesh.colored_vertex(position, color);
|
||||
}
|
||||
mesh.add_triangle(0, 1, 2);
|
||||
mesh.add_triangle(0, 2, 3);
|
||||
painter.add(mesh);
|
||||
let marker = egui::pos2(
|
||||
egui::lerp(rect.x_range(), saturation),
|
||||
egui::lerp(rect.y_range(), 1.0 - value),
|
||||
);
|
||||
painter.circle_stroke(marker, 5.0, egui::Stroke::new(2.0_f32, marker_color));
|
||||
}
|
||||
|
||||
pub(super) fn checker(
|
||||
painter: &egui::Painter,
|
||||
rect: egui::Rect,
|
||||
dark: egui::Color32,
|
||||
light: egui::Color32,
|
||||
) {
|
||||
let size = 6.0;
|
||||
let columns = (rect.width() / size).ceil() as usize;
|
||||
let rows = (rect.height() / size).ceil() as usize;
|
||||
for row in 0..rows {
|
||||
for column in 0..columns {
|
||||
let cell = egui::Rect::from_min_size(
|
||||
rect.min + egui::vec2(column as f32 * size, row as f32 * size),
|
||||
egui::vec2(size, size),
|
||||
)
|
||||
.intersect(rect);
|
||||
painter.rect_filled(
|
||||
cell,
|
||||
0.0,
|
||||
if (row + column) % 2 == 0 { dark } else { light },
|
||||
);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fn paint_swatch(
|
||||
ui: &mut egui::Ui,
|
||||
rect: egui::Rect,
|
||||
color: egui::Color32,
|
||||
sense: egui::Sense,
|
||||
tooltip: &str,
|
||||
) -> egui::Response {
|
||||
let palette = crate::design_system::palette(ui);
|
||||
checker(ui.painter(), rect, palette.control, palette.elevated);
|
||||
ui.painter().rect_filled(rect.shrink(1.0), 3.0, color);
|
||||
ui.painter().rect_stroke(
|
||||
rect,
|
||||
3.0,
|
||||
egui::Stroke::new(1.0_f32, palette.border),
|
||||
egui::StrokeKind::Inside,
|
||||
);
|
||||
ui.interact(
|
||||
rect,
|
||||
ui.make_persistent_id(("color_swatch", rect.min.x.to_bits(), rect.min.y.to_bits())),
|
||||
sense,
|
||||
)
|
||||
.on_hover_text(tooltip)
|
||||
}
|
||||
|
||||
fn icon_button(
|
||||
ui: &mut egui::Ui,
|
||||
rect: egui::Rect,
|
||||
icon: Icon,
|
||||
tooltip: &str,
|
||||
enabled: bool,
|
||||
) -> egui::Response {
|
||||
let palette = crate::design_system::palette(ui);
|
||||
ui.put(
|
||||
rect,
|
||||
egui::Button::new(egui::RichText::new(icon.as_str()).font(egui::FontId::new(
|
||||
13.0,
|
||||
egui::FontFamily::Name("phosphor-regular".into()),
|
||||
)))
|
||||
.fill(palette.control)
|
||||
.stroke(egui::Stroke::new(1.0_f32, palette.border))
|
||||
.corner_radius(4.0)
|
||||
.sense(if enabled {
|
||||
egui::Sense::click()
|
||||
} else {
|
||||
egui::Sense::hover()
|
||||
}),
|
||||
)
|
||||
.on_hover_text(tooltip)
|
||||
}
|
||||
|
||||
fn bare_icon(
|
||||
ui: &mut egui::Ui,
|
||||
rect: egui::Rect,
|
||||
icon: Icon,
|
||||
tooltip: &str,
|
||||
color: egui::Color32,
|
||||
) -> egui::Response {
|
||||
let response = ui.interact(
|
||||
rect,
|
||||
ui.make_persistent_id(("color_icon", tooltip)),
|
||||
if tooltip == PLANNED_EYEDROPPER {
|
||||
egui::Sense::hover()
|
||||
} else {
|
||||
egui::Sense::click()
|
||||
},
|
||||
);
|
||||
ui.painter().text(
|
||||
rect.center(),
|
||||
egui::Align2::CENTER_CENTER,
|
||||
icon.as_str(),
|
||||
egui::FontId::new(12.0, egui::FontFamily::Name("phosphor-regular".into())),
|
||||
color,
|
||||
);
|
||||
response.on_hover_text(tooltip)
|
||||
}
|
||||
|
||||
fn labeled_button(
|
||||
ui: &mut egui::Ui,
|
||||
rect: egui::Rect,
|
||||
icon: Icon,
|
||||
label: &str,
|
||||
accent: bool,
|
||||
) -> egui::Response {
|
||||
let palette = crate::design_system::palette(ui);
|
||||
ui.push_id(("color_picker_footer_action", label), |ui| {
|
||||
ui.put(
|
||||
rect,
|
||||
egui::Button::new(crate::design_system::controls::icon_label(
|
||||
icon,
|
||||
label,
|
||||
TypeRole::Control,
|
||||
12.0,
|
||||
palette.text_primary,
|
||||
))
|
||||
.fill(if accent {
|
||||
palette.accent
|
||||
} else {
|
||||
palette.control
|
||||
})
|
||||
.stroke(egui::Stroke::new(
|
||||
1.0_f32,
|
||||
if accent {
|
||||
palette.accent
|
||||
} else {
|
||||
palette.border
|
||||
},
|
||||
))
|
||||
.corner_radius(4.0),
|
||||
)
|
||||
})
|
||||
.inner
|
||||
}
|
||||
|
||||
fn field_background(ui: &egui::Ui, rect: egui::Rect) {
|
||||
let palette = crate::design_system::palette(ui);
|
||||
ui.painter().rect(
|
||||
rect,
|
||||
4.0,
|
||||
palette.control,
|
||||
egui::Stroke::new(1.0_f32, palette.border),
|
||||
egui::StrokeKind::Inside,
|
||||
);
|
||||
}
|
||||
|
||||
fn caption(ui: &egui::Ui, root: egui::Rect, x: f32, y: f32, value: &str) {
|
||||
let palette = crate::design_system::palette(ui);
|
||||
text(
|
||||
ui,
|
||||
root.min + egui::vec2(x, y),
|
||||
egui::Align2::LEFT_TOP,
|
||||
value,
|
||||
TypeRole::Caption.font(),
|
||||
palette.text_muted,
|
||||
);
|
||||
}
|
||||
|
||||
fn text(
|
||||
ui: &egui::Ui,
|
||||
position: egui::Pos2,
|
||||
align: egui::Align2,
|
||||
value: &str,
|
||||
font: egui::FontId,
|
||||
color: egui::Color32,
|
||||
) {
|
||||
ui.painter().text(position, align, value, font, color);
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn exported_popup_regions_match_penpot_geometry() {
|
||||
assert_eq!(POPUP_SIZE, egui::vec2(420.0, 350.0));
|
||||
assert_eq!(Geometry::HEADER_HEIGHT, 38.0);
|
||||
assert_eq!(Geometry::CONTENT.size(), egui::vec2(396.0, 202.0));
|
||||
assert_eq!(Geometry::WHEEL_EDITOR.size(), egui::vec2(178.0, 202.0));
|
||||
assert_eq!(Geometry::VALUES.size(), egui::vec2(198.0, 186.0));
|
||||
assert_eq!(Geometry::RECENTS.size(), egui::vec2(396.0, 28.0));
|
||||
assert_eq!(Geometry::FOOTER.size(), egui::vec2(396.0, 26.0));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn exported_value_and_action_fields_retain_exact_sizes() {
|
||||
let root = egui::Rect::from_min_size(egui::Pos2::ZERO, POPUP_SIZE);
|
||||
assert_eq!(
|
||||
Geometry::at(root, 198.0, 144.0, 166.0, 24.0).size(),
|
||||
egui::vec2(166.0, 24.0)
|
||||
);
|
||||
assert_eq!(
|
||||
Geometry::at(root, 370.0, 144.0, 26.0, 24.0).size(),
|
||||
egui::vec2(26.0, 24.0)
|
||||
);
|
||||
assert_eq!(
|
||||
Geometry::at(root, 240.0, 256.0, 156.0, 14.0).size(),
|
||||
egui::vec2(156.0, 14.0)
|
||||
);
|
||||
assert_eq!(
|
||||
Geometry::at(root, 334.0, 316.0, 74.0, 26.0).size(),
|
||||
egui::vec2(74.0, 26.0)
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn disabled_eyedropper_has_no_state_or_action_contract() {
|
||||
assert_eq!(PLANNED_EYEDROPPER, "Planned — screen sampling pending");
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,167 @@
|
||||
//! Fixed Penpot geometry for the color picker's RGBA and HSV channel modes.
|
||||
|
||||
use egui::{self, ecolor::Hsva};
|
||||
|
||||
use super::super::{byte, set_current, PickerSession};
|
||||
use super::{caption, text, Geometry};
|
||||
use crate::design_system::typography::TypeRole;
|
||||
|
||||
/// Each 186 px channel group owns a 178 px row: a single-letter channel label,
|
||||
/// a 104 px track, and a 44 px value field.
|
||||
struct SliderGeometry;
|
||||
|
||||
impl SliderGeometry {
|
||||
const RGBA_X: f32 = 12.0;
|
||||
const HSV_X: f32 = 206.0;
|
||||
const TITLE_Y: f32 = 74.0;
|
||||
const FIRST_ROW_Y: f32 = 90.0;
|
||||
const ROW_STRIDE: f32 = 30.0;
|
||||
const LABEL_WIDTH: f32 = 18.0;
|
||||
const TRACK_X: f32 = 24.0;
|
||||
const TRACK_WIDTH: f32 = 104.0;
|
||||
const VALUE_X: f32 = 134.0;
|
||||
const VALUE_WIDTH: f32 = 44.0;
|
||||
const ROW_HEIGHT: f32 = 24.0;
|
||||
}
|
||||
|
||||
pub(super) fn show(ui: &mut egui::Ui, root: egui::Rect, session: &mut PickerSession) {
|
||||
let palette = crate::design_system::palette(ui);
|
||||
let content = Geometry::rect(root, Geometry::CONTENT);
|
||||
ui.painter().rect_filled(content, 4.0, palette.recessed);
|
||||
caption(
|
||||
ui,
|
||||
root,
|
||||
SliderGeometry::RGBA_X,
|
||||
SliderGeometry::TITLE_Y,
|
||||
"RGBA CHANNELS",
|
||||
);
|
||||
caption(
|
||||
ui,
|
||||
root,
|
||||
SliderGeometry::HSV_X,
|
||||
SliderGeometry::TITLE_Y,
|
||||
"HSV CHANNELS",
|
||||
);
|
||||
|
||||
let mut bytes = session.current.map(|component| f32::from(byte(component)));
|
||||
let before_bytes = bytes;
|
||||
for (index, label) in ["R", "G", "B", "A"].into_iter().enumerate() {
|
||||
slider_channel(
|
||||
ui,
|
||||
root,
|
||||
SliderGeometry::RGBA_X,
|
||||
index,
|
||||
label,
|
||||
&mut bytes[index],
|
||||
0.0..=255.0,
|
||||
"",
|
||||
);
|
||||
}
|
||||
if bytes != before_bytes {
|
||||
set_current(session, bytes.map(|component| component / 255.0));
|
||||
}
|
||||
|
||||
let mut hsva = Hsva::from_rgba_unmultiplied(
|
||||
session.current[0],
|
||||
session.current[1],
|
||||
session.current[2],
|
||||
session.current[3],
|
||||
);
|
||||
let mut values = [
|
||||
hsva.h * 360.0,
|
||||
hsva.s * 100.0,
|
||||
hsva.v * 100.0,
|
||||
hsva.a * 100.0,
|
||||
];
|
||||
let before = values;
|
||||
for (index, label) in ["H", "S", "V", "A"].into_iter().enumerate() {
|
||||
let range = if index == 0 { 0.0..=360.0 } else { 0.0..=100.0 };
|
||||
slider_channel(
|
||||
ui,
|
||||
root,
|
||||
SliderGeometry::HSV_X,
|
||||
index,
|
||||
label,
|
||||
&mut values[index],
|
||||
range,
|
||||
if index == 0 { "°" } else { "%" },
|
||||
);
|
||||
}
|
||||
if values != before {
|
||||
hsva.h = values[0] / 360.0;
|
||||
hsva.s = values[1] / 100.0;
|
||||
hsva.v = values[2] / 100.0;
|
||||
hsva.a = values[3] / 100.0;
|
||||
let [r, g, b] = hsva.to_rgb();
|
||||
set_current(session, [r, g, b, hsva.a]);
|
||||
}
|
||||
}
|
||||
|
||||
#[allow(clippy::too_many_arguments)]
|
||||
fn slider_channel(
|
||||
ui: &mut egui::Ui,
|
||||
root: egui::Rect,
|
||||
group_x: f32,
|
||||
index: usize,
|
||||
label: &str,
|
||||
value: &mut f32,
|
||||
range: std::ops::RangeInclusive<f32>,
|
||||
suffix: &str,
|
||||
) {
|
||||
let palette = crate::design_system::palette(ui);
|
||||
let y = SliderGeometry::FIRST_ROW_Y + index as f32 * SliderGeometry::ROW_STRIDE;
|
||||
let label_rect = Geometry::at(
|
||||
root,
|
||||
group_x,
|
||||
y,
|
||||
SliderGeometry::LABEL_WIDTH,
|
||||
SliderGeometry::ROW_HEIGHT,
|
||||
);
|
||||
text(
|
||||
ui,
|
||||
label_rect.left_center(),
|
||||
egui::Align2::LEFT_CENTER,
|
||||
label,
|
||||
TypeRole::Body.font(),
|
||||
palette.text_secondary,
|
||||
);
|
||||
|
||||
ui.put(
|
||||
Geometry::at(
|
||||
root,
|
||||
group_x + SliderGeometry::TRACK_X,
|
||||
y,
|
||||
SliderGeometry::TRACK_WIDTH,
|
||||
SliderGeometry::ROW_HEIGHT,
|
||||
),
|
||||
egui::Slider::new(value, range.clone()).show_value(false),
|
||||
);
|
||||
ui.put(
|
||||
Geometry::at(
|
||||
root,
|
||||
group_x + SliderGeometry::VALUE_X,
|
||||
y,
|
||||
SliderGeometry::VALUE_WIDTH,
|
||||
SliderGeometry::ROW_HEIGHT,
|
||||
),
|
||||
egui::DragValue::new(value)
|
||||
.range(range)
|
||||
.suffix(suffix)
|
||||
.max_decimals(0),
|
||||
);
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn sliders_mode_matches_the_two_exported_channel_groups() {
|
||||
assert_eq!(SliderGeometry::HSV_X - SliderGeometry::RGBA_X, 194.0);
|
||||
assert_eq!(SliderGeometry::TRACK_WIDTH, 104.0);
|
||||
assert_eq!(SliderGeometry::VALUE_WIDTH, 44.0);
|
||||
assert_eq!(SliderGeometry::VALUE_X + SliderGeometry::VALUE_WIDTH, 178.0);
|
||||
assert_eq!(SliderGeometry::ROW_STRIDE, 30.0);
|
||||
assert_eq!(SliderGeometry::ROW_HEIGHT, 24.0);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,381 @@
|
||||
//! Reusable Penpot-styled editor controls with no world or asset-store access.
|
||||
|
||||
use egui;
|
||||
use egui_phosphor_icons::{icons, Icon};
|
||||
use std::ops::RangeInclusive;
|
||||
|
||||
use super::palette;
|
||||
use super::typography::TypeRole;
|
||||
|
||||
// Penpot's scalar component keeps a six-pixel leading inset inside its value-group frame. The
|
||||
// exported child geometry is authoritative here; the group's transparent parent frame is six
|
||||
// pixels narrower than its visible children and must not be mistaken for the control width.
|
||||
const SCALAR_TRACK_X: f32 = 6.0;
|
||||
const SCALAR_NUMBER_GAP: f32 = 6.0;
|
||||
const SCALAR_TRACK_INTERACTION_HEIGHT: f32 = 10.0;
|
||||
const SCALAR_NUMBER_WIDTH: f32 = 33.0;
|
||||
const SCALAR_THUMB_RADIUS: f32 = 4.0;
|
||||
|
||||
pub fn section_frame(ui: &egui::Ui) -> egui::Frame {
|
||||
let palette = palette(ui);
|
||||
egui::Frame::new()
|
||||
.fill(palette.section)
|
||||
.stroke(egui::Stroke::new(1.0_f32, palette.border))
|
||||
.corner_radius(egui::CornerRadius::same(5))
|
||||
}
|
||||
|
||||
pub fn section_header(ui: &mut egui::Ui, title: &str, open: &mut bool) -> egui::Response {
|
||||
section_header_with_summary(ui, title, None, open)
|
||||
}
|
||||
|
||||
pub fn section_header_with_summary(
|
||||
ui: &mut egui::Ui,
|
||||
title: &str,
|
||||
summary: Option<&str>,
|
||||
open: &mut bool,
|
||||
) -> egui::Response {
|
||||
let palette = palette(ui);
|
||||
let (rect, response) = ui.allocate_exact_size(
|
||||
egui::vec2(
|
||||
ui.available_width().max(1.0),
|
||||
super::INPUT_SECTION_HEADER_HEIGHT,
|
||||
),
|
||||
egui::Sense::click(),
|
||||
);
|
||||
ui.painter().rect_filled(rect, 4.0, palette.elevated);
|
||||
ui.painter().text(
|
||||
rect.left_center() + egui::vec2(12.0, 0.0),
|
||||
egui::Align2::CENTER_CENTER,
|
||||
if *open {
|
||||
icons::CARET_DOWN.as_str()
|
||||
} else {
|
||||
icons::CARET_RIGHT.as_str()
|
||||
},
|
||||
egui::FontId::new(10.0, egui::FontFamily::Name("phosphor-bold".into())),
|
||||
palette.text_secondary,
|
||||
);
|
||||
ui.painter().text(
|
||||
rect.left_center() + egui::vec2(26.0, 0.0),
|
||||
egui::Align2::LEFT_CENTER,
|
||||
title,
|
||||
TypeRole::Section.font(),
|
||||
palette.text_primary,
|
||||
);
|
||||
if let Some(summary) = summary {
|
||||
ui.painter().text(
|
||||
rect.right_center() - egui::vec2(12.0, 0.0),
|
||||
egui::Align2::RIGHT_CENTER,
|
||||
summary,
|
||||
TypeRole::Small.font(),
|
||||
palette.text_muted,
|
||||
);
|
||||
}
|
||||
if response.clicked() {
|
||||
*open = !*open;
|
||||
}
|
||||
response
|
||||
}
|
||||
|
||||
/// Compose a Phosphor glyph and Source Sans label without asking either font to render the
|
||||
/// other's codepoints. This is the canonical path for icon-plus-text controls in a design-system
|
||||
/// scope.
|
||||
pub fn icon_label(
|
||||
icon: Icon,
|
||||
label: &str,
|
||||
role: TypeRole,
|
||||
icon_size: f32,
|
||||
color: egui::Color32,
|
||||
) -> egui::WidgetText {
|
||||
let mut job = egui::text::LayoutJob::default();
|
||||
job.append(
|
||||
icon.as_str(),
|
||||
0.0,
|
||||
egui::TextFormat {
|
||||
font_id: egui::FontId::new(icon_size, egui::FontFamily::Name("phosphor-bold".into())),
|
||||
color,
|
||||
..Default::default()
|
||||
},
|
||||
);
|
||||
if !label.is_empty() {
|
||||
job.append(
|
||||
label,
|
||||
6.0,
|
||||
egui::TextFormat {
|
||||
font_id: role.font(),
|
||||
color,
|
||||
..Default::default()
|
||||
},
|
||||
);
|
||||
}
|
||||
job.into()
|
||||
}
|
||||
|
||||
pub fn icon_button(ui: &mut egui::Ui, icon: Icon, tooltip: &str, enabled: bool) -> egui::Response {
|
||||
let palette = palette(ui);
|
||||
let response = ui.add_enabled(
|
||||
enabled,
|
||||
egui::Button::new(
|
||||
egui::RichText::new(icon.as_str())
|
||||
.font(egui::FontId::new(
|
||||
14.0,
|
||||
egui::FontFamily::Name("phosphor-bold".into()),
|
||||
))
|
||||
.color(palette.text_secondary),
|
||||
)
|
||||
.min_size(egui::vec2(24.0, 24.0))
|
||||
.fill(palette.control)
|
||||
.stroke(egui::Stroke::new(1.0_f32, palette.border))
|
||||
.corner_radius(egui::CornerRadius::same(4)),
|
||||
);
|
||||
response.on_hover_text(tooltip)
|
||||
}
|
||||
|
||||
pub fn status(ui: &mut egui::Ui, icon: Icon, color: egui::Color32, label: &str, tooltip: &str) {
|
||||
let palette = palette(ui);
|
||||
let mut job = egui::text::LayoutJob::default();
|
||||
job.append(
|
||||
icon.as_str(),
|
||||
0.0,
|
||||
egui::TextFormat {
|
||||
font_id: egui::FontId::new(12.0, egui::FontFamily::Name("phosphor-bold".into())),
|
||||
color,
|
||||
..Default::default()
|
||||
},
|
||||
);
|
||||
job.append(
|
||||
label,
|
||||
5.0,
|
||||
egui::TextFormat {
|
||||
font_id: TypeRole::Small.font(),
|
||||
color: palette.text_secondary,
|
||||
..Default::default()
|
||||
},
|
||||
);
|
||||
let response = ui.add(egui::Label::new(job).sense(egui::Sense::hover()));
|
||||
response.on_hover_text(tooltip);
|
||||
}
|
||||
|
||||
pub fn switch(ui: &mut egui::Ui, value: &mut bool) -> egui::Response {
|
||||
let palette = palette(ui);
|
||||
let (rect, mut response) = ui.allocate_exact_size(egui::vec2(31.0, 16.0), egui::Sense::click());
|
||||
if response.clicked() {
|
||||
*value = !*value;
|
||||
response.mark_changed();
|
||||
}
|
||||
let fill = if *value {
|
||||
palette.accent_dark
|
||||
} else {
|
||||
palette.control
|
||||
};
|
||||
let stroke = if *value {
|
||||
palette.accent
|
||||
} else {
|
||||
palette.border_strong
|
||||
};
|
||||
ui.painter().rect(
|
||||
rect,
|
||||
8.0,
|
||||
fill,
|
||||
egui::Stroke::new(1.0_f32, stroke),
|
||||
egui::StrokeKind::Inside,
|
||||
);
|
||||
let x = if *value {
|
||||
rect.right() - 8.0
|
||||
} else {
|
||||
rect.left() + 8.0
|
||||
};
|
||||
ui.painter()
|
||||
.circle_filled(egui::pos2(x, rect.center().y), 5.0, palette.text_primary);
|
||||
response
|
||||
}
|
||||
|
||||
/// Fixed 128×24 two-option control used by the Penpot material Surface section.
|
||||
///
|
||||
/// Returning the selected side keeps the control independent from material state and prevents
|
||||
/// stock `selectable_label` padding from changing its geometry.
|
||||
pub fn two_option_segmented(
|
||||
ui: &mut egui::Ui,
|
||||
left_label: &str,
|
||||
right_label: &str,
|
||||
right_selected: bool,
|
||||
) -> Option<bool> {
|
||||
const WIDTH: f32 = 128.0;
|
||||
const HEIGHT: f32 = 24.0;
|
||||
const OPTION_WIDTH: f32 = WIDTH * 0.5;
|
||||
|
||||
let palette = palette(ui);
|
||||
let (rect, _) = ui.allocate_exact_size(egui::vec2(WIDTH, HEIGHT), egui::Sense::hover());
|
||||
ui.painter().rect(
|
||||
rect,
|
||||
4.0,
|
||||
palette.control,
|
||||
egui::Stroke::new(1.0_f32, palette.border),
|
||||
egui::StrokeKind::Inside,
|
||||
);
|
||||
let left = egui::Rect::from_min_size(rect.min, egui::vec2(OPTION_WIDTH, HEIGHT));
|
||||
let right = egui::Rect::from_min_size(
|
||||
rect.min + egui::vec2(OPTION_WIDTH, 0.0),
|
||||
egui::vec2(OPTION_WIDTH, HEIGHT),
|
||||
);
|
||||
let mut selection = None;
|
||||
for (option_rect, label, selected, value) in [
|
||||
(left, left_label, !right_selected, false),
|
||||
(right, right_label, right_selected, true),
|
||||
] {
|
||||
let response = ui.interact(
|
||||
option_rect,
|
||||
ui.make_persistent_id(("two_option_segment", label)),
|
||||
egui::Sense::click(),
|
||||
);
|
||||
let fill = if selected {
|
||||
palette.accent_dark
|
||||
} else if response.hovered() {
|
||||
palette.elevated
|
||||
} else {
|
||||
palette.control
|
||||
};
|
||||
ui.painter().rect_filled(option_rect.shrink(1.0), 3.0, fill);
|
||||
if selected {
|
||||
ui.painter().rect_stroke(
|
||||
option_rect,
|
||||
3.0,
|
||||
egui::Stroke::new(1.0_f32, palette.accent),
|
||||
egui::StrokeKind::Inside,
|
||||
);
|
||||
}
|
||||
ui.painter().text(
|
||||
option_rect.center(),
|
||||
egui::Align2::CENTER_CENTER,
|
||||
label,
|
||||
TypeRole::Control.font(),
|
||||
if selected {
|
||||
palette.text_primary
|
||||
} else {
|
||||
palette.text_secondary
|
||||
},
|
||||
);
|
||||
if response.clicked() && right_selected != value {
|
||||
selection = Some(value);
|
||||
}
|
||||
}
|
||||
selection
|
||||
}
|
||||
|
||||
/// Exact Penpot scalar editor used by material inputs.
|
||||
///
|
||||
/// The track and numeric field are painted as independent controls so egui's stock slider
|
||||
/// padding cannot move the thumb into the value field at the reference width.
|
||||
pub fn scalar_control(
|
||||
ui: &mut egui::Ui,
|
||||
salt: impl std::hash::Hash,
|
||||
value: &mut f32,
|
||||
range: RangeInclusive<f32>,
|
||||
max_decimals: usize,
|
||||
) -> egui::Response {
|
||||
let palette = palette(ui);
|
||||
let before = *value;
|
||||
// The final Penpot component deliberately stretches only the track at the compact
|
||||
// breakpoint: 93.8 px at the 569 px reference and 160.3 px at the 369 px reference.
|
||||
// The numeric field remains a stable 33 px in both modes, after a six-pixel leading inset
|
||||
// and a six-pixel track-to-number gap.
|
||||
let width = ui.available_width().max(1.0);
|
||||
let (rect, base_response) =
|
||||
ui.allocate_exact_size(egui::vec2(width, 22.0), egui::Sense::hover());
|
||||
let number_width = SCALAR_NUMBER_WIDTH.min(width);
|
||||
let number_x = (width - number_width).max(0.0);
|
||||
let track_width = (number_x - SCALAR_TRACK_X - SCALAR_NUMBER_GAP).max(1.0);
|
||||
let slider_rect = egui::Rect::from_min_size(
|
||||
rect.min + egui::vec2(SCALAR_TRACK_X, 6.0),
|
||||
egui::vec2(track_width, SCALAR_TRACK_INTERACTION_HEIGHT),
|
||||
);
|
||||
let track_rect =
|
||||
egui::Rect::from_center_size(slider_rect.center(), egui::vec2(track_width, 3.0));
|
||||
let slider_response = ui.interact(
|
||||
slider_rect,
|
||||
ui.make_persistent_id(("penpot_scalar", salt)),
|
||||
egui::Sense::click_and_drag(),
|
||||
);
|
||||
if slider_response.clicked() || slider_response.dragged() {
|
||||
if let Some(pointer) = slider_response.interact_pointer_pos() {
|
||||
let start = *range.start();
|
||||
let end = *range.end();
|
||||
let normalized = ((pointer.x - track_rect.left()) / track_rect.width()).clamp(0.0, 1.0);
|
||||
*value = egui::lerp(start..=end, normalized);
|
||||
}
|
||||
}
|
||||
|
||||
let start = *range.start();
|
||||
let end = *range.end();
|
||||
let normalized = if end > start {
|
||||
((*value - start) / (end - start)).clamp(0.0, 1.0)
|
||||
} else {
|
||||
0.0
|
||||
};
|
||||
ui.painter().rect_filled(track_rect, 2.0, palette.border);
|
||||
let fill = egui::Rect::from_min_max(
|
||||
track_rect.left_top(),
|
||||
egui::pos2(
|
||||
egui::lerp(track_rect.x_range(), normalized),
|
||||
track_rect.bottom(),
|
||||
),
|
||||
);
|
||||
ui.painter().rect_filled(fill, 2.0, palette.accent);
|
||||
let thumb_center = egui::pos2(
|
||||
egui::lerp(track_rect.x_range(), normalized),
|
||||
track_rect.center().y,
|
||||
);
|
||||
ui.painter().circle(
|
||||
thumb_center,
|
||||
SCALAR_THUMB_RADIUS,
|
||||
palette.text_primary,
|
||||
egui::Stroke::new(1.0_f32, palette.accent),
|
||||
);
|
||||
|
||||
let number_rect = egui::Rect::from_min_size(
|
||||
rect.min + egui::vec2(number_x, 0.0),
|
||||
egui::vec2(number_width, 22.0),
|
||||
);
|
||||
let number_response = ui.put(
|
||||
number_rect,
|
||||
egui::DragValue::new(value)
|
||||
.speed(0.01)
|
||||
.range(range)
|
||||
.max_decimals(max_decimals),
|
||||
);
|
||||
let mut response = base_response.union(slider_response).union(number_response);
|
||||
if *value != before {
|
||||
response.mark_changed();
|
||||
}
|
||||
response
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod scalar_tests {
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn penpot_scalar_geometry_matches_the_current_export() {
|
||||
let wide_width = 138.8;
|
||||
let wide_number_x = wide_width - SCALAR_NUMBER_WIDTH;
|
||||
let wide_track = wide_number_x - SCALAR_TRACK_X - SCALAR_NUMBER_GAP;
|
||||
assert!((wide_track - 93.8).abs() < 0.001);
|
||||
|
||||
let compact_width = 205.3;
|
||||
let compact_number_x = compact_width - SCALAR_NUMBER_WIDTH;
|
||||
let compact_track = compact_number_x - SCALAR_TRACK_X - SCALAR_NUMBER_GAP;
|
||||
assert!((compact_track - 160.3).abs() < 0.001);
|
||||
assert_eq!(SCALAR_TRACK_INTERACTION_HEIGHT, 10.0);
|
||||
assert_eq!(SCALAR_THUMB_RADIUS, 4.0);
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod segmented_tests {
|
||||
#[test]
|
||||
fn penpot_segmented_control_has_two_fixed_halves() {
|
||||
const WIDTH: f32 = 128.0;
|
||||
const OPTION_WIDTH: f32 = WIDTH * 0.5;
|
||||
assert_eq!(OPTION_WIDTH, 64.0);
|
||||
assert_eq!(OPTION_WIDTH * 2.0, WIDTH);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,153 @@
|
||||
//! Penpot-led editor design-system primitives.
|
||||
//!
|
||||
//! The first consumer is the Material Slot panel. These semantic tokens and controls are kept
|
||||
//! independent from material/world state so later editor panels can migrate without copying style.
|
||||
|
||||
pub mod color_picker;
|
||||
pub mod controls;
|
||||
pub mod property_grid;
|
||||
pub mod typography;
|
||||
|
||||
use egui::{self, Color32, CornerRadius, Stroke};
|
||||
|
||||
use crate::theme::EditorVisualPalette;
|
||||
|
||||
pub const REFERENCE_WIDTH: f32 = 620.0;
|
||||
pub const INSPECTOR_MIN_WIDTH: f32 = 420.0;
|
||||
pub const OUTER_PADDING: f32 = 12.0;
|
||||
pub const SECTION_GAP: f32 = 8.0;
|
||||
pub const MATERIALS_HEADING_HEIGHT: f32 = 32.0;
|
||||
pub const HEADER_HEIGHT: f32 = 82.0;
|
||||
pub const COLLAPSED_HEADER_HEIGHT: f32 = 52.0;
|
||||
pub const MATERIAL_PREVIEW_SIZE: f32 = 64.0;
|
||||
pub const MATERIAL_IDENTITY_WIDTH: f32 = 229.5;
|
||||
pub const SURFACE_SECTION_HEIGHT: f32 = 46.0;
|
||||
pub const COMPACT_SURFACE_SECTION_HEIGHT: f32 = 46.0;
|
||||
pub const INPUT_SECTION_HEADER_HEIGHT: f32 = 24.0;
|
||||
pub const PARAMETER_ROW_HEIGHT: f32 = 32.0;
|
||||
pub const COMPACT_PARAMETER_ROW_HEIGHT: f32 = 58.0;
|
||||
pub const UV_SECTION_HEIGHT: f32 = 54.0;
|
||||
pub const COMPACT_UV_SECTION_HEIGHT: f32 = 94.0;
|
||||
pub const ADVANCED_COLLAPSED_HEIGHT: f32 = 30.0;
|
||||
pub const ADVANCED_EXPANDED_HEIGHT: f32 = 178.0;
|
||||
pub const CONTROL_HEIGHT: f32 = 24.0;
|
||||
|
||||
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
|
||||
pub struct DesignPalette {
|
||||
pub accent: Color32,
|
||||
pub accent_dark: Color32,
|
||||
pub panel: Color32,
|
||||
pub section: Color32,
|
||||
pub recessed: Color32,
|
||||
pub control: Color32,
|
||||
pub elevated: Color32,
|
||||
pub row_even: Color32,
|
||||
pub row_odd: Color32,
|
||||
pub checker: Color32,
|
||||
pub border: Color32,
|
||||
pub border_strong: Color32,
|
||||
pub text_primary: Color32,
|
||||
pub text_secondary: Color32,
|
||||
pub text_muted: Color32,
|
||||
pub healthy: Color32,
|
||||
pub warning: Color32,
|
||||
pub error: Color32,
|
||||
}
|
||||
|
||||
impl From<EditorVisualPalette> for DesignPalette {
|
||||
fn from(value: EditorVisualPalette) -> Self {
|
||||
Self {
|
||||
accent: value.selection,
|
||||
accent_dark: value.selection_bg,
|
||||
panel: value.panel,
|
||||
section: value.widget,
|
||||
recessed: value.panel_dark,
|
||||
control: value.widget,
|
||||
elevated: value.elevated,
|
||||
row_even: value.panel,
|
||||
row_odd: value.widget,
|
||||
checker: value.elevated,
|
||||
border: value.border,
|
||||
border_strong: value.border_strong,
|
||||
text_primary: value.text,
|
||||
text_secondary: value.text_dim,
|
||||
text_muted: value.text_muted,
|
||||
healthy: value.success,
|
||||
warning: value.warning,
|
||||
error: value.error,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
pub fn palette(ui: &egui::Ui) -> DesignPalette {
|
||||
crate::theme::editor_palette(ui.ctx()).into()
|
||||
}
|
||||
|
||||
/// Applies the Penpot material-panel visual language locally without restyling the whole editor.
|
||||
pub fn scope<R>(ui: &mut egui::Ui, add_contents: impl FnOnce(&mut egui::Ui) -> R) -> R {
|
||||
let palette = palette(ui);
|
||||
ui.scope(|ui| {
|
||||
let style = ui.style_mut();
|
||||
style.spacing.item_spacing = egui::vec2(8.0, 4.0);
|
||||
style.spacing.button_padding = egui::vec2(8.0, 3.0);
|
||||
style.spacing.interact_size = egui::vec2(31.0, CONTROL_HEIGHT);
|
||||
style.visuals.widgets.noninteractive.bg_fill = palette.section;
|
||||
style.visuals.widgets.noninteractive.bg_stroke = Stroke::new(1.0_f32, palette.border);
|
||||
style.visuals.widgets.noninteractive.fg_stroke =
|
||||
Stroke::new(1.0_f32, palette.text_secondary);
|
||||
style.visuals.widgets.inactive.bg_fill = palette.control;
|
||||
style.visuals.widgets.inactive.weak_bg_fill = palette.control;
|
||||
style.visuals.widgets.inactive.bg_stroke = Stroke::new(1.0_f32, palette.border);
|
||||
style.visuals.widgets.inactive.fg_stroke = Stroke::new(1.0_f32, palette.text_primary);
|
||||
style.visuals.widgets.hovered.bg_fill = palette.elevated;
|
||||
style.visuals.widgets.hovered.weak_bg_fill = palette.elevated;
|
||||
style.visuals.widgets.hovered.bg_stroke = Stroke::new(1.0_f32, palette.border_strong);
|
||||
style.visuals.widgets.hovered.fg_stroke = Stroke::new(1.0_f32, palette.text_primary);
|
||||
style.visuals.widgets.active.bg_fill = palette.accent_dark;
|
||||
style.visuals.widgets.active.weak_bg_fill = palette.accent_dark;
|
||||
style.visuals.widgets.active.bg_stroke = Stroke::new(1.0_f32, palette.accent);
|
||||
style.visuals.widgets.active.fg_stroke = Stroke::new(1.0_f32, palette.text_primary);
|
||||
style.visuals.selection.bg_fill = palette.accent_dark;
|
||||
style.visuals.selection.stroke = Stroke::new(1.0_f32, palette.accent);
|
||||
style.visuals.window_fill = palette.panel;
|
||||
style.visuals.window_stroke = Stroke::new(1.0_f32, palette.border_strong);
|
||||
style.visuals.window_corner_radius = CornerRadius::same(7);
|
||||
style.visuals.menu_corner_radius = CornerRadius::same(5);
|
||||
style.visuals.override_text_color = Some(palette.text_primary);
|
||||
typography::install_local_text_styles(style);
|
||||
add_contents(ui)
|
||||
})
|
||||
.inner
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn penpot_geometry_tokens_are_exact() {
|
||||
assert_eq!(REFERENCE_WIDTH, 620.0);
|
||||
assert_eq!(MATERIALS_HEADING_HEIGHT, 32.0);
|
||||
assert_eq!(HEADER_HEIGHT, 82.0);
|
||||
assert_eq!(COLLAPSED_HEADER_HEIGHT, 52.0);
|
||||
assert_eq!(MATERIAL_PREVIEW_SIZE, 64.0);
|
||||
assert_eq!(MATERIAL_IDENTITY_WIDTH, 229.5);
|
||||
assert_eq!(SURFACE_SECTION_HEIGHT, 46.0);
|
||||
assert_eq!(COMPACT_SURFACE_SECTION_HEIGHT, 46.0);
|
||||
assert_eq!(INPUT_SECTION_HEADER_HEIGHT, 24.0);
|
||||
assert_eq!(PARAMETER_ROW_HEIGHT, 32.0);
|
||||
assert_eq!(COMPACT_PARAMETER_ROW_HEIGHT, 58.0);
|
||||
assert_eq!(UV_SECTION_HEIGHT, 54.0);
|
||||
assert_eq!(COMPACT_UV_SECTION_HEIGHT, 94.0);
|
||||
assert_eq!(ADVANCED_COLLAPSED_HEIGHT, 30.0);
|
||||
assert_eq!(ADVANCED_EXPANDED_HEIGHT, 178.0);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn material_design_palette_uses_blacksite_semantics() {
|
||||
let palette = DesignPalette::from(crate::theme::BLACKSITE_PALETTE);
|
||||
assert_eq!(palette.accent, crate::theme::SELECTION);
|
||||
assert_eq!(palette.panel, crate::theme::PANEL_BG);
|
||||
assert_eq!(palette.text_primary, crate::theme::TEXT);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,294 @@
|
||||
//! Testable geometry for dense Penpot material property rows.
|
||||
|
||||
use super::{COMPACT_PARAMETER_ROW_HEIGHT, PARAMETER_ROW_HEIGHT};
|
||||
use egui;
|
||||
|
||||
/// Minimum live section width that can safely retain the exported wide-row geometry.
|
||||
///
|
||||
/// The Penpot reference section itself is 569 px wide. In the native Inspector, dock chrome,
|
||||
/// component-card borders, and the floating scrollbar consume up to ten pixels before the
|
||||
/// material parameter body is allocated. Treat that 559 px contained canvas as wide so a 640 px
|
||||
/// Inspector renders the authoritative wide reference instead of incorrectly switching to the
|
||||
/// 420 px two-line rows.
|
||||
pub const WIDE_SECTION_WIDTH: f32 = 559.0;
|
||||
pub const RESPONSIVE_BREAKPOINT: f32 = WIDE_SECTION_WIDTH;
|
||||
/// The actor component chrome can consume up to twelve pixels of the exported 372 px compact
|
||||
/// canvas. At 360 px the complete texture row still fits: 12 px inset + 336 px group + 12 px inset.
|
||||
const COMPACT_INLINE_ACTION_FIT_WIDTH: f32 = 357.0;
|
||||
|
||||
#[derive(Debug, Clone, Copy, PartialEq)]
|
||||
pub struct PropertyGridGeometry {
|
||||
pub stacked: bool,
|
||||
pub row_height: f32,
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, Copy, PartialEq)]
|
||||
pub struct PropertyRowRects {
|
||||
pub row: egui::Rect,
|
||||
pub label: egui::Rect,
|
||||
pub value: egui::Rect,
|
||||
pub color_value: egui::Rect,
|
||||
pub channel: egui::Rect,
|
||||
pub texture_group: egui::Rect,
|
||||
pub texture_field: egui::Rect,
|
||||
pub locate: egui::Rect,
|
||||
pub clear: egui::Rect,
|
||||
pub inline_texture_actions: bool,
|
||||
}
|
||||
|
||||
impl PropertyGridGeometry {
|
||||
pub fn for_width(section_width: f32) -> Self {
|
||||
if section_width + f32::EPSILON >= RESPONSIVE_BREAKPOINT {
|
||||
Self {
|
||||
stacked: false,
|
||||
row_height: PARAMETER_ROW_HEIGHT,
|
||||
}
|
||||
} else {
|
||||
Self {
|
||||
stacked: true,
|
||||
row_height: COMPACT_PARAMETER_ROW_HEIGHT,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
pub fn row_rects(self, row: egui::Rect) -> PropertyRowRects {
|
||||
let inset = 12.0_f32.min(row.width() * 0.5);
|
||||
let inner_width = (row.width() - inset * 2.0).max(1.0);
|
||||
if !self.stacked {
|
||||
let texture_group_width = (inner_width - 286.5).max(60.0);
|
||||
let texture_field_width = (texture_group_width - 60.0).max(1.0);
|
||||
let texture_group = egui::Rect::from_min_size(
|
||||
row.min + egui::vec2(298.5, 5.0),
|
||||
egui::vec2(texture_group_width, 22.0),
|
||||
);
|
||||
return PropertyRowRects {
|
||||
row,
|
||||
label: egui::Rect::from_min_size(
|
||||
row.min + egui::vec2(12.0, 5.0),
|
||||
egui::vec2(82.0, 22.0),
|
||||
),
|
||||
value: egui::Rect::from_min_size(
|
||||
row.min + egui::vec2(103.35, 5.0),
|
||||
egui::vec2(138.8, 22.0),
|
||||
),
|
||||
color_value: egui::Rect::from_min_size(
|
||||
row.min + egui::vec2(107.95, 5.0),
|
||||
egui::vec2(182.55, 22.0),
|
||||
),
|
||||
channel: egui::Rect::from_min_size(
|
||||
row.min + egui::vec2(242.5, 5.0),
|
||||
egui::vec2(48.0, 22.0),
|
||||
),
|
||||
texture_group,
|
||||
texture_field: egui::Rect::from_min_size(
|
||||
texture_group.min,
|
||||
egui::vec2(texture_field_width, 22.0),
|
||||
),
|
||||
locate: egui::Rect::from_min_size(
|
||||
texture_group.min + egui::vec2(texture_field_width + 6.0, 0.0),
|
||||
egui::vec2(24.0, 22.0),
|
||||
),
|
||||
clear: egui::Rect::from_min_size(
|
||||
texture_group.min + egui::vec2(texture_field_width + 36.0, 0.0),
|
||||
egui::vec2(24.0, 22.0),
|
||||
),
|
||||
inline_texture_actions: true,
|
||||
};
|
||||
}
|
||||
|
||||
let channel_width = 48.0_f32.min(inner_width);
|
||||
let channel_x = inset + inner_width - channel_width;
|
||||
let value_x = (inset + 91.35).min(channel_x);
|
||||
// The scalar's visible children finish 0.35 px before the channel. Penpot's transparent
|
||||
// parent frame is six pixels narrower and is not the actual clipping boundary.
|
||||
let value_width = (channel_x - value_x - 0.35).max(1.0);
|
||||
let color_value_x = (inset + 95.95).min(channel_x);
|
||||
let color_value_width = (inset + inner_width - color_value_x).max(1.0);
|
||||
let texture_group = egui::Rect::from_min_size(
|
||||
row.min + egui::vec2(inset, 31.0),
|
||||
egui::vec2(inner_width, 22.0),
|
||||
);
|
||||
let inline_texture_actions = row.width() + f32::EPSILON >= COMPACT_INLINE_ACTION_FIT_WIDTH;
|
||||
let texture_field_width = if inline_texture_actions {
|
||||
(inner_width - 60.0).max(1.0)
|
||||
} else {
|
||||
(inner_width - 30.0).max(1.0)
|
||||
};
|
||||
let overflow_or_locate_x = texture_field_width + 6.0;
|
||||
PropertyRowRects {
|
||||
row,
|
||||
label: egui::Rect::from_min_size(
|
||||
row.min + egui::vec2(inset, 5.0),
|
||||
egui::vec2(78.0_f32.min(inner_width), 22.0),
|
||||
),
|
||||
value: egui::Rect::from_min_size(
|
||||
row.min + egui::vec2(value_x, 5.0),
|
||||
egui::vec2(value_width, 22.0),
|
||||
),
|
||||
color_value: egui::Rect::from_min_size(
|
||||
row.min + egui::vec2(color_value_x, 5.0),
|
||||
egui::vec2(color_value_width, 22.0),
|
||||
),
|
||||
channel: egui::Rect::from_min_size(
|
||||
row.min + egui::vec2(channel_x, 5.0),
|
||||
egui::vec2(channel_width, 22.0),
|
||||
),
|
||||
texture_group,
|
||||
texture_field: egui::Rect::from_min_size(
|
||||
texture_group.min,
|
||||
egui::vec2(texture_field_width, 22.0),
|
||||
),
|
||||
locate: egui::Rect::from_min_size(
|
||||
texture_group.min + egui::vec2(overflow_or_locate_x, 0.0),
|
||||
egui::vec2(24.0, 22.0),
|
||||
),
|
||||
clear: egui::Rect::from_min_size(
|
||||
texture_group.min
|
||||
+ egui::vec2(
|
||||
if inline_texture_actions {
|
||||
texture_field_width + 36.0
|
||||
} else {
|
||||
inner_width
|
||||
},
|
||||
0.0,
|
||||
),
|
||||
egui::vec2(if inline_texture_actions { 24.0 } else { 0.0 }, 22.0),
|
||||
),
|
||||
inline_texture_actions,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn penpot_exact_reference_geometry_matches_columns() {
|
||||
let geometry = PropertyGridGeometry::for_width(569.0);
|
||||
assert!(!geometry.stacked);
|
||||
assert_eq!(geometry.row_height, 32.0);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn native_wide_containment_threshold_keeps_reference_rows() {
|
||||
let geometry = PropertyGridGeometry::for_width(559.0);
|
||||
assert!(!geometry.stacked);
|
||||
assert_eq!(geometry.row_height, 32.0);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn below_native_wide_containment_threshold_reflows_without_compression() {
|
||||
let geometry = PropertyGridGeometry::for_width(558.0);
|
||||
assert!(geometry.stacked);
|
||||
assert_eq!(geometry.row_height, 58.0);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn row_rects_match_exported_wide_geometry() {
|
||||
let row = egui::Rect::from_min_size(egui::Pos2::ZERO, egui::vec2(569.0, 32.0));
|
||||
let rects = PropertyGridGeometry::for_width(569.0).row_rects(row);
|
||||
assert_eq!(rects.label.min, egui::pos2(12.0, 5.0));
|
||||
assert_eq!(rects.value.min, egui::pos2(103.35, 5.0));
|
||||
assert!((rects.value.width() - 138.8).abs() < 0.001);
|
||||
assert_eq!(rects.value.height(), 22.0);
|
||||
assert_eq!(rects.color_value.min, egui::pos2(107.95, 5.0));
|
||||
assert!((rects.color_value.width() - 182.55).abs() < 0.001);
|
||||
assert_eq!(
|
||||
rects.channel,
|
||||
egui::Rect::from_min_size(egui::pos2(242.5, 5.0), egui::vec2(48.0, 22.0))
|
||||
);
|
||||
assert_eq!(
|
||||
rects.texture_group,
|
||||
egui::Rect::from_min_size(egui::pos2(298.5, 5.0), egui::vec2(258.5, 22.0))
|
||||
);
|
||||
assert_eq!(rects.texture_field.size(), egui::vec2(198.5, 22.0));
|
||||
assert_eq!(rects.locate.min, egui::pos2(503.0, 5.0));
|
||||
assert_eq!(rects.clear.min, egui::pos2(533.0, 5.0));
|
||||
assert!(rects.inline_texture_actions);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn row_rects_match_exported_compact_geometry() {
|
||||
let row = egui::Rect::from_min_size(egui::Pos2::ZERO, egui::vec2(369.0, 58.0));
|
||||
let rects = PropertyGridGeometry::for_width(369.0).row_rects(row);
|
||||
assert_eq!(rects.label.min, egui::pos2(12.0, 5.0));
|
||||
assert_eq!(rects.value.min, egui::pos2(103.35, 5.0));
|
||||
assert!((rects.value.width() - 205.3).abs() < 0.001);
|
||||
assert_eq!(rects.color_value.min, egui::pos2(107.95, 5.0));
|
||||
assert!((rects.color_value.width() - 249.05).abs() < 0.001);
|
||||
assert_eq!(
|
||||
rects.channel,
|
||||
egui::Rect::from_min_size(egui::pos2(309.0, 5.0), egui::vec2(48.0, 22.0))
|
||||
);
|
||||
assert_eq!(
|
||||
rects.texture_group,
|
||||
egui::Rect::from_min_size(egui::pos2(12.0, 31.0), egui::vec2(345.0, 22.0))
|
||||
);
|
||||
assert_eq!(rects.texture_field.size(), egui::vec2(285.0, 22.0));
|
||||
assert_eq!(rects.locate.min, egui::pos2(303.0, 31.0));
|
||||
assert_eq!(rects.clear.min, egui::pos2(333.0, 31.0));
|
||||
assert!(rects.inline_texture_actions);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn transient_row_rects_are_finite_and_contained() {
|
||||
for width in [356.0, 300.0, 240.0] {
|
||||
let row = egui::Rect::from_min_size(egui::Pos2::ZERO, egui::vec2(width, 58.0));
|
||||
let rects = PropertyGridGeometry::for_width(width).row_rects(row);
|
||||
for rect in [
|
||||
rects.label,
|
||||
rects.value,
|
||||
rects.color_value,
|
||||
rects.channel,
|
||||
rects.texture_group,
|
||||
rects.texture_field,
|
||||
rects.locate,
|
||||
rects.clear,
|
||||
] {
|
||||
assert!(rect.is_finite());
|
||||
assert!(row.contains_rect(rect));
|
||||
}
|
||||
assert!(!rects.inline_texture_actions);
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn inspector_chrome_reduced_floor_keeps_compact_texture_actions() {
|
||||
let row = egui::Rect::from_min_size(egui::Pos2::ZERO, egui::vec2(363.0, 58.0));
|
||||
let rects = PropertyGridGeometry::for_width(363.0).row_rects(row);
|
||||
assert!(rects.inline_texture_actions);
|
||||
assert_eq!(rects.texture_group.min, egui::pos2(12.0, 31.0));
|
||||
assert_eq!(rects.texture_group.max, egui::pos2(351.0, 53.0));
|
||||
assert!(row.contains_rect(rects.locate));
|
||||
assert!(row.contains_rect(rects.clear));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn penpot_wide_growth_only_expands_texture_field() {
|
||||
let reference_row = egui::Rect::from_min_size(egui::Pos2::ZERO, egui::vec2(569.0, 32.0));
|
||||
let wide_row = egui::Rect::from_min_size(egui::Pos2::ZERO, egui::vec2(669.0, 32.0));
|
||||
let reference = PropertyGridGeometry::for_width(569.0).row_rects(reference_row);
|
||||
let wide = PropertyGridGeometry::for_width(669.0).row_rects(wide_row);
|
||||
assert_eq!(wide.label, reference.label);
|
||||
assert_eq!(wide.value, reference.value);
|
||||
assert_eq!(wide.color_value, reference.color_value);
|
||||
assert_eq!(wide.channel, reference.channel);
|
||||
assert_eq!(
|
||||
wide.texture_field.width(),
|
||||
reference.texture_field.width() + 100.0
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn penpot_very_narrow_first_line_never_exceeds_inner_width() {
|
||||
let geometry = PropertyGridGeometry::for_width(300.0);
|
||||
assert!(geometry.stacked);
|
||||
let row = egui::Rect::from_min_size(egui::Pos2::ZERO, egui::vec2(300.0, 58.0));
|
||||
let rects = geometry.row_rects(row);
|
||||
assert!(row.contains_rect(rects.label));
|
||||
assert!(row.contains_rect(rects.value));
|
||||
assert!(row.contains_rect(rects.channel));
|
||||
assert_eq!(rects.texture_group.width(), 276.0);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,94 @@
|
||||
//! Source Sans typography roles used by the Penpot-led editor visual system.
|
||||
|
||||
use egui::{self, FontFamily, FontId, RichText, Style, TextStyle};
|
||||
|
||||
use crate::fonts::{SOURCE_SANS_BOLD, SOURCE_SANS_REGULAR};
|
||||
|
||||
#[derive(Debug, Clone, Copy, PartialEq)]
|
||||
pub enum TypeRole {
|
||||
Caption,
|
||||
Eyebrow,
|
||||
Small,
|
||||
Body,
|
||||
Control,
|
||||
Section,
|
||||
AssetLabel,
|
||||
AssetTitle,
|
||||
Title,
|
||||
}
|
||||
|
||||
impl TypeRole {
|
||||
pub const fn size(self) -> f32 {
|
||||
match self {
|
||||
Self::Caption | Self::Eyebrow => 9.0,
|
||||
Self::Small => 10.0,
|
||||
Self::Body => 11.0,
|
||||
Self::Control | Self::AssetLabel => 10.0,
|
||||
Self::Section => 11.0,
|
||||
Self::AssetTitle => 13.0,
|
||||
Self::Title => 14.0,
|
||||
}
|
||||
}
|
||||
|
||||
pub const fn bold(self) -> bool {
|
||||
matches!(
|
||||
self,
|
||||
Self::Eyebrow | Self::Section | Self::AssetLabel | Self::AssetTitle | Self::Title
|
||||
)
|
||||
}
|
||||
|
||||
pub fn font(self) -> FontId {
|
||||
let family = if self.bold() {
|
||||
SOURCE_SANS_BOLD
|
||||
} else {
|
||||
SOURCE_SANS_REGULAR
|
||||
};
|
||||
FontId::new(self.size(), FontFamily::Name(family.into()))
|
||||
}
|
||||
|
||||
pub fn text(self, value: impl Into<String>) -> RichText {
|
||||
RichText::new(value).font(self.font())
|
||||
}
|
||||
}
|
||||
|
||||
pub fn install_local_text_styles(style: &mut Style) {
|
||||
style
|
||||
.text_styles
|
||||
.insert(TextStyle::Body, TypeRole::Body.font());
|
||||
style
|
||||
.text_styles
|
||||
.insert(TextStyle::Button, TypeRole::Control.font());
|
||||
style
|
||||
.text_styles
|
||||
.insert(TextStyle::Small, TypeRole::Small.font());
|
||||
style
|
||||
.text_styles
|
||||
.insert(TextStyle::Heading, TypeRole::Title.font());
|
||||
style.text_styles.insert(
|
||||
TextStyle::Monospace,
|
||||
FontId::new(11.0, egui::FontFamily::Monospace),
|
||||
);
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn penpot_type_scale_and_weights_are_stable() {
|
||||
assert_eq!(TypeRole::Caption.size(), 9.0);
|
||||
assert_eq!(TypeRole::Eyebrow.size(), 9.0);
|
||||
assert_eq!(TypeRole::Small.size(), 10.0);
|
||||
assert_eq!(TypeRole::Body.size(), 11.0);
|
||||
assert_eq!(TypeRole::Control.size(), 10.0);
|
||||
assert_eq!(TypeRole::Section.size(), 11.0);
|
||||
assert_eq!(TypeRole::AssetLabel.size(), 10.0);
|
||||
assert_eq!(TypeRole::AssetTitle.size(), 13.0);
|
||||
assert_eq!(TypeRole::Title.size(), 14.0);
|
||||
assert!(!TypeRole::Body.bold());
|
||||
assert!(TypeRole::Eyebrow.bold());
|
||||
assert!(TypeRole::Section.bold());
|
||||
assert!(TypeRole::AssetLabel.bold());
|
||||
assert!(TypeRole::AssetTitle.bold());
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,54 @@
|
||||
//! Source Sans Pro and Phosphor font registration for every Blacksite egui host.
|
||||
|
||||
use std::sync::Arc;
|
||||
|
||||
pub const SOURCE_SANS_REGULAR: &str = "blacksite-source-sans-regular";
|
||||
pub const SOURCE_SANS_BOLD: &str = "blacksite-source-sans-bold";
|
||||
|
||||
pub fn font_definitions() -> egui::FontDefinitions {
|
||||
let mut fonts = egui::FontDefinitions::default();
|
||||
egui_phosphor_icons::add_fonts(&mut fonts);
|
||||
fonts.font_data.insert(
|
||||
SOURCE_SANS_REGULAR.to_owned(),
|
||||
Arc::new(egui::FontData::from_static(include_bytes!(
|
||||
"../assets/fonts/source-sans/SourceSansPro-Regular.ttf"
|
||||
))),
|
||||
);
|
||||
fonts.font_data.insert(
|
||||
SOURCE_SANS_BOLD.to_owned(),
|
||||
Arc::new(egui::FontData::from_static(include_bytes!(
|
||||
"../assets/fonts/source-sans/SourceSansPro-Bold.ttf"
|
||||
))),
|
||||
);
|
||||
fonts
|
||||
.families
|
||||
.entry(egui::FontFamily::Proportional)
|
||||
.or_default()
|
||||
.insert(0, SOURCE_SANS_REGULAR.to_owned());
|
||||
fonts.families.insert(
|
||||
egui::FontFamily::Name(SOURCE_SANS_REGULAR.into()),
|
||||
vec![SOURCE_SANS_REGULAR.to_owned()],
|
||||
);
|
||||
fonts.families.insert(
|
||||
egui::FontFamily::Name(SOURCE_SANS_BOLD.into()),
|
||||
vec![SOURCE_SANS_BOLD.to_owned(), SOURCE_SANS_REGULAR.to_owned()],
|
||||
);
|
||||
let fallbacks = fonts
|
||||
.families
|
||||
.get(&egui::FontFamily::Proportional)
|
||||
.cloned()
|
||||
.unwrap_or_default();
|
||||
for (family, font_names) in &mut fonts.families {
|
||||
let egui::FontFamily::Name(name) = family else {
|
||||
continue;
|
||||
};
|
||||
if name.starts_with("phosphor-") {
|
||||
for fallback in &fallbacks {
|
||||
if !font_names.contains(fallback) {
|
||||
font_names.push(fallback.clone());
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
fonts
|
||||
}
|
||||
@@ -0,0 +1,262 @@
|
||||
//! Action-returning Inspector component-card chrome shared by production and gallery fixtures.
|
||||
|
||||
use egui;
|
||||
use egui_phosphor_icons::{icons, Icon};
|
||||
|
||||
use crate::design_system;
|
||||
use crate::design_system::typography::TypeRole;
|
||||
use crate::theme::{BORDER, ERROR, SELECTION, SUCCESS, TEXT, TEXT_DIM, TEXT_MUTED, WIDGET_BG};
|
||||
|
||||
pub const COMPONENT_HEADER_HEIGHT: f32 = 50.0;
|
||||
const COMPONENT_RAIL_X: f32 = 7.0;
|
||||
const COMPONENT_CARET_CENTER_X: f32 = 26.0;
|
||||
const COMPONENT_ICON_CENTER_X: f32 = 51.0;
|
||||
const COMPONENT_IDENTITY_X: f32 = 69.0;
|
||||
const COMPONENT_ACTIONS_WIDTH: f32 = 104.0;
|
||||
|
||||
#[derive(Debug, Clone, Copy)]
|
||||
pub struct ComponentCardOptions {
|
||||
pub type_name: &'static str,
|
||||
pub title: &'static str,
|
||||
pub icon: Icon,
|
||||
pub active_toggle: bool,
|
||||
pub removable: bool,
|
||||
pub reorderable: bool,
|
||||
pub resettable: bool,
|
||||
pub copyable: bool,
|
||||
pub summary: &'static str,
|
||||
pub body_margin: i8,
|
||||
}
|
||||
|
||||
impl ComponentCardOptions {
|
||||
pub const fn removable(type_name: &'static str, title: &'static str, icon: Icon) -> Self {
|
||||
Self {
|
||||
type_name,
|
||||
title,
|
||||
icon,
|
||||
active_toggle: true,
|
||||
removable: true,
|
||||
reorderable: true,
|
||||
resettable: true,
|
||||
copyable: true,
|
||||
summary: "Authoring component",
|
||||
body_margin: 12,
|
||||
}
|
||||
}
|
||||
|
||||
pub const fn fixed(type_name: &'static str, title: &'static str, icon: Icon) -> Self {
|
||||
Self {
|
||||
type_name,
|
||||
title,
|
||||
icon,
|
||||
active_toggle: false,
|
||||
removable: false,
|
||||
reorderable: false,
|
||||
resettable: true,
|
||||
copyable: false,
|
||||
summary: "Authoring component",
|
||||
body_margin: 12,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone)]
|
||||
pub struct ComponentCardViewModel {
|
||||
pub options: ComponentCardOptions,
|
||||
pub active: bool,
|
||||
pub collapsed: bool,
|
||||
pub pasteable: bool,
|
||||
pub can_move_up: bool,
|
||||
pub can_move_down: bool,
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, Default)]
|
||||
pub struct ComponentCardAction {
|
||||
pub type_name: &'static str,
|
||||
pub collapsed: Option<bool>,
|
||||
pub active: Option<bool>,
|
||||
pub reset: bool,
|
||||
pub copy: bool,
|
||||
pub paste: bool,
|
||||
pub move_up: bool,
|
||||
pub move_down: bool,
|
||||
pub remove: bool,
|
||||
}
|
||||
|
||||
pub fn component_card(
|
||||
ui: &mut egui::Ui,
|
||||
view: &ComponentCardViewModel,
|
||||
add_contents: impl FnOnce(&mut egui::Ui),
|
||||
) -> ComponentCardAction {
|
||||
let mut action = ComponentCardAction {
|
||||
type_name: view.options.type_name,
|
||||
..Default::default()
|
||||
};
|
||||
design_system::scope(ui, |ui| {
|
||||
egui::Frame::new()
|
||||
.fill(WIDGET_BG)
|
||||
.stroke(egui::Stroke::new(1.0_f32, BORDER))
|
||||
.corner_radius(egui::CornerRadius::same(5))
|
||||
.show(ui, |ui| {
|
||||
let width = ui.available_width().max(1.0);
|
||||
let (header, response) = ui.allocate_exact_size(
|
||||
egui::vec2(width, COMPONENT_HEADER_HEIGHT),
|
||||
egui::Sense::click(),
|
||||
);
|
||||
ui.painter().rect_filled(
|
||||
egui::Rect::from_min_size(
|
||||
header.min + egui::vec2(COMPONENT_RAIL_X, 7.0),
|
||||
egui::vec2(3.0, 36.0),
|
||||
),
|
||||
2.0,
|
||||
SELECTION,
|
||||
);
|
||||
let caret_rect = egui::Rect::from_center_size(
|
||||
egui::pos2(header.left() + COMPONENT_CARET_CENTER_X, header.center().y),
|
||||
egui::vec2(20.0, 28.0),
|
||||
);
|
||||
if ui
|
||||
.put(
|
||||
caret_rect,
|
||||
egui::Button::new(icon_text(
|
||||
if view.collapsed {
|
||||
icons::CARET_RIGHT
|
||||
} else {
|
||||
icons::CARET_DOWN
|
||||
},
|
||||
12.0,
|
||||
))
|
||||
.frame(false),
|
||||
)
|
||||
.clicked()
|
||||
{
|
||||
action.collapsed = Some(!view.collapsed);
|
||||
}
|
||||
ui.painter().text(
|
||||
egui::pos2(header.left() + COMPONENT_ICON_CENTER_X, header.center().y),
|
||||
egui::Align2::CENTER_CENTER,
|
||||
view.options.icon.as_str(),
|
||||
egui::FontId::new(18.0, egui::FontFamily::Name("phosphor-bold".into())),
|
||||
TEXT_DIM,
|
||||
);
|
||||
ui.painter().text(
|
||||
egui::pos2(header.left() + COMPONENT_IDENTITY_X, header.top() + 18.0),
|
||||
egui::Align2::LEFT_CENTER,
|
||||
view.options.title,
|
||||
TypeRole::Title.font(),
|
||||
TEXT,
|
||||
);
|
||||
ui.painter().text(
|
||||
egui::pos2(header.left() + COMPONENT_IDENTITY_X, header.top() + 34.0),
|
||||
egui::Align2::LEFT_CENTER,
|
||||
view.options.summary,
|
||||
TypeRole::Small.font(),
|
||||
TEXT_MUTED,
|
||||
);
|
||||
let actions_rect = egui::Rect::from_min_size(
|
||||
egui::pos2(
|
||||
header.right() - COMPONENT_ACTIONS_WIDTH - 8.0,
|
||||
header.top() + 11.0,
|
||||
),
|
||||
egui::vec2(COMPONENT_ACTIONS_WIDTH, 28.0),
|
||||
);
|
||||
ui.scope_builder(egui::UiBuilder::new().max_rect(actions_rect), |ui| {
|
||||
ui.with_layout(egui::Layout::right_to_left(egui::Align::Center), |ui| {
|
||||
actions_menu(ui, view, &mut action);
|
||||
let color = if view.active { SUCCESS } else { TEXT_MUTED };
|
||||
let status_rect = ui
|
||||
.allocate_exact_size(egui::vec2(8.0, 14.0), egui::Sense::hover())
|
||||
.0;
|
||||
ui.painter().circle_filled(status_rect.center(), 4.0, color);
|
||||
ui.label(
|
||||
TypeRole::Small
|
||||
.text(if view.active { "Active" } else { "Off" })
|
||||
.color(TEXT_DIM),
|
||||
);
|
||||
});
|
||||
});
|
||||
if response.clicked()
|
||||
&& ui
|
||||
.input(|input| input.pointer.interact_pos())
|
||||
.is_some_and(|point| {
|
||||
!caret_rect.contains(point) && !actions_rect.contains(point)
|
||||
})
|
||||
{
|
||||
action.collapsed = Some(!view.collapsed);
|
||||
}
|
||||
if !view.collapsed {
|
||||
egui::Frame::new()
|
||||
.inner_margin(egui::Margin {
|
||||
left: view.options.body_margin,
|
||||
right: view.options.body_margin,
|
||||
top: 10,
|
||||
bottom: view.options.body_margin,
|
||||
})
|
||||
.show(ui, add_contents);
|
||||
}
|
||||
});
|
||||
});
|
||||
ui.add_space(6.0);
|
||||
action
|
||||
}
|
||||
|
||||
fn actions_menu(
|
||||
ui: &mut egui::Ui,
|
||||
view: &ComponentCardViewModel,
|
||||
action: &mut ComponentCardAction,
|
||||
) {
|
||||
ui.menu_button(
|
||||
icon_text(icons::DOTS_THREE_VERTICAL, 16.0).color(TEXT_DIM),
|
||||
|ui| {
|
||||
ui.set_min_width(160.0);
|
||||
action.reset |= action_button(ui, view.options.resettable, "Reset");
|
||||
action.copy |= action_button(ui, view.options.copyable, "Copy Values");
|
||||
action.paste |= action_button(ui, view.pasteable, "Paste Values");
|
||||
ui.separator();
|
||||
action.move_up |= action_button(ui, view.can_move_up, "Move Up");
|
||||
action.move_down |= action_button(ui, view.can_move_down, "Move Down");
|
||||
ui.separator();
|
||||
ui.add_enabled(false, egui::Button::new("Open Documentation"));
|
||||
if ui
|
||||
.add_enabled(
|
||||
view.options.removable,
|
||||
egui::Button::new(egui::RichText::new("Remove").color(ERROR)),
|
||||
)
|
||||
.clicked()
|
||||
{
|
||||
action.remove = true;
|
||||
ui.close();
|
||||
}
|
||||
},
|
||||
);
|
||||
}
|
||||
|
||||
fn action_button(ui: &mut egui::Ui, enabled: bool, label: &str) -> bool {
|
||||
let clicked = ui.add_enabled(enabled, egui::Button::new(label)).clicked();
|
||||
if clicked {
|
||||
ui.close();
|
||||
}
|
||||
clicked
|
||||
}
|
||||
|
||||
fn icon_text(icon: Icon, size: f32) -> egui::RichText {
|
||||
egui::RichText::new(icon.as_str()).font(egui::FontId::new(
|
||||
size,
|
||||
egui::FontFamily::Name("phosphor-bold".into()),
|
||||
))
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn penpot_component_header_geometry_is_exact() {
|
||||
assert_eq!(COMPONENT_HEADER_HEIGHT, 50.0);
|
||||
assert_eq!(COMPONENT_RAIL_X, 7.0);
|
||||
assert_eq!(COMPONENT_CARET_CENTER_X, 26.0);
|
||||
assert_eq!(COMPONENT_ICON_CENTER_X, 51.0);
|
||||
assert_eq!(COMPONENT_IDENTITY_X, 69.0);
|
||||
assert_eq!(COMPONENT_ACTIONS_WIDTH, 104.0);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,12 @@
|
||||
//! Production egui presentation shared by the Blacksite editor and lightweight UI gallery.
|
||||
//!
|
||||
//! This crate owns rendering, deterministic geometry, and action-returning view contracts. It does
|
||||
//! not own a Bevy world, project state, authored-document publication, scene mutations, or content
|
||||
//! processing.
|
||||
|
||||
pub mod design_system;
|
||||
pub mod fonts;
|
||||
pub mod inspector;
|
||||
pub mod materials;
|
||||
pub mod renderer;
|
||||
pub mod theme;
|
||||
@@ -0,0 +1,286 @@
|
||||
//! Non-interactive Penpot v2.3.1 renderer-control preview.
|
||||
|
||||
use egui;
|
||||
use egui_phosphor_icons::icons;
|
||||
|
||||
use crate::design_system::typography::TypeRole;
|
||||
use crate::design_system::{self, ADVANCED_COLLAPSED_HEIGHT, ADVANCED_EXPANDED_HEIGHT};
|
||||
|
||||
const PLANNED_TOOLTIP: &str = "Planned — renderer support pending";
|
||||
|
||||
pub(super) fn unsupported_advanced_preview(ui: &mut egui::Ui) {
|
||||
let open_id = ui.make_persistent_id("material_unsupported_advanced_open");
|
||||
let reveal_id = open_id.with("reveal_complete_body");
|
||||
let mut open = ui
|
||||
.ctx()
|
||||
.data_mut(|data| data.get_persisted::<bool>(open_id))
|
||||
.unwrap_or(false);
|
||||
let width = ui.available_width().max(1.0);
|
||||
let mode = super::layout::ResponsiveMaterialLayout::for_width(width);
|
||||
let height = if open {
|
||||
if mode == super::layout::ResponsiveMaterialLayout::Transient {
|
||||
254.0
|
||||
} else {
|
||||
ADVANCED_EXPANDED_HEIGHT
|
||||
}
|
||||
} else {
|
||||
ADVANCED_COLLAPSED_HEIGHT
|
||||
};
|
||||
let palette = design_system::palette(ui);
|
||||
let (rect, _) = ui.allocate_exact_size(egui::vec2(width, height), egui::Sense::hover());
|
||||
ui.painter().rect(
|
||||
rect,
|
||||
5.0,
|
||||
palette.panel,
|
||||
egui::Stroke::new(1.0_f32, palette.border),
|
||||
egui::StrokeKind::Inside,
|
||||
);
|
||||
let header = egui::Rect::from_min_size(rect.min, egui::vec2(rect.width(), 30.0));
|
||||
ui.painter().rect_filled(header, 4.0, palette.panel);
|
||||
let header_response = ui.interact(header, open_id.with("header"), egui::Sense::click());
|
||||
if header_response.clicked() {
|
||||
open = !open;
|
||||
ui.ctx().data_mut(|data| data.insert_temp(reveal_id, open));
|
||||
}
|
||||
header_response.on_hover_text(if open {
|
||||
"Collapse Advanced preview"
|
||||
} else {
|
||||
"Expand Advanced preview"
|
||||
});
|
||||
ui.painter().text(
|
||||
header.left_center() + egui::vec2(12.0, 0.0),
|
||||
egui::Align2::LEFT_CENTER,
|
||||
if open {
|
||||
icons::CARET_DOWN.as_str()
|
||||
} else {
|
||||
icons::CARET_RIGHT.as_str()
|
||||
},
|
||||
egui::FontId::new(10.0, egui::FontFamily::Name("phosphor-bold".into())),
|
||||
palette.text_secondary,
|
||||
);
|
||||
ui.painter().text(
|
||||
header.left_center() + egui::vec2(26.0, 0.0),
|
||||
egui::Align2::LEFT_CENTER,
|
||||
"Advanced",
|
||||
TypeRole::Section.font(),
|
||||
palette.text_secondary,
|
||||
);
|
||||
if !open && rect.width() >= 300.0 {
|
||||
ui.painter().hline(
|
||||
(header.left() + 82.0)..=(header.right() - 158.0),
|
||||
header.center().y,
|
||||
egui::Stroke::new(1.0_f32, palette.border),
|
||||
);
|
||||
ui.painter().text(
|
||||
header.right_center() - egui::vec2(12.0, 0.0),
|
||||
egui::Align2::RIGHT_CENTER,
|
||||
PLANNED_TOOLTIP,
|
||||
TypeRole::Small.font(),
|
||||
palette.text_muted,
|
||||
);
|
||||
}
|
||||
if open {
|
||||
match mode {
|
||||
super::layout::ResponsiveMaterialLayout::Reference => reference_controls(ui, rect),
|
||||
super::layout::ResponsiveMaterialLayout::Compact => {
|
||||
compact_reference_controls(ui, rect)
|
||||
}
|
||||
super::layout::ResponsiveMaterialLayout::Transient => compact_controls(ui, rect),
|
||||
}
|
||||
}
|
||||
let reveal_complete_body = ui
|
||||
.ctx()
|
||||
.data_mut(|data| data.get_temp::<bool>(reveal_id))
|
||||
.unwrap_or(false);
|
||||
if open && reveal_complete_body && rect.height() > ADVANCED_COLLAPSED_HEIGHT {
|
||||
ui.scroll_to_rect(rect, Some(egui::Align::BOTTOM));
|
||||
ui.ctx().data_mut(|data| data.remove::<bool>(reveal_id));
|
||||
}
|
||||
ui.ctx()
|
||||
.data_mut(|data| data.insert_persisted(open_id, open));
|
||||
}
|
||||
|
||||
fn reference_controls(ui: &mut egui::Ui, rect: egui::Rect) {
|
||||
disabled_field(ui, rect, 28.0, 42.0, "Culling", "Back");
|
||||
disabled_field(ui, rect, 28.0, 76.0, "Render Queue", "From Shader");
|
||||
disabled_toggle(ui, rect, 328.0, 42.0, "Depth Write", true);
|
||||
disabled_toggle(ui, rect, 328.0, 76.0, "Receive Shadows", true);
|
||||
planned_note(ui, rect, 28.0, 124.0);
|
||||
}
|
||||
|
||||
fn compact_reference_controls(ui: &mut egui::Ui, rect: egui::Rect) {
|
||||
disabled_field_at(ui, rect, 20.0, 90.0, 90.0, 42.0, "Culling", "Back");
|
||||
disabled_field_at(
|
||||
ui,
|
||||
rect,
|
||||
20.0,
|
||||
90.0,
|
||||
90.0,
|
||||
76.0,
|
||||
"Render Queue",
|
||||
"From Shader",
|
||||
);
|
||||
disabled_toggle_at(
|
||||
ui,
|
||||
rect,
|
||||
196.0,
|
||||
rect.width() - 38.0,
|
||||
42.0,
|
||||
"Depth Write",
|
||||
true,
|
||||
);
|
||||
disabled_toggle_at(
|
||||
ui,
|
||||
rect,
|
||||
196.0,
|
||||
rect.width() - 38.0,
|
||||
76.0,
|
||||
"Receive Shadows",
|
||||
true,
|
||||
);
|
||||
planned_note(ui, rect, 20.0, 124.0);
|
||||
}
|
||||
|
||||
fn compact_controls(ui: &mut egui::Ui, rect: egui::Rect) {
|
||||
disabled_field(ui, rect, 20.0, 42.0, "Culling", "Back");
|
||||
disabled_field(ui, rect, 20.0, 78.0, "Render Queue", "From Shader");
|
||||
disabled_toggle(ui, rect, 20.0, 124.0, "Depth Write", true);
|
||||
disabled_toggle(ui, rect, 20.0, 160.0, "Receive Shadows", true);
|
||||
planned_note(ui, rect, 20.0, 210.0);
|
||||
}
|
||||
|
||||
fn disabled_field(ui: &mut egui::Ui, rect: egui::Rect, x: f32, y: f32, label: &str, value: &str) {
|
||||
disabled_field_at(ui, rect, x, x + 106.0, 150.0, y, label, value);
|
||||
}
|
||||
|
||||
#[expect(
|
||||
clippy::too_many_arguments,
|
||||
reason = "explicit Penpot preview geometry"
|
||||
)]
|
||||
fn disabled_field_at(
|
||||
ui: &mut egui::Ui,
|
||||
rect: egui::Rect,
|
||||
label_x: f32,
|
||||
field_x: f32,
|
||||
field_width: f32,
|
||||
y: f32,
|
||||
label: &str,
|
||||
value: &str,
|
||||
) {
|
||||
let palette = design_system::palette(ui);
|
||||
ui.painter().text(
|
||||
rect.min + egui::vec2(label_x, y),
|
||||
egui::Align2::LEFT_CENTER,
|
||||
label,
|
||||
TypeRole::Body.font(),
|
||||
palette.text_muted,
|
||||
);
|
||||
let field = egui::Rect::from_min_size(
|
||||
egui::pos2(rect.left() + field_x, rect.top() + y - 7.0),
|
||||
egui::vec2(field_width.min(rect.width() - field_x - 8.0).max(1.0), 24.0),
|
||||
);
|
||||
paint_disabled_field(ui, field, value);
|
||||
}
|
||||
|
||||
fn disabled_toggle(
|
||||
ui: &mut egui::Ui,
|
||||
rect: egui::Rect,
|
||||
x: f32,
|
||||
y: f32,
|
||||
label: &str,
|
||||
enabled: bool,
|
||||
) {
|
||||
disabled_toggle_at(ui, rect, x, x + 106.0, y, label, enabled);
|
||||
}
|
||||
|
||||
fn disabled_toggle_at(
|
||||
ui: &mut egui::Ui,
|
||||
rect: egui::Rect,
|
||||
label_x: f32,
|
||||
toggle_x: f32,
|
||||
y: f32,
|
||||
label: &str,
|
||||
enabled: bool,
|
||||
) {
|
||||
let palette = design_system::palette(ui);
|
||||
ui.painter().text(
|
||||
rect.min + egui::vec2(label_x, y),
|
||||
egui::Align2::LEFT_CENTER,
|
||||
label,
|
||||
TypeRole::Body.font(),
|
||||
palette.text_muted,
|
||||
);
|
||||
let toggle = egui::Rect::from_min_size(
|
||||
egui::pos2(rect.left() + toggle_x, rect.top() + y - 8.0),
|
||||
egui::vec2(30.0, 16.0),
|
||||
);
|
||||
ui.painter().rect(
|
||||
toggle,
|
||||
8.0,
|
||||
palette.control,
|
||||
egui::Stroke::new(1.0_f32, palette.border),
|
||||
egui::StrokeKind::Inside,
|
||||
);
|
||||
let thumb_x = if enabled {
|
||||
toggle.right() - 8.0
|
||||
} else {
|
||||
toggle.left() + 8.0
|
||||
};
|
||||
ui.painter().circle_filled(
|
||||
egui::pos2(thumb_x, toggle.center().y),
|
||||
5.0,
|
||||
palette.text_muted,
|
||||
);
|
||||
ui.interact(
|
||||
toggle,
|
||||
ui.make_persistent_id(("advanced_toggle", label)),
|
||||
egui::Sense::hover(),
|
||||
)
|
||||
.on_hover_text(PLANNED_TOOLTIP);
|
||||
}
|
||||
|
||||
fn paint_disabled_field(ui: &mut egui::Ui, rect: egui::Rect, value: &str) {
|
||||
let palette = design_system::palette(ui);
|
||||
ui.painter().rect(
|
||||
rect,
|
||||
4.0,
|
||||
palette.control,
|
||||
egui::Stroke::new(1.0_f32, palette.border),
|
||||
egui::StrokeKind::Inside,
|
||||
);
|
||||
ui.painter().text(
|
||||
rect.left_center() + egui::vec2(10.0, 0.0),
|
||||
egui::Align2::LEFT_CENTER,
|
||||
value,
|
||||
TypeRole::Body.font(),
|
||||
palette.text_muted,
|
||||
);
|
||||
ui.interact(
|
||||
rect,
|
||||
ui.make_persistent_id(("advanced_field", value)),
|
||||
egui::Sense::hover(),
|
||||
)
|
||||
.on_hover_text(PLANNED_TOOLTIP);
|
||||
}
|
||||
|
||||
fn planned_note(ui: &egui::Ui, rect: egui::Rect, x: f32, y: f32) {
|
||||
let palette = design_system::palette(ui);
|
||||
ui.painter().text(
|
||||
rect.min + egui::vec2(x, y),
|
||||
egui::Align2::LEFT_CENTER,
|
||||
PLANNED_TOOLTIP,
|
||||
TypeRole::Small.font(),
|
||||
palette.text_muted,
|
||||
);
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn penpot_advanced_preview_matches_v231_heights() {
|
||||
assert_eq!(ADVANCED_COLLAPSED_HEIGHT, 30.0);
|
||||
assert_eq!(ADVANCED_EXPANDED_HEIGHT, 178.0);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,724 @@
|
||||
use super::texture_inputs::{
|
||||
ensure_material_texture_binding, material_property_texture_binding,
|
||||
material_texture_channel_ui, texture_binding_ui, texture_channel_label,
|
||||
upsert_material_texture_binding,
|
||||
};
|
||||
use super::uv_transform::{material_vec2_value, set_material_vec2_value, uv_transform_section};
|
||||
use super::*;
|
||||
|
||||
use crate::design_system;
|
||||
use crate::design_system::color_picker::{color_control, color_control_with_intensity};
|
||||
use crate::design_system::controls::{
|
||||
scalar_control, section_header, section_header_with_summary, switch,
|
||||
};
|
||||
use crate::design_system::property_grid::PropertyGridGeometry;
|
||||
use crate::design_system::typography::TypeRole;
|
||||
use material_schema::MaterialShaderKind;
|
||||
|
||||
pub fn material_input_schema_editor(
|
||||
ui: &mut egui::Ui,
|
||||
schema: &MaterialInputSchema,
|
||||
inputs: &mut MaterialInputSet,
|
||||
texture_assets: &[MaterialTextureCandidate],
|
||||
drop_candidate: Option<&MaterialTextureCandidate>,
|
||||
) -> MaterialInputEditorResponse {
|
||||
material_input_schema_editor_with_inheritance(
|
||||
ui,
|
||||
schema,
|
||||
inputs,
|
||||
None,
|
||||
texture_assets,
|
||||
drop_candidate,
|
||||
)
|
||||
}
|
||||
|
||||
pub fn material_input_schema_editor_with_inheritance(
|
||||
ui: &mut egui::Ui,
|
||||
schema: &MaterialInputSchema,
|
||||
inputs: &mut MaterialInputSet,
|
||||
inherited: Option<&MaterialInputSet>,
|
||||
texture_assets: &[MaterialTextureCandidate],
|
||||
drop_candidate: Option<&MaterialTextureCandidate>,
|
||||
) -> MaterialInputEditorResponse {
|
||||
let mut response = MaterialInputEditorResponse::default();
|
||||
let has_standard_packed_inputs = ["occlusion", "roughness", "metallic"]
|
||||
.iter()
|
||||
.all(|name| schema.inputs.iter().any(|input| input.name == *name));
|
||||
let mut groups = schema.groups.clone();
|
||||
if groups.is_empty() {
|
||||
groups.push(material_schema::MaterialInputGroupDesc {
|
||||
id: String::new(),
|
||||
display_name: "Properties".into(),
|
||||
order: 0,
|
||||
advanced: false,
|
||||
});
|
||||
}
|
||||
groups.sort_by_key(|group| group.order);
|
||||
for group in groups {
|
||||
let mut properties = schema
|
||||
.inputs
|
||||
.iter()
|
||||
.filter(|property| {
|
||||
property.group == group.id
|
||||
&& matches!(
|
||||
property.presentation,
|
||||
material_schema::MaterialInputPresentation::Row
|
||||
)
|
||||
})
|
||||
.collect::<Vec<_>>();
|
||||
let companions = schema
|
||||
.inputs
|
||||
.iter()
|
||||
.filter(|property| property.group == group.id)
|
||||
.filter_map(|property| match &property.presentation {
|
||||
material_schema::MaterialInputPresentation::Companion { owner } => {
|
||||
Some((owner.as_str(), property))
|
||||
}
|
||||
material_schema::MaterialInputPresentation::Row => None,
|
||||
})
|
||||
.collect::<Vec<_>>();
|
||||
properties.sort_by_key(|property| property.order);
|
||||
if properties.is_empty() {
|
||||
continue;
|
||||
}
|
||||
if group.id == "uv_transform" {
|
||||
material_uv_transform_ui(ui, inputs, inherited);
|
||||
// The design-system scope contributes four pixels between vertical items; add the
|
||||
// remaining four to reach the authored eight-pixel section gap.
|
||||
ui.add_space(4.0);
|
||||
continue;
|
||||
}
|
||||
let open_id = ui.make_persistent_id(("material_input_group_open", &group.id));
|
||||
let mut open = ui
|
||||
.ctx()
|
||||
.data_mut(|data| data.get_persisted::<bool>(open_id))
|
||||
.unwrap_or(!group.advanced);
|
||||
let context = MaterialInputGroupContext {
|
||||
properties: &properties,
|
||||
companions: &companions,
|
||||
texture_assets,
|
||||
drop_candidate,
|
||||
};
|
||||
let rows = material_input_group_ui(ui, context, &mut open, inputs, |ui, open| {
|
||||
if group.id == "surface_inputs" {
|
||||
let summary = format!("{} bindings", properties.len());
|
||||
section_header_with_summary(ui, "Inputs", Some(&summary), open);
|
||||
} else {
|
||||
section_header(ui, &group.display_name, open);
|
||||
}
|
||||
});
|
||||
response.accepted_drop |= rows.accepted_drop;
|
||||
response.locate = response.locate.take().or(rows.locate);
|
||||
response.browse_library |= rows.browse_library;
|
||||
ui.ctx()
|
||||
.data_mut(|data| data.insert_persisted(open_id, open));
|
||||
ui.add_space(4.0);
|
||||
}
|
||||
if has_standard_packed_inputs {
|
||||
super::advanced_preview::unsupported_advanced_preview(ui);
|
||||
}
|
||||
response
|
||||
}
|
||||
|
||||
#[derive(Clone, Copy)]
|
||||
struct MaterialInputGroupContext<'schema, 'view> {
|
||||
properties: &'view [&'schema MaterialInputDesc],
|
||||
companions: &'view [(&'schema str, &'schema MaterialInputDesc)],
|
||||
texture_assets: &'view [MaterialTextureCandidate],
|
||||
drop_candidate: Option<&'view MaterialTextureCandidate>,
|
||||
}
|
||||
|
||||
fn material_input_group_ui(
|
||||
ui: &mut egui::Ui,
|
||||
context: MaterialInputGroupContext<'_, '_>,
|
||||
open: &mut bool,
|
||||
inputs: &mut MaterialInputSet,
|
||||
header_ui: impl FnOnce(&mut egui::Ui, &mut bool),
|
||||
) -> MaterialInputEditorResponse {
|
||||
let width = ui.available_width().max(1.0);
|
||||
let geometry = PropertyGridGeometry::for_width(width);
|
||||
let body_open = *open;
|
||||
let height = material_input_group_height(width, body_open, context.properties.len());
|
||||
let (rect, _) = ui.allocate_exact_size(egui::vec2(width, height), egui::Sense::hover());
|
||||
let palette = design_system::palette(ui);
|
||||
ui.painter().rect(
|
||||
rect,
|
||||
5.0,
|
||||
palette.section,
|
||||
egui::Stroke::new(1.0_f32, palette.border),
|
||||
egui::StrokeKind::Inside,
|
||||
);
|
||||
|
||||
// The parent owns the complete section rect. Child controls may manage local layout state,
|
||||
// but they cannot alter where the next material section begins.
|
||||
let mut section = ui.new_child(egui::UiBuilder::new().max_rect(rect));
|
||||
section.set_clip_rect(rect.intersect(ui.clip_rect()));
|
||||
let header_rect = egui::Rect::from_min_size(
|
||||
rect.min,
|
||||
egui::vec2(width, design_system::INPUT_SECTION_HEADER_HEIGHT),
|
||||
);
|
||||
let mut header = section.new_child(egui::UiBuilder::new().max_rect(header_rect));
|
||||
header.set_clip_rect(header_rect.intersect(section.clip_rect()));
|
||||
header_ui(&mut header, open);
|
||||
|
||||
if body_open {
|
||||
let rows_rect =
|
||||
egui::Rect::from_min_max(egui::pos2(rect.left(), header_rect.bottom()), rect.max);
|
||||
material_input_rows(&mut section, rows_rect, geometry, context, inputs)
|
||||
} else {
|
||||
MaterialInputEditorResponse::default()
|
||||
}
|
||||
}
|
||||
|
||||
fn material_input_group_height(width: f32, open: bool, rows: usize) -> f32 {
|
||||
let body = if open {
|
||||
PropertyGridGeometry::for_width(width).row_height * rows as f32
|
||||
} else {
|
||||
0.0
|
||||
};
|
||||
design_system::INPUT_SECTION_HEADER_HEIGHT + body
|
||||
}
|
||||
|
||||
fn material_uv_transform_ui(
|
||||
ui: &mut egui::Ui,
|
||||
inputs: &mut MaterialInputSet,
|
||||
inherited: Option<&MaterialInputSet>,
|
||||
) {
|
||||
let mut offset = material_vec2_value(inputs, "uv_offset", Vec2::ZERO);
|
||||
let mut tiling = material_vec2_value(inputs, "uv_tiling", Vec2::ONE);
|
||||
let reset_offset = inherited.map_or(Vec2::ZERO, |inputs| {
|
||||
material_vec2_value(inputs, "uv_offset", Vec2::ZERO)
|
||||
});
|
||||
let reset_tiling = inherited.map_or(Vec2::ONE, |inputs| {
|
||||
material_vec2_value(inputs, "uv_tiling", Vec2::ONE)
|
||||
});
|
||||
let original = (offset, tiling);
|
||||
uv_transform_section(ui, &mut offset, &mut tiling, reset_offset, reset_tiling);
|
||||
if (offset, tiling) != original {
|
||||
set_material_vec2_value(inputs, "uv_offset", offset);
|
||||
set_material_vec2_value(inputs, "uv_tiling", tiling);
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
|
||||
pub enum PackedMapMode {
|
||||
Arm,
|
||||
Separate,
|
||||
}
|
||||
|
||||
pub fn packed_map_mode(inputs: &MaterialInputSet) -> PackedMapMode {
|
||||
let channels = [
|
||||
("occlusion", TextureChannel::R),
|
||||
("roughness", TextureChannel::G),
|
||||
("metallic", TextureChannel::B),
|
||||
];
|
||||
if channels.iter().all(|(name, channel)| {
|
||||
inputs
|
||||
.texture(name)
|
||||
.is_some_and(|binding| binding.channel == *channel)
|
||||
}) {
|
||||
PackedMapMode::Arm
|
||||
} else {
|
||||
PackedMapMode::Separate
|
||||
}
|
||||
}
|
||||
|
||||
pub fn apply_arm_texture_preset(inputs: &mut MaterialInputSet) {
|
||||
let shared_texture = ["occlusion", "roughness", "metallic"]
|
||||
.iter()
|
||||
.find_map(|name| {
|
||||
inputs
|
||||
.texture(name)
|
||||
.and_then(|binding| binding.texture.clone())
|
||||
});
|
||||
for (name, channel) in [
|
||||
("occlusion", TextureChannel::R),
|
||||
("roughness", TextureChannel::G),
|
||||
("metallic", TextureChannel::B),
|
||||
] {
|
||||
let binding = ensure_material_texture_binding(&mut inputs.textures, name);
|
||||
binding.channel = channel;
|
||||
if let Some(texture) = shared_texture.clone() {
|
||||
binding.texture = Some(texture);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
pub fn apply_separate_texture_preset(inputs: &mut MaterialInputSet) {
|
||||
for name in ["occlusion", "roughness", "metallic"] {
|
||||
ensure_material_texture_binding(&mut inputs.textures, name).channel = TextureChannel::R;
|
||||
}
|
||||
}
|
||||
|
||||
fn material_input_rows(
|
||||
ui: &mut egui::Ui,
|
||||
rows_rect: egui::Rect,
|
||||
geometry: PropertyGridGeometry,
|
||||
context: MaterialInputGroupContext<'_, '_>,
|
||||
inputs: &mut MaterialInputSet,
|
||||
) -> MaterialInputEditorResponse {
|
||||
let palette = design_system::palette(ui);
|
||||
let mut response = MaterialInputEditorResponse::default();
|
||||
for (row, property) in context.properties.iter().enumerate() {
|
||||
let companion = context
|
||||
.companions
|
||||
.iter()
|
||||
.find_map(|(owner, companion)| (*owner == property.name).then_some(*companion));
|
||||
ui.push_id(("material_input_row", &property.name), |ui| {
|
||||
let row_rect = egui::Rect::from_min_size(
|
||||
rows_rect.min + egui::vec2(0.0, row as f32 * geometry.row_height),
|
||||
egui::vec2(rows_rect.width(), geometry.row_height),
|
||||
);
|
||||
ui.painter().rect_filled(
|
||||
row_rect,
|
||||
0.0,
|
||||
if row.is_multiple_of(2) {
|
||||
palette.row_even
|
||||
} else {
|
||||
palette.row_odd
|
||||
},
|
||||
);
|
||||
let rects = geometry.row_rects(row_rect);
|
||||
rect_ui(ui, rects.label, |ui| material_input_label(ui, property));
|
||||
let is_color = matches!(property.property_type, ShaderPropertyType::Color);
|
||||
rect_ui(
|
||||
ui,
|
||||
if is_color {
|
||||
rects.color_value
|
||||
} else {
|
||||
rects.value
|
||||
},
|
||||
|ui| material_input_value_ui(ui, property, companion, inputs),
|
||||
);
|
||||
if !is_color {
|
||||
rect_ui(ui, rects.channel, |ui| {
|
||||
material_input_channel_ui(ui, property, inputs)
|
||||
});
|
||||
}
|
||||
if material_input_uses_texture(property) {
|
||||
let texture = rect_ui(ui, rects.texture_group, |ui| {
|
||||
material_input_texture_ui(
|
||||
ui,
|
||||
property,
|
||||
inputs,
|
||||
context.texture_assets,
|
||||
context.drop_candidate,
|
||||
rects.inline_texture_actions,
|
||||
)
|
||||
});
|
||||
response.accepted_drop |= texture.accepted_drop;
|
||||
response.locate = response.locate.take().or(texture.locate);
|
||||
response.browse_library |= texture.browse_library;
|
||||
}
|
||||
});
|
||||
}
|
||||
response
|
||||
}
|
||||
|
||||
fn rect_ui<R>(
|
||||
ui: &mut egui::Ui,
|
||||
rect: egui::Rect,
|
||||
add_contents: impl FnOnce(&mut egui::Ui) -> R,
|
||||
) -> R {
|
||||
ui.scope_builder(egui::UiBuilder::new().max_rect(rect), |ui| {
|
||||
ui.set_clip_rect(rect.intersect(ui.clip_rect()));
|
||||
add_contents(ui)
|
||||
})
|
||||
.inner
|
||||
}
|
||||
|
||||
pub(super) fn material_input_label(ui: &mut egui::Ui, property: &MaterialInputDesc) {
|
||||
let palette = design_system::palette(ui);
|
||||
ui.add(
|
||||
egui::Label::new(
|
||||
TypeRole::Body
|
||||
.text(&property.display_name)
|
||||
.color(palette.text_secondary),
|
||||
)
|
||||
.truncate(),
|
||||
)
|
||||
.on_hover_text(&property.tooltip);
|
||||
}
|
||||
|
||||
pub(super) fn material_input_uses_texture(property: &MaterialInputDesc) -> bool {
|
||||
property.texture.is_some() || matches!(property.property_type, ShaderPropertyType::Texture)
|
||||
}
|
||||
|
||||
pub(super) fn material_input_value_ui(
|
||||
ui: &mut egui::Ui,
|
||||
property: &MaterialInputDesc,
|
||||
companion: Option<&MaterialInputDesc>,
|
||||
inputs: &mut MaterialInputSet,
|
||||
) {
|
||||
let MaterialInputSet { values, .. } = inputs;
|
||||
ui.horizontal(|ui| {
|
||||
if matches!(property.property_type, ShaderPropertyType::Texture) {
|
||||
ui.label(egui::RichText::new("Texture").small().color(TEXT_DIM));
|
||||
} else {
|
||||
let default = property
|
||||
.default_value
|
||||
.clone()
|
||||
.unwrap_or_else(|| default_value_for_shader_property(&property.property_type));
|
||||
let mut value = values
|
||||
.iter()
|
||||
.find(|value| value.name == property.name)
|
||||
.map(|parameter| parameter.value.clone())
|
||||
.unwrap_or(default);
|
||||
if !parameter_value_matches_property(&value, &property.property_type) {
|
||||
value = default_value_for_shader_property(&property.property_type);
|
||||
}
|
||||
let original = value.clone();
|
||||
if matches!(property.property_type, ShaderPropertyType::Color)
|
||||
&& companion.is_some_and(|input| input.name == "emissive_intensity")
|
||||
{
|
||||
let companion = companion.expect("checked companion");
|
||||
let companion_default = companion
|
||||
.default_value
|
||||
.clone()
|
||||
.unwrap_or(MaterialParameterValue::Float(0.0));
|
||||
let mut companion_value = values
|
||||
.iter()
|
||||
.find(|value| value.name == companion.name)
|
||||
.map(|parameter| parameter.value.clone())
|
||||
.unwrap_or(companion_default);
|
||||
if !parameter_value_matches_property(&companion_value, &companion.property_type) {
|
||||
companion_value = default_value_for_shader_property(&companion.property_type);
|
||||
}
|
||||
let original_companion = companion_value.clone();
|
||||
if let (
|
||||
MaterialParameterValue::Color(color),
|
||||
MaterialParameterValue::Float(intensity),
|
||||
) = (&mut value, &mut companion_value)
|
||||
{
|
||||
let mut rgba = [color.r, color.g, color.b, color.a];
|
||||
let picker = color_control_with_intensity(
|
||||
ui,
|
||||
"material_emissive_color",
|
||||
&property.display_name,
|
||||
&mut rgba,
|
||||
intensity,
|
||||
);
|
||||
if picker.changed {
|
||||
*color = ColorDesc {
|
||||
r: rgba[0],
|
||||
g: rgba[1],
|
||||
b: rgba[2],
|
||||
a: rgba[3],
|
||||
};
|
||||
}
|
||||
}
|
||||
if value != original {
|
||||
upsert_material_parameter(values, &property.name, value);
|
||||
}
|
||||
if companion_value != original_companion {
|
||||
upsert_material_parameter(values, &companion.name, companion_value);
|
||||
}
|
||||
} else {
|
||||
material_parameter_control_ui(
|
||||
ui,
|
||||
&property.display_name,
|
||||
&property.property_type,
|
||||
&mut value,
|
||||
);
|
||||
if value != original {
|
||||
upsert_material_parameter(values, &property.name, value);
|
||||
}
|
||||
}
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
fn upsert_material_parameter(
|
||||
values: &mut Vec<MaterialParameter>,
|
||||
name: &str,
|
||||
value: MaterialParameterValue,
|
||||
) {
|
||||
if let Some(parameter) = values.iter_mut().find(|parameter| parameter.name == name) {
|
||||
parameter.value = value;
|
||||
} else {
|
||||
values.push(MaterialParameter {
|
||||
name: name.to_string(),
|
||||
value,
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
fn material_input_channel_ui(
|
||||
ui: &mut egui::Ui,
|
||||
property: &MaterialInputDesc,
|
||||
inputs: &mut MaterialInputSet,
|
||||
) {
|
||||
let palette = design_system::palette(ui);
|
||||
if property
|
||||
.texture
|
||||
.as_ref()
|
||||
.is_some_and(|texture| texture.allow_channel_override)
|
||||
{
|
||||
let original = material_property_texture_binding(&inputs.textures, property);
|
||||
let mut binding = original.clone();
|
||||
material_texture_channel_ui(ui, property, &mut binding);
|
||||
if binding != original {
|
||||
upsert_material_texture_binding(&mut inputs.textures, binding);
|
||||
}
|
||||
} else {
|
||||
let channel = property.texture.as_ref().map(|texture| {
|
||||
if matches!(texture.semantic, material_schema::TextureSemantic::Color) {
|
||||
"RGB"
|
||||
} else {
|
||||
texture_channel_label(texture.default_channel)
|
||||
}
|
||||
});
|
||||
if let Some(channel) = channel {
|
||||
readonly_channel(ui, channel);
|
||||
} else {
|
||||
ui.label(TypeRole::Body.text("—").color(palette.text_muted));
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
pub(super) fn material_input_texture_ui(
|
||||
ui: &mut egui::Ui,
|
||||
property: &MaterialInputDesc,
|
||||
inputs: &mut MaterialInputSet,
|
||||
texture_assets: &[MaterialTextureCandidate],
|
||||
drop_candidate: Option<&MaterialTextureCandidate>,
|
||||
inline_actions: bool,
|
||||
) -> TextureSlotResponse {
|
||||
if !material_input_uses_texture(property) {
|
||||
return TextureSlotResponse::default();
|
||||
}
|
||||
let original = material_property_texture_binding(&inputs.textures, property);
|
||||
let mut binding = original.clone();
|
||||
let response = texture_binding_ui(
|
||||
ui,
|
||||
&mut binding,
|
||||
texture_assets,
|
||||
drop_candidate,
|
||||
inline_actions,
|
||||
);
|
||||
if binding != original {
|
||||
upsert_material_texture_binding(&mut inputs.textures, binding);
|
||||
}
|
||||
response
|
||||
}
|
||||
|
||||
pub(super) fn material_parameter_control_ui(
|
||||
ui: &mut egui::Ui,
|
||||
label: &str,
|
||||
property_type: &ShaderPropertyType,
|
||||
value: &mut MaterialParameterValue,
|
||||
) {
|
||||
if !parameter_value_matches_property(value, property_type) {
|
||||
*value = default_value_for_shader_property(property_type);
|
||||
}
|
||||
match value {
|
||||
MaterialParameterValue::Bool(value) => {
|
||||
switch(ui, value);
|
||||
}
|
||||
MaterialParameterValue::Float(value) => {
|
||||
let (min, max) = match property_type {
|
||||
ShaderPropertyType::Float { min, max } => (*min, *max),
|
||||
_ => (None, None),
|
||||
};
|
||||
match (min, max) {
|
||||
(Some(min), Some(max)) => {
|
||||
scalar_control(ui, label, value, min..=max, usize::from(max <= 1_000.0) * 2);
|
||||
}
|
||||
_ => {
|
||||
ui.add(egui::DragValue::new(value).speed(0.01));
|
||||
}
|
||||
}
|
||||
}
|
||||
MaterialParameterValue::Vec2(value) => {
|
||||
ui.add(egui::DragValue::new(&mut value.x).speed(0.01).prefix("X "));
|
||||
ui.add(egui::DragValue::new(&mut value.y).speed(0.01).prefix("Y "));
|
||||
}
|
||||
MaterialParameterValue::Vec3(value) => {
|
||||
ui.add(egui::DragValue::new(&mut value.x).speed(0.01).prefix("X "));
|
||||
ui.add(egui::DragValue::new(&mut value.y).speed(0.01).prefix("Y "));
|
||||
ui.add(egui::DragValue::new(&mut value.z).speed(0.01).prefix("Z "));
|
||||
}
|
||||
MaterialParameterValue::Color(value) => {
|
||||
let mut rgba = [value.r, value.g, value.b, value.a];
|
||||
let response = color_control(ui, "material_color", label, &mut rgba);
|
||||
if response.changed {
|
||||
*value = ColorDesc {
|
||||
r: rgba[0],
|
||||
g: rgba[1],
|
||||
b: rgba[2],
|
||||
a: rgba[3],
|
||||
};
|
||||
}
|
||||
}
|
||||
MaterialParameterValue::Enum(value) => {
|
||||
let options = match property_type {
|
||||
ShaderPropertyType::Enum { options } => options.as_slice(),
|
||||
_ => &[],
|
||||
};
|
||||
egui::ComboBox::from_id_salt(("material_enum", value.as_str()))
|
||||
.selected_text(value.as_str())
|
||||
.show_ui(ui, |ui| {
|
||||
for option in options {
|
||||
ui.selectable_value(value, option.clone(), option);
|
||||
}
|
||||
});
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fn readonly_channel(ui: &mut egui::Ui, channel: &str) {
|
||||
let palette = design_system::palette(ui);
|
||||
let (rect, response) = ui.allocate_exact_size(egui::vec2(48.0, 22.0), egui::Sense::hover());
|
||||
ui.painter().rect(
|
||||
rect,
|
||||
4.0,
|
||||
palette.control,
|
||||
egui::Stroke::new(1.0_f32, palette.border),
|
||||
egui::StrokeKind::Inside,
|
||||
);
|
||||
ui.painter().text(
|
||||
rect.left_center() + egui::vec2(9.0, 0.0),
|
||||
egui::Align2::LEFT_CENTER,
|
||||
channel,
|
||||
TypeRole::Body.font(),
|
||||
palette.text_secondary,
|
||||
);
|
||||
ui.painter().text(
|
||||
rect.right_center() - egui::vec2(8.0, 0.0),
|
||||
egui::Align2::CENTER_CENTER,
|
||||
egui_phosphor_icons::icons::CARET_DOWN.as_str(),
|
||||
egui::FontId::new(9.0, egui::FontFamily::Name("phosphor-bold".into())),
|
||||
palette.text_muted,
|
||||
);
|
||||
response.on_hover_text("Channel is fixed by this material input");
|
||||
}
|
||||
|
||||
pub fn default_value_for_shader_property(
|
||||
property_type: &ShaderPropertyType,
|
||||
) -> MaterialParameterValue {
|
||||
match property_type {
|
||||
ShaderPropertyType::Bool => MaterialParameterValue::Bool(false),
|
||||
ShaderPropertyType::Float { .. } => MaterialParameterValue::Float(0.0),
|
||||
ShaderPropertyType::Vec2 => MaterialParameterValue::Vec2(Vec2::ZERO),
|
||||
ShaderPropertyType::Vec3 => MaterialParameterValue::Vec3(Vec3::ZERO),
|
||||
ShaderPropertyType::Color => MaterialParameterValue::Color(ColorDesc::default()),
|
||||
ShaderPropertyType::Enum { options } => {
|
||||
MaterialParameterValue::Enum(options.first().cloned().unwrap_or_default())
|
||||
}
|
||||
ShaderPropertyType::Texture => MaterialParameterValue::Float(0.0),
|
||||
}
|
||||
}
|
||||
|
||||
pub fn parameter_value_matches_property(
|
||||
value: &MaterialParameterValue,
|
||||
property_type: &ShaderPropertyType,
|
||||
) -> bool {
|
||||
matches!(
|
||||
(value, property_type),
|
||||
(MaterialParameterValue::Bool(_), ShaderPropertyType::Bool)
|
||||
| (
|
||||
MaterialParameterValue::Float(_),
|
||||
ShaderPropertyType::Float { .. }
|
||||
)
|
||||
| (MaterialParameterValue::Vec2(_), ShaderPropertyType::Vec2)
|
||||
| (MaterialParameterValue::Vec3(_), ShaderPropertyType::Vec3)
|
||||
| (MaterialParameterValue::Color(_), ShaderPropertyType::Color)
|
||||
| (
|
||||
MaterialParameterValue::Enum(_),
|
||||
ShaderPropertyType::Enum { .. }
|
||||
)
|
||||
)
|
||||
}
|
||||
|
||||
pub fn compact_text_edit(ui: &mut egui::Ui, label: &str, value: &mut String) {
|
||||
ui.horizontal(|ui| {
|
||||
ui.add_sized([92.0, 20.0], egui::Label::new(label));
|
||||
ui.add_sized(
|
||||
[fit_width(ui, 100.0, f32::INFINITY), 22.0],
|
||||
egui::TextEdit::singleline(value),
|
||||
);
|
||||
});
|
||||
}
|
||||
|
||||
pub fn shader_kind_picker(ui: &mut egui::Ui, kind: &mut MaterialShaderKind) {
|
||||
ui.horizontal(|ui| {
|
||||
ui.add_sized([92.0, 20.0], egui::Label::new("Shader"));
|
||||
shader_kind_combo(ui, kind, "asset_material_shader_kind");
|
||||
});
|
||||
}
|
||||
|
||||
pub fn shader_kind_combo(
|
||||
ui: &mut egui::Ui,
|
||||
kind: &mut MaterialShaderKind,
|
||||
salt: impl std::hash::Hash,
|
||||
) {
|
||||
egui::ComboBox::from_id_salt(salt)
|
||||
.selected_text(match kind {
|
||||
MaterialShaderKind::StandardLit => "Standard Lit",
|
||||
MaterialShaderKind::Unlit => "Unlit",
|
||||
MaterialShaderKind::Custom => "Custom Surface",
|
||||
})
|
||||
.width(150.0_f32.min(ui.available_width().max(1.0)))
|
||||
.show_ui(ui, |ui| {
|
||||
ui.selectable_value(kind, MaterialShaderKind::StandardLit, "Standard Lit");
|
||||
ui.selectable_value(kind, MaterialShaderKind::Unlit, "Unlit");
|
||||
ui.selectable_value(kind, MaterialShaderKind::Custom, "Custom Surface");
|
||||
});
|
||||
}
|
||||
|
||||
pub fn optional_path_edit(ui: &mut egui::Ui, label: &str, value: &mut Option<String>) {
|
||||
ui.horizontal(|ui| {
|
||||
ui.add_sized([92.0, 20.0], egui::Label::new(label));
|
||||
let mut text = value.clone().unwrap_or_default();
|
||||
if ui
|
||||
.add_sized(
|
||||
[fit_width(ui, 80.0, f32::INFINITY), 22.0],
|
||||
egui::TextEdit::singleline(&mut text),
|
||||
)
|
||||
.changed()
|
||||
{
|
||||
*value = if text.trim().is_empty() {
|
||||
None
|
||||
} else {
|
||||
Some(text)
|
||||
};
|
||||
}
|
||||
if ui.button("Clear").clicked() {
|
||||
*value = None;
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn input_group_parent_owns_exact_reference_and_compact_heights() {
|
||||
assert_eq!(material_input_group_height(569.0, true, 6), 216.0);
|
||||
assert_eq!(material_input_group_height(369.0, true, 6), 372.0);
|
||||
assert_eq!(material_input_group_height(569.0, false, 6), 24.0);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn rendering_missing_standard_defaults_does_not_author_or_dirty_inputs() {
|
||||
let context = egui::Context::default();
|
||||
context.set_fonts(crate::fonts::font_definitions());
|
||||
let mut inputs = MaterialInputSet::default();
|
||||
let original = inputs.clone();
|
||||
let schema = material_schema::standard_lit_input_schema();
|
||||
let _ = context.run_ui(
|
||||
egui::RawInput {
|
||||
screen_rect: Some(egui::Rect::from_min_size(
|
||||
egui::Pos2::ZERO,
|
||||
egui::vec2(700.0, 900.0),
|
||||
)),
|
||||
..Default::default()
|
||||
},
|
||||
|ui| {
|
||||
material_input_schema_editor(ui, &schema, &mut inputs, &[], None);
|
||||
},
|
||||
);
|
||||
assert_eq!(inputs, original);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,344 @@
|
||||
//! Numeric Penpot v2.3.1 material-panel geometry shared by rendering and tests.
|
||||
|
||||
use egui;
|
||||
|
||||
use crate::design_system::{
|
||||
ADVANCED_COLLAPSED_HEIGHT, ADVANCED_EXPANDED_HEIGHT, COLLAPSED_HEADER_HEIGHT, HEADER_HEIGHT,
|
||||
INPUT_SECTION_HEADER_HEIGHT, MATERIAL_IDENTITY_WIDTH, MATERIAL_PREVIEW_SIZE, OUTER_PADDING,
|
||||
PARAMETER_ROW_HEIGHT, SECTION_GAP, SURFACE_SECTION_HEIGHT, UV_SECTION_HEIGHT,
|
||||
};
|
||||
|
||||
/// Smallest canvas that can still contain the exported compact Surface controls.
|
||||
///
|
||||
/// The Penpot board owns a 372 px parameter section. In the actor Inspector, component-card
|
||||
/// chrome can temporarily reduce that canvas by a few pixels even while the Inspector itself is
|
||||
/// at its supported 420 px floor. The fixed compact controls only require 362 px, so keep the
|
||||
/// intended two-line layout until that real containment limit and reserve `Transient` for actual
|
||||
/// sub-minimum docking frames.
|
||||
pub(super) const COMPACT_SECTION_WIDTH: f32 = 357.0;
|
||||
|
||||
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
|
||||
pub(super) enum ResponsiveMaterialLayout {
|
||||
Reference,
|
||||
Compact,
|
||||
Transient,
|
||||
}
|
||||
|
||||
impl ResponsiveMaterialLayout {
|
||||
pub(super) fn for_width(width: f32) -> Self {
|
||||
if width + f32::EPSILON >= crate::design_system::property_grid::WIDE_SECTION_WIDTH {
|
||||
Self::Reference
|
||||
} else if width + f32::EPSILON >= COMPACT_SECTION_WIDTH {
|
||||
Self::Compact
|
||||
} else {
|
||||
Self::Transient
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, Copy, PartialEq)]
|
||||
pub(super) struct SurfaceSectionGeometry {
|
||||
pub height: f32,
|
||||
pub title: egui::Rect,
|
||||
pub blend: egui::Rect,
|
||||
pub packed: egui::Rect,
|
||||
pub double_sided: egui::Rect,
|
||||
}
|
||||
|
||||
impl SurfaceSectionGeometry {
|
||||
pub(super) fn for_rect(rect: egui::Rect) -> Self {
|
||||
let local = |x: f32, y: f32, width: f32, height: f32| {
|
||||
let x = x.clamp(0.0, rect.width());
|
||||
let y = y.clamp(0.0, rect.height());
|
||||
egui::Rect::from_min_size(
|
||||
rect.min + egui::vec2(x, y),
|
||||
egui::vec2(
|
||||
width.max(0.0).min(rect.width() - x),
|
||||
height.max(0.0).min(rect.height() - y),
|
||||
),
|
||||
)
|
||||
};
|
||||
match ResponsiveMaterialLayout::for_width(rect.width()) {
|
||||
ResponsiveMaterialLayout::Reference => Self {
|
||||
height: SURFACE_SECTION_HEIGHT,
|
||||
title: local(10.0, 10.0, 48.0, 26.0),
|
||||
blend: local(66.0, 10.0, 250.0, 26.0),
|
||||
packed: local(324.0, 11.0, 128.0, 24.0),
|
||||
double_sided: local(460.0, 12.0, 99.0, 22.0),
|
||||
},
|
||||
ResponsiveMaterialLayout::Compact => Self {
|
||||
height: crate::design_system::COMPACT_SURFACE_SECTION_HEIGHT,
|
||||
title: local(10.0, 10.0, 48.0, 26.0),
|
||||
blend: local(66.0, 10.0, 50.0, 26.0),
|
||||
packed: local(124.0, 11.0, 128.0, 24.0),
|
||||
double_sided: local(260.0, 12.0, 99.0, 22.0),
|
||||
},
|
||||
ResponsiveMaterialLayout::Transient => Self {
|
||||
height: 100.0,
|
||||
title: local(10.0, 10.0, 48.0, 26.0),
|
||||
blend: local(66.0, 10.0, (rect.width() - 76.0).clamp(1.0, 250.0), 26.0),
|
||||
packed: local(10.0, 42.0, (rect.width() - 20.0).clamp(0.0, 128.0), 24.0),
|
||||
double_sided: local(146.0, 43.0, (rect.width() - 156.0).clamp(0.0, 99.0), 22.0),
|
||||
},
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, Copy, PartialEq)]
|
||||
pub(super) struct UvGroupGeometry {
|
||||
pub label: egui::Rect,
|
||||
pub x: egui::Rect,
|
||||
pub y: egui::Rect,
|
||||
pub reset: Option<egui::Rect>,
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, Copy, PartialEq)]
|
||||
pub(super) struct UvSectionGeometry {
|
||||
pub height: f32,
|
||||
pub title: egui::Rect,
|
||||
pub offset: UvGroupGeometry,
|
||||
pub tiling: UvGroupGeometry,
|
||||
}
|
||||
|
||||
impl UvSectionGeometry {
|
||||
pub(super) fn for_rect(rect: egui::Rect) -> Self {
|
||||
let mode = ResponsiveMaterialLayout::for_width(rect.width());
|
||||
let title = egui::Rect::from_min_size(
|
||||
rect.min + egui::vec2(12.0, 7.0),
|
||||
egui::vec2(20.0_f32.min(rect.width()), 14.0_f32.min(rect.height())),
|
||||
);
|
||||
if mode == ResponsiveMaterialLayout::Transient {
|
||||
let group_width = (rect.width() - 20.0).max(1.0);
|
||||
return Self {
|
||||
height: 100.0,
|
||||
title,
|
||||
offset: uv_group(rect.min + egui::vec2(42.0, 7.0), group_width),
|
||||
tiling: uv_group(rect.min + egui::vec2(42.0, 47.0), group_width),
|
||||
};
|
||||
}
|
||||
if mode == ResponsiveMaterialLayout::Reference {
|
||||
Self {
|
||||
height: UV_SECTION_HEIGHT,
|
||||
title,
|
||||
offset: uv_group(rect.min + egui::vec2(104.667, 7.0), 165.0),
|
||||
tiling: uv_group(rect.min + egui::vec2(332.333, 7.0), 164.0),
|
||||
}
|
||||
} else {
|
||||
Self {
|
||||
height: crate::design_system::COMPACT_UV_SECTION_HEIGHT,
|
||||
title,
|
||||
offset: uv_group(rect.min + egui::vec2(118.0, 7.0), 165.0),
|
||||
tiling: uv_group(rect.min + egui::vec2(118.5, 47.0), 164.0),
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fn uv_group(origin: egui::Pos2, group_width: f32) -> UvGroupGeometry {
|
||||
let local = |x: f32, y: f32, control_width: f32, height: f32| {
|
||||
let x = x.clamp(0.0, group_width.max(0.0));
|
||||
egui::Rect::from_min_size(
|
||||
origin + egui::vec2(x, y),
|
||||
egui::vec2(control_width.max(0.0).min(group_width - x), height),
|
||||
)
|
||||
};
|
||||
let reset = (group_width >= 164.0).then(|| local(group_width - 24.0, 8.0, 24.0, 24.0));
|
||||
UvGroupGeometry {
|
||||
label: local(0.0, 10.0, 25.0, 20.0),
|
||||
x: local(30.0, 8.0, 50.0, 24.0),
|
||||
y: local(86.0, 8.0, 50.0, 24.0),
|
||||
reset,
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, Copy, PartialEq)]
|
||||
pub(super) struct MaterialPanelGeometry {
|
||||
pub header: f32,
|
||||
pub collapsed_header: f32,
|
||||
pub asset_zone: f32,
|
||||
pub surface: f32,
|
||||
pub input_header: f32,
|
||||
pub input_row: f32,
|
||||
pub uv: f32,
|
||||
pub advanced_collapsed: f32,
|
||||
pub advanced_expanded: f32,
|
||||
pub preview: f32,
|
||||
pub identity: f32,
|
||||
pub outer_padding: f32,
|
||||
pub section_gap: f32,
|
||||
}
|
||||
|
||||
impl MaterialPanelGeometry {
|
||||
pub(super) const REFERENCE: Self = Self {
|
||||
header: HEADER_HEIGHT,
|
||||
collapsed_header: COLLAPSED_HEADER_HEIGHT,
|
||||
asset_zone: HEADER_HEIGHT,
|
||||
surface: SURFACE_SECTION_HEIGHT,
|
||||
input_header: INPUT_SECTION_HEADER_HEIGHT,
|
||||
input_row: PARAMETER_ROW_HEIGHT,
|
||||
uv: UV_SECTION_HEIGHT,
|
||||
advanced_collapsed: ADVANCED_COLLAPSED_HEIGHT,
|
||||
advanced_expanded: ADVANCED_EXPANDED_HEIGHT,
|
||||
preview: MATERIAL_PREVIEW_SIZE,
|
||||
identity: MATERIAL_IDENTITY_WIDTH,
|
||||
outer_padding: OUTER_PADDING,
|
||||
section_gap: SECTION_GAP,
|
||||
};
|
||||
|
||||
#[cfg(test)]
|
||||
pub(super) const fn slot_width(inspector_width: f32) -> f32 {
|
||||
inspector_width - OUTER_PADDING * 2.0
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
pub(super) const fn parameter_width(slot_width: f32) -> f32 {
|
||||
slot_width - 27.0
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
pub(super) const fn inputs_height(compact: bool, primary_rows: usize) -> f32 {
|
||||
INPUT_SECTION_HEADER_HEIGHT
|
||||
+ primary_rows as f32
|
||||
* if compact {
|
||||
crate::design_system::COMPACT_PARAMETER_ROW_HEIGHT
|
||||
} else {
|
||||
PARAMETER_ROW_HEIGHT
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn final_penpot_reference_geometry_is_exact() {
|
||||
let geometry = MaterialPanelGeometry::REFERENCE;
|
||||
assert_eq!(geometry.header, 82.0);
|
||||
assert_eq!(geometry.collapsed_header, 52.0);
|
||||
assert_eq!(geometry.asset_zone, 82.0);
|
||||
assert_eq!(geometry.surface, 46.0);
|
||||
assert_eq!(geometry.input_header, 24.0);
|
||||
assert_eq!(geometry.input_row, 32.0);
|
||||
assert_eq!(geometry.uv, 54.0);
|
||||
assert_eq!(geometry.advanced_collapsed, 30.0);
|
||||
assert_eq!(geometry.advanced_expanded, 178.0);
|
||||
assert_eq!(geometry.preview, 64.0);
|
||||
assert_eq!(geometry.identity, 229.5);
|
||||
assert_eq!(620.0 - OUTER_PADDING * 2.0, 596.0);
|
||||
assert_eq!(420.0 - OUTER_PADDING * 2.0, 396.0);
|
||||
assert_eq!(MaterialPanelGeometry::slot_width(620.0), 596.0);
|
||||
assert_eq!(MaterialPanelGeometry::slot_width(420.0), 396.0);
|
||||
assert_eq!(MaterialPanelGeometry::parameter_width(596.0), 569.0);
|
||||
assert_eq!(MaterialPanelGeometry::parameter_width(396.0), 369.0);
|
||||
assert_eq!(MaterialPanelGeometry::inputs_height(false, 6), 216.0);
|
||||
assert_eq!(MaterialPanelGeometry::inputs_height(true, 6), 372.0);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn surface_geometry_matches_both_exported_references() {
|
||||
let wide = SurfaceSectionGeometry::for_rect(egui::Rect::from_min_size(
|
||||
egui::Pos2::ZERO,
|
||||
egui::vec2(569.0, 46.0),
|
||||
));
|
||||
assert_eq!(
|
||||
wide.title,
|
||||
egui::Rect::from_min_size(egui::pos2(10.0, 10.0), egui::vec2(48.0, 26.0))
|
||||
);
|
||||
assert_eq!(
|
||||
wide.blend,
|
||||
egui::Rect::from_min_size(egui::pos2(66.0, 10.0), egui::vec2(250.0, 26.0))
|
||||
);
|
||||
assert_eq!(
|
||||
wide.packed,
|
||||
egui::Rect::from_min_size(egui::pos2(324.0, 11.0), egui::vec2(128.0, 24.0))
|
||||
);
|
||||
assert_eq!(
|
||||
wide.double_sided,
|
||||
egui::Rect::from_min_size(egui::pos2(460.0, 12.0), egui::vec2(99.0, 22.0))
|
||||
);
|
||||
|
||||
let narrow = SurfaceSectionGeometry::for_rect(egui::Rect::from_min_size(
|
||||
egui::Pos2::ZERO,
|
||||
egui::vec2(369.0, 46.0),
|
||||
));
|
||||
assert_eq!(
|
||||
narrow.blend,
|
||||
egui::Rect::from_min_size(egui::pos2(66.0, 10.0), egui::vec2(50.0, 26.0))
|
||||
);
|
||||
assert_eq!(
|
||||
narrow.packed,
|
||||
egui::Rect::from_min_size(egui::pos2(124.0, 11.0), egui::vec2(128.0, 24.0))
|
||||
);
|
||||
assert_eq!(
|
||||
narrow.double_sided,
|
||||
egui::Rect::from_min_size(egui::pos2(260.0, 12.0), egui::vec2(99.0, 22.0))
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn uv_geometry_centers_title_and_keeps_independent_resets() {
|
||||
for (width, height) in [(569.0, 54.0), (369.0, 94.0)] {
|
||||
let section = egui::Rect::from_min_size(egui::Pos2::ZERO, egui::vec2(width, height));
|
||||
let geometry = UvSectionGeometry::for_rect(section);
|
||||
assert_eq!(geometry.title.min, egui::pos2(12.0, 7.0));
|
||||
assert_eq!(geometry.title.height(), 14.0);
|
||||
assert_eq!(geometry.offset.x.size(), egui::vec2(50.0, 24.0));
|
||||
assert_eq!(geometry.offset.y.size(), egui::vec2(50.0, 24.0));
|
||||
assert!(geometry.offset.reset.is_some());
|
||||
assert!(geometry.tiling.reset.is_some());
|
||||
for rect in [
|
||||
geometry.title,
|
||||
geometry.offset.label,
|
||||
geometry.offset.x,
|
||||
geometry.offset.y,
|
||||
geometry.offset.reset.expect("reference reset"),
|
||||
geometry.tiling.label,
|
||||
geometry.tiling.x,
|
||||
geometry.tiling.y,
|
||||
geometry.tiling.reset.expect("reference reset"),
|
||||
] {
|
||||
assert!(section.contains_rect(rect));
|
||||
assert!(rect.is_finite());
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn transient_geometry_stays_finite_and_bounded() {
|
||||
let section = egui::Rect::from_min_size(egui::Pos2::ZERO, egui::vec2(300.0, 100.0));
|
||||
let surface = SurfaceSectionGeometry::for_rect(section);
|
||||
let uv = UvSectionGeometry::for_rect(section);
|
||||
for rect in [
|
||||
surface.title,
|
||||
surface.blend,
|
||||
surface.packed,
|
||||
surface.double_sided,
|
||||
] {
|
||||
assert!(rect.is_finite());
|
||||
assert!(section.contains_rect(rect));
|
||||
}
|
||||
for rect in [
|
||||
uv.title,
|
||||
uv.offset.label,
|
||||
uv.offset.x,
|
||||
uv.offset.y,
|
||||
uv.tiling.label,
|
||||
uv.tiling.x,
|
||||
uv.tiling.y,
|
||||
] {
|
||||
assert!(rect.is_finite());
|
||||
assert!(section.contains_rect(rect));
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn inspector_chrome_reduced_floor_keeps_the_penpot_compact_surface() {
|
||||
let section = egui::Rect::from_min_size(egui::Pos2::ZERO, egui::vec2(363.0, 46.0));
|
||||
let surface = SurfaceSectionGeometry::for_rect(section);
|
||||
assert_eq!(surface.height, 46.0);
|
||||
assert_eq!(surface.packed.min, egui::pos2(124.0, 11.0));
|
||||
assert_eq!(surface.packed.max, egui::pos2(252.0, 35.0));
|
||||
assert_eq!(surface.double_sided.min, egui::pos2(260.0, 12.0));
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,96 @@
|
||||
//! Material-slot and schema-driven parameter widgets shared by production and the gallery.
|
||||
|
||||
use bevy_math::{Vec2, Vec3};
|
||||
use egui;
|
||||
use egui_phosphor_icons::Icon;
|
||||
use material_schema::{
|
||||
ColorDesc, EditorAssetRef, MaterialInputDesc, MaterialInputSchema, MaterialInputSet,
|
||||
MaterialParameter, MaterialParameterValue, MaterialTextureBinding, ShaderPropertyType,
|
||||
TextureChannel,
|
||||
};
|
||||
|
||||
use crate::theme::TEXT_DIM;
|
||||
|
||||
mod advanced_preview;
|
||||
mod inputs;
|
||||
mod layout;
|
||||
mod panel;
|
||||
mod pickers;
|
||||
mod surface;
|
||||
mod texture_inputs;
|
||||
mod uv_transform;
|
||||
|
||||
pub use inputs::{
|
||||
apply_arm_texture_preset, apply_separate_texture_preset, compact_text_edit,
|
||||
default_value_for_shader_property, material_input_schema_editor,
|
||||
material_input_schema_editor_with_inheritance, optional_path_edit, packed_map_mode,
|
||||
parameter_value_matches_property, shader_kind_combo, shader_kind_picker, PackedMapMode,
|
||||
};
|
||||
pub use panel::{
|
||||
material_slot_panel, materials_section, MaterialHealth, MaterialLayerBadge,
|
||||
MaterialPickerCandidate, MaterialSlotAction, MaterialSlotPanelAction,
|
||||
MaterialSlotPanelResponse, MaterialSlotPanelViewModel, MaterialsSectionViewModel,
|
||||
};
|
||||
pub use surface::material_surface_options_ui;
|
||||
pub use texture_inputs::ensure_material_texture_binding;
|
||||
|
||||
#[derive(Clone, Debug, PartialEq, Eq)]
|
||||
pub enum MaterialLocateTarget {
|
||||
File(String),
|
||||
SubAsset {
|
||||
parent_path: String,
|
||||
sub_asset_id: String,
|
||||
label: String,
|
||||
source_path: Option<String>,
|
||||
},
|
||||
}
|
||||
|
||||
#[derive(Clone, Debug)]
|
||||
pub struct MaterialTextureCandidate {
|
||||
pub label: String,
|
||||
pub detail: String,
|
||||
pub reference: EditorAssetRef,
|
||||
pub locate: MaterialLocateTarget,
|
||||
pub thumbnail: MaterialThumbnailPresentation,
|
||||
}
|
||||
|
||||
#[derive(Default)]
|
||||
pub struct MaterialInputEditorResponse {
|
||||
pub accepted_drop: bool,
|
||||
pub locate: Option<MaterialLocateTarget>,
|
||||
pub browse_library: bool,
|
||||
}
|
||||
|
||||
#[derive(Clone, Copy, Debug, PartialEq)]
|
||||
pub enum MaterialThumbnailPresentation {
|
||||
Ready(egui::TextureId),
|
||||
Pending,
|
||||
Failed,
|
||||
Empty,
|
||||
}
|
||||
|
||||
#[derive(Clone, Copy)]
|
||||
enum TextureSlotSelection<'a> {
|
||||
Reference(Option<&'a EditorAssetRef>),
|
||||
}
|
||||
|
||||
#[derive(Default)]
|
||||
struct TextureSlotResponse {
|
||||
selected: Option<MaterialTextureCandidate>,
|
||||
locate: Option<MaterialLocateTarget>,
|
||||
clear: bool,
|
||||
accepted_drop: bool,
|
||||
browse_library: bool,
|
||||
}
|
||||
|
||||
fn fit_width(ui: &egui::Ui, min: f32, max: f32) -> f32 {
|
||||
let available = ui.available_width().max(1.0);
|
||||
available.min(max).max(min.min(available))
|
||||
}
|
||||
|
||||
fn icon_text(icon: Icon, size: f32) -> egui::RichText {
|
||||
egui::RichText::new(icon.as_str()).font(egui::FontId::new(
|
||||
size,
|
||||
egui::FontFamily::Name("phosphor-bold".into()),
|
||||
))
|
||||
}
|
||||
@@ -0,0 +1,773 @@
|
||||
//! Action-returning Penpot material-slot shell shared by primitive and mesh inspectors.
|
||||
|
||||
use egui;
|
||||
use egui_phosphor_icons::icons;
|
||||
use material_schema::{EditorAssetRef, MaterialShaderKind};
|
||||
|
||||
use super::layout::MaterialPanelGeometry;
|
||||
use super::MaterialThumbnailPresentation;
|
||||
use crate::design_system::controls::status;
|
||||
use crate::design_system::typography::TypeRole;
|
||||
use crate::design_system::{self, DesignPalette, HEADER_HEIGHT};
|
||||
|
||||
mod header_actions;
|
||||
|
||||
use header_actions::{expanded_status_actions, overflow_menu, SLOT_STATUS_ACTION_WIDTH};
|
||||
|
||||
// `Frame` reserves one pixel for the slot stroke before handing its child Ui to us. These local
|
||||
// origins compensate for that inset so the painted rail/caret/preview retain the exported board
|
||||
// coordinates relative to the outer slot rectangle.
|
||||
const SLOT_ACCENT_X: f32 = 7.0;
|
||||
const SLOT_CARET_CENTER_X: f32 = 22.0;
|
||||
const SLOT_PREVIEW_X: f32 = 34.0;
|
||||
const SHADER_CONTROL_WIDTH: f32 = 220.0;
|
||||
|
||||
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
|
||||
pub enum MaterialLayerBadge {
|
||||
ModelSource,
|
||||
ModelDefault,
|
||||
ProjectDefault,
|
||||
DefaultGrid,
|
||||
}
|
||||
|
||||
impl MaterialLayerBadge {
|
||||
pub const fn label(self) -> &'static str {
|
||||
match self {
|
||||
Self::ModelSource => "Model Source",
|
||||
Self::ModelDefault => "Model Default",
|
||||
Self::ProjectDefault => "Project Default",
|
||||
Self::DefaultGrid => "Default Grid",
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
|
||||
pub enum MaterialHealth {
|
||||
Healthy,
|
||||
Dirty,
|
||||
Processing,
|
||||
Broken,
|
||||
ReadOnly,
|
||||
}
|
||||
|
||||
impl MaterialHealth {
|
||||
fn presentation(self, palette: DesignPalette) -> (egui::Color32, &'static str, &'static str) {
|
||||
match self {
|
||||
Self::Healthy => (
|
||||
palette.text_secondary,
|
||||
"Compiled",
|
||||
"Material is resolved and up to date",
|
||||
),
|
||||
Self::Dirty => (
|
||||
palette.warning,
|
||||
"Unsaved",
|
||||
"Material has unsaved in-memory changes",
|
||||
),
|
||||
Self::Processing => (
|
||||
palette.accent,
|
||||
"Processing",
|
||||
"Derived material data is processing",
|
||||
),
|
||||
Self::Broken => (
|
||||
palette.error,
|
||||
"Failed",
|
||||
"Material reference or processing failed",
|
||||
),
|
||||
Self::ReadOnly => (
|
||||
palette.text_muted,
|
||||
"Read only",
|
||||
"This material cannot be edited in place",
|
||||
),
|
||||
}
|
||||
}
|
||||
|
||||
fn icon(self) -> egui_phosphor_icons::Icon {
|
||||
match self {
|
||||
Self::Healthy => icons::CHECK_CIRCLE,
|
||||
Self::Dirty => icons::PENCIL_SIMPLE,
|
||||
Self::Processing => icons::CIRCLE_NOTCH,
|
||||
Self::Broken => icons::WARNING_CIRCLE,
|
||||
Self::ReadOnly => icons::LOCK_SIMPLE,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone)]
|
||||
pub struct MaterialPickerCandidate {
|
||||
pub reference: EditorAssetRef,
|
||||
pub label: String,
|
||||
pub detail: String,
|
||||
pub thumbnail: MaterialThumbnailPresentation,
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone)]
|
||||
pub struct MaterialSlotPanelViewModel {
|
||||
pub slot_id: String,
|
||||
pub label: String,
|
||||
pub path: Option<String>,
|
||||
pub shader: String,
|
||||
pub shader_kind: Option<MaterialShaderKind>,
|
||||
pub can_edit_shader: bool,
|
||||
pub thumbnail: MaterialThumbnailPresentation,
|
||||
pub inherited: Option<MaterialLayerBadge>,
|
||||
pub health: MaterialHealth,
|
||||
pub assigned: Option<EditorAssetRef>,
|
||||
pub effective: Option<EditorAssetRef>,
|
||||
pub candidates: Vec<MaterialPickerCandidate>,
|
||||
pub drop_candidate: Option<MaterialPickerCandidate>,
|
||||
pub invalid_drop_reason: Option<String>,
|
||||
pub can_locate: bool,
|
||||
pub can_clear: bool,
|
||||
pub can_extract: bool,
|
||||
pub can_create_instance: bool,
|
||||
/// Initial disclosure used only until this slot has persisted UI state.
|
||||
pub parameters_initially_open: bool,
|
||||
/// Renderer arrays keep the full asset/action header visible when only parameters collapse.
|
||||
pub expanded_header_when_parameters_closed: bool,
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, PartialEq)]
|
||||
pub enum MaterialSlotAction {
|
||||
Assign {
|
||||
reference: EditorAssetRef,
|
||||
from_drop: bool,
|
||||
},
|
||||
BrowseLibrary,
|
||||
Locate,
|
||||
Clear,
|
||||
ExtractEditable,
|
||||
CreateInstance,
|
||||
SetShader(MaterialShaderKind),
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, PartialEq)]
|
||||
pub struct MaterialSlotPanelAction {
|
||||
pub slot_id: String,
|
||||
pub action: MaterialSlotAction,
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, Default, PartialEq, Eq)]
|
||||
pub struct MaterialsSectionViewModel {
|
||||
pub slot_ids: Vec<String>,
|
||||
}
|
||||
|
||||
pub struct MaterialSlotPanelResponse {
|
||||
pub actions: Vec<MaterialSlotPanelAction>,
|
||||
}
|
||||
|
||||
pub fn materials_section<R>(
|
||||
ui: &mut egui::Ui,
|
||||
_view: &MaterialsSectionViewModel,
|
||||
add_slots: impl FnOnce(&mut egui::Ui) -> R,
|
||||
) -> R {
|
||||
let start = ui.next_widget_position();
|
||||
let expanded = actor_materials_rect(ui.max_rect(), start.y);
|
||||
let mut child = ui.new_child(
|
||||
egui::UiBuilder::new()
|
||||
.max_rect(expanded)
|
||||
.layout(egui::Layout::top_down(egui::Align::Min)),
|
||||
);
|
||||
child.set_clip_rect(ui.clip_rect());
|
||||
let result = design_system::scope(&mut child, |ui| {
|
||||
let palette = design_system::palette(ui);
|
||||
ui.allocate_ui_with_layout(
|
||||
egui::vec2(
|
||||
ui.available_width().max(1.0),
|
||||
design_system::MATERIALS_HEADING_HEIGHT,
|
||||
),
|
||||
egui::Layout::left_to_right(egui::Align::Center),
|
||||
|ui| {
|
||||
ui.label(
|
||||
TypeRole::Title
|
||||
.text("Materials")
|
||||
.color(palette.text_primary),
|
||||
);
|
||||
},
|
||||
);
|
||||
// The top-down layout already contributes the design system's four-pixel item gap after
|
||||
// the 32 px heading. Add only the remaining four pixels so the slot begins at the Penpot
|
||||
// board's authored eight-pixel offset instead of drifting four pixels lower.
|
||||
ui.add_space(4.0);
|
||||
add_slots(ui)
|
||||
});
|
||||
// `min_rect` is not a safe content-height signal for a child hosted by a ScrollArea: nested
|
||||
// frames may temporarily inherit the parent's virtual extent even though their layout cursor
|
||||
// has only advanced through finite authored rows. Advancing from that rect creates a phantom
|
||||
// tail after multi-slot renderers and lets the Inspector scrollbar enter an empty region.
|
||||
// The cursor is the authoritative end of this top-down section.
|
||||
let used_bottom = materials_used_bottom(child.next_widget_position().y, start.y);
|
||||
ui.advance_cursor_after_rect(egui::Rect::from_min_max(
|
||||
egui::pos2(ui.max_rect().left(), start.y),
|
||||
egui::pos2(ui.max_rect().right(), used_bottom),
|
||||
));
|
||||
result
|
||||
}
|
||||
|
||||
fn actor_materials_rect(body: egui::Rect, start_y: f32) -> egui::Rect {
|
||||
// A ScrollArea content Ui has an effectively unbounded max-rect in its scrolling direction.
|
||||
// Carrying that bottom edge into the child gives the Materials section a phantom multi-screen
|
||||
// height even though its painted contents are finite. Seed only the exported width here; egui
|
||||
// grows the zero-height child as headings and slots are actually allocated.
|
||||
egui::Rect::from_min_size(
|
||||
egui::pos2(body.left(), start_y),
|
||||
egui::vec2(body.width(), 0.0),
|
||||
)
|
||||
}
|
||||
|
||||
fn materials_used_bottom(cursor_y: f32, start_y: f32) -> f32 {
|
||||
if cursor_y.is_finite() {
|
||||
cursor_y.max(start_y)
|
||||
} else {
|
||||
start_y
|
||||
}
|
||||
}
|
||||
|
||||
pub fn material_slot_panel(
|
||||
ui: &mut egui::Ui,
|
||||
id: impl std::hash::Hash,
|
||||
view: &MaterialSlotPanelViewModel,
|
||||
content_ui: impl FnOnce(&mut egui::Ui),
|
||||
diagnostics_ui: impl FnOnce(&mut egui::Ui),
|
||||
) -> MaterialSlotPanelResponse {
|
||||
design_system::scope(ui, |ui| {
|
||||
let palette = design_system::palette(ui);
|
||||
let id = ui.make_persistent_id(id);
|
||||
let open_id = id.with("parameters_open");
|
||||
let mut parameters_open = ui
|
||||
.ctx()
|
||||
.data_mut(|data| data.get_persisted::<bool>(open_id))
|
||||
.unwrap_or(view.parameters_initially_open);
|
||||
let mut slot_actions = Vec::new();
|
||||
|
||||
egui::Frame::new()
|
||||
.fill(palette.recessed)
|
||||
.stroke(egui::Stroke::new(1.0_f32, palette.border_strong))
|
||||
.corner_radius(egui::CornerRadius::same(8))
|
||||
.show(ui, |ui| {
|
||||
slot_header(
|
||||
ui,
|
||||
id,
|
||||
view,
|
||||
&mut parameters_open,
|
||||
&mut slot_actions,
|
||||
diagnostics_ui,
|
||||
);
|
||||
if parameters_open {
|
||||
parameter_body(ui, content_ui);
|
||||
}
|
||||
ui.ctx()
|
||||
.data_mut(|data| data.insert_persisted(open_id, parameters_open));
|
||||
});
|
||||
MaterialSlotPanelResponse {
|
||||
actions: slot_actions
|
||||
.into_iter()
|
||||
.map(|action| MaterialSlotPanelAction {
|
||||
slot_id: view.slot_id.clone(),
|
||||
action,
|
||||
})
|
||||
.collect(),
|
||||
}
|
||||
})
|
||||
}
|
||||
|
||||
fn slot_header(
|
||||
ui: &mut egui::Ui,
|
||||
id: egui::Id,
|
||||
view: &MaterialSlotPanelViewModel,
|
||||
open: &mut bool,
|
||||
actions: &mut Vec<MaterialSlotAction>,
|
||||
diagnostics_ui: impl FnOnce(&mut egui::Ui),
|
||||
) {
|
||||
let palette = design_system::palette(ui);
|
||||
let expanded_header = *open || view.expanded_header_when_parameters_closed;
|
||||
let height = if expanded_header {
|
||||
HEADER_HEIGHT
|
||||
} else {
|
||||
MaterialPanelGeometry::REFERENCE.collapsed_header
|
||||
};
|
||||
let width = ui.available_width().max(1.0);
|
||||
let (rect, response) = ui.allocate_exact_size(egui::vec2(width, height), egui::Sense::click());
|
||||
ui.painter().rect_filled(rect, 7.0, palette.recessed);
|
||||
ui.painter().rect_filled(
|
||||
egui::Rect::from_min_size(
|
||||
rect.min + egui::vec2(SLOT_ACCENT_X, 8.0),
|
||||
egui::vec2(3.0, height - 16.0),
|
||||
),
|
||||
2.0,
|
||||
palette.accent,
|
||||
);
|
||||
let caret_rect = egui::Rect::from_center_size(
|
||||
egui::pos2(rect.left() + SLOT_CARET_CENTER_X, rect.center().y),
|
||||
egui::vec2(18.0, 28.0),
|
||||
);
|
||||
let caret_icon = if *open {
|
||||
icons::CARET_DOWN
|
||||
} else {
|
||||
icons::CARET_RIGHT
|
||||
};
|
||||
let caret = ui.put(
|
||||
caret_rect,
|
||||
egui::Button::new(
|
||||
egui::RichText::new(caret_icon.as_str()).font(egui::FontId::new(
|
||||
12.0,
|
||||
egui::FontFamily::Name("phosphor-bold".into()),
|
||||
)),
|
||||
)
|
||||
.frame(false),
|
||||
);
|
||||
if caret.clicked() {
|
||||
*open = !*open;
|
||||
}
|
||||
let preview_size = if expanded_header { 64.0 } else { 32.0 };
|
||||
let preview_rect = egui::Rect::from_min_size(
|
||||
egui::pos2(
|
||||
rect.left() + SLOT_PREVIEW_X,
|
||||
rect.center().y - preview_size * 0.5,
|
||||
),
|
||||
egui::vec2(preview_size, preview_size),
|
||||
);
|
||||
let preview = material_thumbnail_at(ui, view, preview_rect);
|
||||
let action_width = SLOT_STATUS_ACTION_WIDTH;
|
||||
let identity_left = preview_rect.right() + 6.0;
|
||||
let actions_left = rect.right() - action_width - 8.0;
|
||||
let identity_right = (identity_left + design_system::MATERIAL_IDENTITY_WIDTH)
|
||||
.min(actions_left)
|
||||
.max(identity_left + 1.0);
|
||||
let identity_rect = egui::Rect::from_min_max(
|
||||
egui::pos2(
|
||||
identity_left,
|
||||
rect.top() + if expanded_header { 8.0 } else { 7.0 },
|
||||
),
|
||||
egui::pos2(
|
||||
identity_right,
|
||||
rect.bottom() - if expanded_header { 8.0 } else { 7.0 },
|
||||
),
|
||||
);
|
||||
let identity = ui
|
||||
.scope_builder(egui::UiBuilder::new().max_rect(identity_rect), |ui| {
|
||||
ui.set_clip_rect(identity_rect.intersect(ui.clip_rect()));
|
||||
if expanded_header {
|
||||
material_identity(ui, view, actions)
|
||||
} else {
|
||||
compact_material_identity(ui, view)
|
||||
}
|
||||
})
|
||||
.inner;
|
||||
let actions_rect = egui::Rect::from_min_size(
|
||||
egui::pos2(
|
||||
actions_left,
|
||||
rect.top() + if expanded_header { 9.0 } else { 7.0 },
|
||||
),
|
||||
egui::vec2(
|
||||
action_width,
|
||||
if expanded_header { 64.0 } else { height - 14.0 },
|
||||
),
|
||||
);
|
||||
if expanded_header {
|
||||
expanded_status_actions(ui, actions_rect, view, actions, diagnostics_ui, palette);
|
||||
} else {
|
||||
ui.scope_builder(egui::UiBuilder::new().max_rect(actions_rect), |ui| {
|
||||
ui.with_layout(egui::Layout::right_to_left(egui::Align::Center), |ui| {
|
||||
overflow_menu(ui, view, actions, diagnostics_ui);
|
||||
let (color, label, tooltip) = view.health.presentation(palette);
|
||||
ui.horizontal(|ui| status(ui, view.health.icon(), color, label, tooltip));
|
||||
});
|
||||
});
|
||||
}
|
||||
if response.clicked() {
|
||||
if let Some(pointer) = ui.input(|input| input.pointer.interact_pos()) {
|
||||
if !caret_rect.contains(pointer)
|
||||
&& !preview_rect.contains(pointer)
|
||||
&& !identity_rect.contains(pointer)
|
||||
&& !actions_rect.contains(pointer)
|
||||
{
|
||||
*open = !*open;
|
||||
}
|
||||
}
|
||||
}
|
||||
super::pickers::material_picker_popup(
|
||||
ui,
|
||||
id.with("material_picker"),
|
||||
&preview.union(identity),
|
||||
view,
|
||||
actions,
|
||||
);
|
||||
if response.hovered()
|
||||
&& view.drop_candidate.is_some()
|
||||
&& ui.input(|input| input.pointer.any_released())
|
||||
{
|
||||
if let Some(candidate) = view.drop_candidate.as_ref() {
|
||||
actions.push(MaterialSlotAction::Assign {
|
||||
reference: candidate.reference.clone(),
|
||||
from_drop: true,
|
||||
});
|
||||
}
|
||||
}
|
||||
if response.hovered() {
|
||||
if let Some(reason) = view.invalid_drop_reason.as_deref() {
|
||||
response.on_hover_text(reason);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fn compact_material_identity(
|
||||
ui: &mut egui::Ui,
|
||||
view: &MaterialSlotPanelViewModel,
|
||||
) -> egui::Response {
|
||||
let palette = design_system::palette(ui);
|
||||
let name = ui
|
||||
.add(
|
||||
egui::Label::new(
|
||||
TypeRole::AssetTitle
|
||||
.text(&view.label)
|
||||
.color(palette.text_primary),
|
||||
)
|
||||
.truncate()
|
||||
.sense(egui::Sense::click()),
|
||||
)
|
||||
.on_hover_text(&view.label);
|
||||
let detail_text = view
|
||||
.inherited
|
||||
.map(MaterialLayerBadge::label)
|
||||
.unwrap_or(view.shader.as_str());
|
||||
let detail = ui
|
||||
.add(
|
||||
egui::Label::new(TypeRole::Small.text(detail_text).color(palette.text_muted))
|
||||
.truncate()
|
||||
.sense(egui::Sense::click()),
|
||||
)
|
||||
.on_hover_text(detail_text);
|
||||
name.union(detail)
|
||||
}
|
||||
|
||||
fn parameter_body(ui: &mut egui::Ui, content_ui: impl FnOnce(&mut egui::Ui)) {
|
||||
let palette = design_system::palette(ui);
|
||||
egui::Frame::new()
|
||||
.fill(palette.recessed)
|
||||
.inner_margin(egui::Margin {
|
||||
// The parent slot stroke already contributes one pixel on each side. Reclaim it here
|
||||
// so the parameter sections are the authored 569/369 px instead of 567/367 px.
|
||||
left: 18,
|
||||
right: 7,
|
||||
// Own the exported PARAMETERS origin here so every primitive/static/skinned caller
|
||||
// receives the same position independent of its surrounding component chrome.
|
||||
top: 21,
|
||||
bottom: 8,
|
||||
})
|
||||
.show(ui, |ui| {
|
||||
let mut measure = egui::text::LayoutJob::default();
|
||||
measure.append(
|
||||
"PARAMETERS",
|
||||
0.0,
|
||||
egui::TextFormat {
|
||||
font_id: TypeRole::Eyebrow.font(),
|
||||
extra_letter_spacing: 0.6,
|
||||
color: egui::Color32::TRANSPARENT,
|
||||
..Default::default()
|
||||
},
|
||||
);
|
||||
// Penpot positions the 9 px eyebrow two raster pixels above egui's default label
|
||||
// baseline. Keep the label's normal allocation so section flow remains unchanged,
|
||||
// then paint the visible glyphs at the authored baseline.
|
||||
let response = ui.label(measure);
|
||||
let mut visible = egui::text::LayoutJob::default();
|
||||
visible.append(
|
||||
"PARAMETERS",
|
||||
0.0,
|
||||
egui::TextFormat {
|
||||
font_id: TypeRole::Eyebrow.font(),
|
||||
extra_letter_spacing: 0.6,
|
||||
color: palette.accent,
|
||||
..Default::default()
|
||||
},
|
||||
);
|
||||
let galley = ui.painter().layout_job(visible);
|
||||
ui.painter().galley(
|
||||
response.rect.min - egui::vec2(0.0, 5.0),
|
||||
galley,
|
||||
palette.accent,
|
||||
);
|
||||
let spine_x = ui.min_rect().left() - 11.0;
|
||||
let spine_top = ui.cursor().top();
|
||||
content_ui(ui);
|
||||
let spine_bottom = ui.min_rect().bottom().max(spine_top);
|
||||
ui.painter().vline(
|
||||
spine_x,
|
||||
spine_top..=spine_bottom,
|
||||
egui::Stroke::new(1.0_f32, palette.accent_dark),
|
||||
);
|
||||
});
|
||||
}
|
||||
|
||||
fn material_identity(
|
||||
ui: &mut egui::Ui,
|
||||
view: &MaterialSlotPanelViewModel,
|
||||
actions: &mut Vec<MaterialSlotAction>,
|
||||
) -> egui::Response {
|
||||
let palette = design_system::palette(ui);
|
||||
let name = ui
|
||||
.add(
|
||||
egui::Label::new(
|
||||
TypeRole::AssetTitle
|
||||
.text(&view.label)
|
||||
.color(palette.text_primary),
|
||||
)
|
||||
.truncate()
|
||||
.sense(egui::Sense::click()),
|
||||
)
|
||||
.on_hover_text(&view.label);
|
||||
let unassigned = view.assigned.is_none() && view.effective.is_none();
|
||||
let path = view.path.as_deref().unwrap_or(if unassigned {
|
||||
"Drop a material here or choose from the browser"
|
||||
} else {
|
||||
"Engine built-in material"
|
||||
});
|
||||
let identity = view.inherited.map_or_else(
|
||||
|| path.to_string(),
|
||||
|layer| format!("{path} · {}", layer.label()),
|
||||
);
|
||||
let detail = ui
|
||||
.add(
|
||||
egui::Label::new(TypeRole::Small.text(&identity).color(palette.text_muted))
|
||||
.truncate()
|
||||
.sense(egui::Sense::click()),
|
||||
)
|
||||
.on_hover_text(&identity);
|
||||
if view.can_edit_shader {
|
||||
if let Some(mut kind) = view.shader_kind {
|
||||
egui::ComboBox::from_id_salt("material_identity_shader_kind")
|
||||
.selected_text(&view.shader)
|
||||
.width(SHADER_CONTROL_WIDTH.min(ui.available_width().max(1.0)))
|
||||
.show_ui(ui, |ui| {
|
||||
ui.selectable_value(&mut kind, MaterialShaderKind::StandardLit, "Standard Lit");
|
||||
ui.selectable_value(&mut kind, MaterialShaderKind::Unlit, "Unlit");
|
||||
ui.selectable_value(&mut kind, MaterialShaderKind::Custom, "Custom Surface");
|
||||
});
|
||||
if Some(kind) != view.shader_kind {
|
||||
actions.push(MaterialSlotAction::SetShader(kind));
|
||||
}
|
||||
}
|
||||
} else if !view.shader.is_empty() {
|
||||
ui.add_sized(
|
||||
[
|
||||
SHADER_CONTROL_WIDTH.min(ui.available_width().max(1.0)),
|
||||
22.0,
|
||||
],
|
||||
egui::Label::new(
|
||||
TypeRole::Body
|
||||
.text(&view.shader)
|
||||
.color(palette.text_secondary),
|
||||
),
|
||||
);
|
||||
}
|
||||
name.union(detail)
|
||||
}
|
||||
|
||||
fn material_thumbnail_at(
|
||||
ui: &mut egui::Ui,
|
||||
view: &MaterialSlotPanelViewModel,
|
||||
rect: egui::Rect,
|
||||
) -> egui::Response {
|
||||
let palette = design_system::palette(ui);
|
||||
let response = ui.interact(
|
||||
rect,
|
||||
ui.make_persistent_id(("material_preview", &view.slot_id)),
|
||||
egui::Sense::click(),
|
||||
);
|
||||
let size = rect.width();
|
||||
let cell = size / 4.0;
|
||||
for row in 0..4 {
|
||||
for column in 0..4 {
|
||||
ui.painter().rect_filled(
|
||||
egui::Rect::from_min_size(
|
||||
rect.min + egui::vec2(column as f32 * cell, row as f32 * cell),
|
||||
egui::vec2(cell, cell),
|
||||
)
|
||||
.intersect(rect),
|
||||
0.0,
|
||||
if (row + column) % 2 == 0 {
|
||||
palette.checker
|
||||
} else {
|
||||
palette.recessed
|
||||
},
|
||||
);
|
||||
}
|
||||
}
|
||||
match view.thumbnail {
|
||||
MaterialThumbnailPresentation::Ready(texture) => {
|
||||
ui.painter().image(
|
||||
texture,
|
||||
rect.shrink(2.0),
|
||||
egui::Rect::from_min_max(egui::Pos2::ZERO, egui::pos2(1.0, 1.0)),
|
||||
egui::Color32::WHITE,
|
||||
);
|
||||
}
|
||||
MaterialThumbnailPresentation::Pending => {
|
||||
ui.painter().text(
|
||||
rect.center(),
|
||||
egui::Align2::CENTER_CENTER,
|
||||
icons::CIRCLE_NOTCH.as_str(),
|
||||
egui::FontId::new(22.0, egui::FontFamily::Name("phosphor-regular".into())),
|
||||
palette.text_secondary,
|
||||
);
|
||||
}
|
||||
MaterialThumbnailPresentation::Failed => {
|
||||
ui.painter().text(
|
||||
rect.center(),
|
||||
egui::Align2::CENTER_CENTER,
|
||||
icons::WARNING.as_str(),
|
||||
egui::FontId::new(22.0, egui::FontFamily::Name("phosphor-regular".into())),
|
||||
palette.error,
|
||||
);
|
||||
}
|
||||
MaterialThumbnailPresentation::Empty => {
|
||||
ui.painter().text(
|
||||
rect.center(),
|
||||
egui::Align2::CENTER_CENTER,
|
||||
icons::PALETTE.as_str(),
|
||||
egui::FontId::new(22.0, egui::FontFamily::Name("phosphor-regular".into())),
|
||||
palette.text_muted,
|
||||
);
|
||||
}
|
||||
}
|
||||
ui.painter().rect_stroke(
|
||||
rect,
|
||||
4.0,
|
||||
egui::Stroke::new(1.0_f32, palette.border),
|
||||
egui::StrokeKind::Inside,
|
||||
);
|
||||
response.on_hover_text(format!("Open {} material picker", view.label))
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
fn view() -> MaterialSlotPanelViewModel {
|
||||
MaterialSlotPanelViewModel {
|
||||
slot_id: "slot:test".into(),
|
||||
label: "M_Wood_Planks".into(),
|
||||
path: Some("materials/wood/M_Wood_Planks.mat".into()),
|
||||
shader: "Standard Lit".into(),
|
||||
shader_kind: Some(MaterialShaderKind::StandardLit),
|
||||
can_edit_shader: true,
|
||||
thumbnail: MaterialThumbnailPresentation::Pending,
|
||||
inherited: None,
|
||||
health: MaterialHealth::Healthy,
|
||||
assigned: None,
|
||||
effective: None,
|
||||
candidates: Vec::new(),
|
||||
drop_candidate: None,
|
||||
invalid_drop_reason: None,
|
||||
can_locate: true,
|
||||
can_clear: true,
|
||||
can_extract: false,
|
||||
can_create_instance: true,
|
||||
parameters_initially_open: true,
|
||||
expanded_header_when_parameters_closed: false,
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn slot_header_insets_match_the_current_penpot_export() {
|
||||
const OUTER_FRAME_STROKE_INSET: f32 = 1.0;
|
||||
assert_eq!(SLOT_ACCENT_X + OUTER_FRAME_STROKE_INSET, 8.0);
|
||||
assert_eq!(SLOT_CARET_CENTER_X + OUTER_FRAME_STROKE_INSET, 23.0);
|
||||
assert_eq!(SLOT_PREVIEW_X + OUTER_FRAME_STROKE_INSET, 35.0);
|
||||
assert_eq!(SLOT_PREVIEW_X - (SLOT_CARET_CENTER_X + 6.0), 6.0);
|
||||
assert_eq!(SLOT_STATUS_ACTION_WIDTH, 140.0);
|
||||
assert_eq!(SHADER_CONTROL_WIDTH, 220.0);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn actor_component_body_preserves_penpot_slot_widths() {
|
||||
let wide_body = egui::Rect::from_min_size(egui::Pos2::ZERO, egui::vec2(596.0, 700.0));
|
||||
let compact_body = egui::Rect::from_min_size(egui::Pos2::ZERO, egui::vec2(396.0, 700.0));
|
||||
|
||||
let wide = actor_materials_rect(wide_body, 32.0);
|
||||
let compact = actor_materials_rect(compact_body, 32.0);
|
||||
|
||||
assert_eq!(wide.width(), 596.0);
|
||||
assert_eq!(compact.width(), 396.0);
|
||||
assert_eq!(wide.left(), 0.0);
|
||||
assert_eq!(compact.left(), 0.0);
|
||||
assert_eq!(wide.top(), 32.0);
|
||||
assert_eq!(compact.top(), 32.0);
|
||||
assert_eq!(wide.height(), 0.0);
|
||||
assert_eq!(compact.height(), 0.0);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn materials_height_uses_the_finite_layout_cursor_not_a_virtual_scroll_extent() {
|
||||
assert_eq!(materials_used_bottom(948.0, 320.0), 948.0);
|
||||
assert_eq!(materials_used_bottom(240.0, 320.0), 320.0);
|
||||
assert_eq!(materials_used_bottom(f32::INFINITY, 320.0), 320.0);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn penpot_direct_assignment_has_no_redundant_explicit_badge() {
|
||||
assert!(view().inherited.is_none());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn penpot_assignment_action_carries_exact_stable_reference() {
|
||||
let reference = EditorAssetRef::new("asset-id", "material:source", "M_Wood");
|
||||
let action = MaterialSlotPanelAction {
|
||||
slot_id: "slot:test".into(),
|
||||
action: MaterialSlotAction::Assign {
|
||||
reference: reference.clone(),
|
||||
from_drop: false,
|
||||
},
|
||||
};
|
||||
assert_eq!(
|
||||
action,
|
||||
MaterialSlotPanelAction {
|
||||
slot_id: "slot:test".into(),
|
||||
action: MaterialSlotAction::Assign {
|
||||
reference,
|
||||
from_drop: false,
|
||||
},
|
||||
}
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn penpot_supported_material_states_share_one_view_model() {
|
||||
for health in [
|
||||
MaterialHealth::Healthy,
|
||||
MaterialHealth::Dirty,
|
||||
MaterialHealth::Processing,
|
||||
MaterialHealth::Broken,
|
||||
MaterialHealth::ReadOnly,
|
||||
] {
|
||||
let mut view = view();
|
||||
view.health = health;
|
||||
let palette = DesignPalette::from(crate::theme::BLACKSITE_PALETTE);
|
||||
assert!(!view.health.presentation(palette).1.is_empty());
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn penpot_material_statuses_use_semantic_phosphor_icons() {
|
||||
assert_eq!(
|
||||
MaterialHealth::Healthy.icon().as_str(),
|
||||
icons::CHECK_CIRCLE.as_str()
|
||||
);
|
||||
assert_eq!(
|
||||
MaterialHealth::Dirty.icon().as_str(),
|
||||
icons::PENCIL_SIMPLE.as_str()
|
||||
);
|
||||
assert_eq!(
|
||||
MaterialHealth::Processing.icon().as_str(),
|
||||
icons::CIRCLE_NOTCH.as_str()
|
||||
);
|
||||
assert_eq!(
|
||||
MaterialHealth::Broken.icon().as_str(),
|
||||
icons::WARNING_CIRCLE.as_str()
|
||||
);
|
||||
assert_eq!(
|
||||
MaterialHealth::ReadOnly.icon().as_str(),
|
||||
icons::LOCK_SIMPLE.as_str()
|
||||
);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,238 @@
|
||||
//! Exact Penpot status/action geometry for an expanded material-slot header.
|
||||
|
||||
use egui;
|
||||
use egui_phosphor_icons::icons;
|
||||
|
||||
use super::{MaterialSlotAction, MaterialSlotPanelViewModel};
|
||||
use crate::design_system::controls::{icon_button, icon_label, status};
|
||||
use crate::design_system::typography::TypeRole;
|
||||
use crate::design_system::{self, DesignPalette};
|
||||
|
||||
pub(super) const SLOT_STATUS_ACTION_WIDTH: f32 = 140.0;
|
||||
|
||||
#[derive(Debug, Clone, Copy, PartialEq)]
|
||||
struct ExpandedHeaderActionGeometry {
|
||||
status: egui::Rect,
|
||||
menu: egui::Rect,
|
||||
browse: egui::Rect,
|
||||
locate: egui::Rect,
|
||||
clear: egui::Rect,
|
||||
}
|
||||
|
||||
fn geometry(rect: egui::Rect) -> ExpandedHeaderActionGeometry {
|
||||
let status_row = egui::Rect::from_min_size(
|
||||
rect.min + egui::vec2(0.0, 5.333),
|
||||
egui::vec2(SLOT_STATUS_ACTION_WIDTH, 24.0),
|
||||
);
|
||||
let menu = egui::Rect::from_min_size(
|
||||
status_row.min + egui::vec2(116.0, 0.0),
|
||||
egui::vec2(24.0, 24.0),
|
||||
);
|
||||
let action_row = rect.min + egui::vec2(0.0, 34.667);
|
||||
ExpandedHeaderActionGeometry {
|
||||
status: egui::Rect::from_min_max(
|
||||
status_row.min,
|
||||
egui::pos2(menu.left() - 5.0, status_row.bottom()),
|
||||
),
|
||||
menu,
|
||||
browse: egui::Rect::from_min_size(
|
||||
action_row + egui::vec2(56.0, 0.0),
|
||||
egui::vec2(24.0, 24.0),
|
||||
),
|
||||
locate: egui::Rect::from_min_size(
|
||||
action_row + egui::vec2(86.0, 0.0),
|
||||
egui::vec2(24.0, 24.0),
|
||||
),
|
||||
clear: egui::Rect::from_min_size(
|
||||
action_row + egui::vec2(116.0, 0.0),
|
||||
egui::vec2(24.0, 24.0),
|
||||
),
|
||||
}
|
||||
}
|
||||
|
||||
pub(super) fn expanded_status_actions(
|
||||
ui: &mut egui::Ui,
|
||||
rect: egui::Rect,
|
||||
view: &MaterialSlotPanelViewModel,
|
||||
actions: &mut Vec<MaterialSlotAction>,
|
||||
diagnostics_ui: impl FnOnce(&mut egui::Ui),
|
||||
palette: DesignPalette,
|
||||
) {
|
||||
if view.assigned.is_none() && view.effective.is_none() {
|
||||
let button_rect = egui::Rect::from_min_size(
|
||||
rect.right_bottom() - egui::vec2(116.0, 28.0),
|
||||
egui::vec2(116.0, 28.0),
|
||||
);
|
||||
if rect_scope(ui, button_rect, |ui| {
|
||||
ui.add(
|
||||
egui::Button::new(icon_label(
|
||||
icons::FOLDER_OPEN,
|
||||
"Choose material",
|
||||
TypeRole::Control,
|
||||
13.0,
|
||||
palette.text_primary,
|
||||
))
|
||||
.min_size(button_rect.size()),
|
||||
)
|
||||
.clicked()
|
||||
}) {
|
||||
actions.push(MaterialSlotAction::BrowseLibrary);
|
||||
}
|
||||
return;
|
||||
}
|
||||
let geometry = geometry(rect);
|
||||
rect_scope(ui, geometry.status, |ui| {
|
||||
ui.with_layout(egui::Layout::right_to_left(egui::Align::Center), |ui| {
|
||||
let (color, label, tooltip) = view.health.presentation(palette);
|
||||
status(ui, view.health.icon(), color, label, tooltip);
|
||||
});
|
||||
});
|
||||
rect_scope(ui, geometry.menu, |ui| {
|
||||
overflow_menu(ui, view, actions, diagnostics_ui);
|
||||
});
|
||||
|
||||
for (button_rect, action, enabled, icon, tooltip) in [
|
||||
(
|
||||
geometry.browse,
|
||||
MaterialSlotAction::BrowseLibrary,
|
||||
true,
|
||||
icons::FOLDER_OPEN,
|
||||
"Browse project materials",
|
||||
),
|
||||
(
|
||||
geometry.locate,
|
||||
MaterialSlotAction::Locate,
|
||||
view.can_locate,
|
||||
icons::CROSSHAIR,
|
||||
"Locate in Content Browser",
|
||||
),
|
||||
(
|
||||
geometry.clear,
|
||||
MaterialSlotAction::Clear,
|
||||
view.can_clear,
|
||||
icons::X,
|
||||
"Clear actor assignment",
|
||||
),
|
||||
] {
|
||||
if !enabled {
|
||||
continue;
|
||||
}
|
||||
let clicked = rect_scope(ui, button_rect, |ui| {
|
||||
icon_button(ui, icon, tooltip, true).clicked()
|
||||
});
|
||||
if clicked {
|
||||
actions.push(action);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
pub(super) fn overflow_menu(
|
||||
ui: &mut egui::Ui,
|
||||
view: &MaterialSlotPanelViewModel,
|
||||
actions: &mut Vec<MaterialSlotAction>,
|
||||
diagnostics_ui: impl FnOnce(&mut egui::Ui),
|
||||
) {
|
||||
let palette = design_system::palette(ui);
|
||||
ui.menu_button(
|
||||
egui::RichText::new(icons::DOTS_THREE.as_str()).font(egui::FontId::new(
|
||||
16.0,
|
||||
egui::FontFamily::Name("phosphor-bold".into()),
|
||||
)),
|
||||
|ui| {
|
||||
if view.can_locate && menu_action(ui, icons::CROSSHAIR, "Locate", palette.text_primary)
|
||||
{
|
||||
actions.push(MaterialSlotAction::Locate);
|
||||
ui.close();
|
||||
}
|
||||
if menu_action(
|
||||
ui,
|
||||
icons::FOLDER_OPEN,
|
||||
"Browse Asset Library",
|
||||
palette.text_primary,
|
||||
) {
|
||||
actions.push(MaterialSlotAction::BrowseLibrary);
|
||||
ui.close();
|
||||
}
|
||||
if view.can_clear && menu_action(ui, icons::X, "Clear material", palette.text_primary) {
|
||||
actions.push(MaterialSlotAction::Clear);
|
||||
ui.close();
|
||||
}
|
||||
if view.can_create_instance
|
||||
&& menu_action(
|
||||
ui,
|
||||
icons::COPY,
|
||||
"Create Instance and Assign",
|
||||
palette.text_primary,
|
||||
)
|
||||
{
|
||||
actions.push(MaterialSlotAction::CreateInstance);
|
||||
ui.close();
|
||||
}
|
||||
if view.can_extract
|
||||
&& menu_action(ui, icons::EXPORT, "Extract Editable…", palette.text_primary)
|
||||
{
|
||||
actions.push(MaterialSlotAction::ExtractEditable);
|
||||
ui.close();
|
||||
}
|
||||
ui.separator();
|
||||
ui.label(TypeRole::Section.text("Source & Diagnostics"));
|
||||
diagnostics_ui(ui);
|
||||
},
|
||||
)
|
||||
.response
|
||||
.on_hover_text("Material actions and diagnostics");
|
||||
}
|
||||
|
||||
fn menu_action(
|
||||
ui: &mut egui::Ui,
|
||||
icon: egui_phosphor_icons::Icon,
|
||||
label: &str,
|
||||
color: egui::Color32,
|
||||
) -> bool {
|
||||
ui.add(egui::Button::new(icon_label(
|
||||
icon,
|
||||
label,
|
||||
TypeRole::Control,
|
||||
14.0,
|
||||
color,
|
||||
)))
|
||||
.clicked()
|
||||
}
|
||||
|
||||
fn rect_scope<R>(
|
||||
ui: &mut egui::Ui,
|
||||
rect: egui::Rect,
|
||||
add_contents: impl FnOnce(&mut egui::Ui) -> R,
|
||||
) -> R {
|
||||
ui.scope_builder(egui::UiBuilder::new().max_rect(rect), |ui| {
|
||||
ui.set_clip_rect(rect.intersect(ui.clip_rect()));
|
||||
add_contents(ui)
|
||||
})
|
||||
.inner
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn expanded_status_and_actions_match_the_penpot_header_geometry() {
|
||||
let rect = egui::Rect::from_min_size(egui::pos2(448.0, 9.0), egui::vec2(140.0, 64.0));
|
||||
let geometry = geometry(rect);
|
||||
assert_eq!(geometry.menu.min, egui::pos2(564.0, 14.333));
|
||||
assert_eq!(geometry.browse.min, egui::pos2(504.0, 43.667));
|
||||
assert_eq!(geometry.locate.min, egui::pos2(534.0, 43.667));
|
||||
assert_eq!(geometry.clear.min, egui::pos2(564.0, 43.667));
|
||||
assert_eq!(geometry.menu.size(), egui::vec2(24.0, 24.0));
|
||||
assert_eq!(geometry.clear.size(), egui::vec2(24.0, 24.0));
|
||||
for child in [
|
||||
geometry.status,
|
||||
geometry.menu,
|
||||
geometry.browse,
|
||||
geometry.locate,
|
||||
geometry.clear,
|
||||
] {
|
||||
assert!(rect.contains_rect(child));
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,420 @@
|
||||
//! Penpot-styled material and texture asset pickers.
|
||||
|
||||
use egui;
|
||||
use egui_phosphor_icons::icons;
|
||||
use material_schema::EditorAssetRef;
|
||||
|
||||
use super::panel::{MaterialPickerCandidate, MaterialSlotAction, MaterialSlotPanelViewModel};
|
||||
use super::{MaterialTextureCandidate, MaterialThumbnailPresentation, TextureSlotResponse};
|
||||
use crate::design_system;
|
||||
use crate::design_system::controls::icon_label;
|
||||
use crate::design_system::typography::TypeRole;
|
||||
|
||||
const MATERIAL_PICKER_WIDTH: f32 = 244.0;
|
||||
const TEXTURE_PICKER_WIDTH: f32 = 420.0;
|
||||
const PICKER_ROW_HEIGHT: f32 = 44.0;
|
||||
const PICKER_THUMBNAIL: f32 = 36.0;
|
||||
|
||||
pub(super) fn material_picker_popup(
|
||||
_ui: &mut egui::Ui,
|
||||
id: egui::Id,
|
||||
anchor: &egui::Response,
|
||||
view: &MaterialSlotPanelViewModel,
|
||||
actions: &mut Vec<MaterialSlotAction>,
|
||||
) {
|
||||
egui::Popup::menu(anchor)
|
||||
.id(id)
|
||||
.width(MATERIAL_PICKER_WIDTH)
|
||||
.show(|ui| {
|
||||
ui.label(
|
||||
TypeRole::Section
|
||||
.text("Material Assets")
|
||||
.color(design_system::palette(ui).text_primary),
|
||||
);
|
||||
if let Some(current) = view.effective.as_ref() {
|
||||
if let Some(candidate) = find_material_candidate(&view.candidates, current) {
|
||||
material_menu_row(ui, candidate, true, actions);
|
||||
} else {
|
||||
unresolved_material_menu_row(ui, current);
|
||||
}
|
||||
}
|
||||
|
||||
let recent_keys = recent_keys(ui, "material_picker_recents");
|
||||
let recent = candidates_for_recent_keys(&view.candidates, &recent_keys);
|
||||
for candidate in recent.into_iter().take(4) {
|
||||
let selected = view
|
||||
.effective
|
||||
.as_ref()
|
||||
.is_some_and(|current| same_reference(current, &candidate.reference));
|
||||
if !selected {
|
||||
material_menu_row(ui, candidate, false, actions);
|
||||
}
|
||||
}
|
||||
picker_footer(ui, view.assigned.is_some(), actions);
|
||||
});
|
||||
}
|
||||
|
||||
pub(super) fn texture_picker_popup(
|
||||
_ui: &mut egui::Ui,
|
||||
id: egui::Id,
|
||||
anchor: &egui::Response,
|
||||
candidates: &[MaterialTextureCandidate],
|
||||
selected: Option<&MaterialTextureCandidate>,
|
||||
response: &mut TextureSlotResponse,
|
||||
) {
|
||||
egui::Popup::menu(anchor)
|
||||
.id(id)
|
||||
.width(TEXTURE_PICKER_WIDTH)
|
||||
.show(|ui| {
|
||||
picker_heading(
|
||||
ui,
|
||||
"Select Texture",
|
||||
"Project textures and imported subassets",
|
||||
);
|
||||
if let Some(current) = selected {
|
||||
picker_section_label(ui, "CURRENT");
|
||||
texture_candidate_row(ui, current, true, response);
|
||||
}
|
||||
let recent_keys = recent_keys(ui, "texture_picker_recents");
|
||||
let recent = candidates_for_recent_texture_keys(candidates, &recent_keys);
|
||||
if !recent.is_empty() {
|
||||
picker_section_label(ui, "RECENT");
|
||||
for candidate in recent.into_iter().take(4) {
|
||||
texture_candidate_row(ui, candidate, false, response);
|
||||
}
|
||||
}
|
||||
picker_section_label(ui, "PROJECT TEXTURES");
|
||||
egui::ScrollArea::vertical()
|
||||
.id_salt(id.with("project_textures"))
|
||||
.max_height(240.0)
|
||||
.auto_shrink([false, true])
|
||||
.show(ui, |ui| {
|
||||
if candidates.is_empty() {
|
||||
empty_picker_row(ui, "No project textures");
|
||||
}
|
||||
for candidate in candidates {
|
||||
let selected = selected.is_some_and(|current| {
|
||||
same_reference(¤t.reference, &candidate.reference)
|
||||
});
|
||||
texture_candidate_row(ui, candidate, selected, response);
|
||||
}
|
||||
});
|
||||
let palette = design_system::palette(ui);
|
||||
ui.separator();
|
||||
if ui
|
||||
.add(egui::Button::new(icon_label(
|
||||
icons::FOLDER_OPEN,
|
||||
"Browse Asset Library",
|
||||
TypeRole::Control,
|
||||
14.0,
|
||||
palette.text_primary,
|
||||
)))
|
||||
.clicked()
|
||||
{
|
||||
response.browse_library = true;
|
||||
ui.close();
|
||||
}
|
||||
if selected.is_some()
|
||||
&& ui
|
||||
.add(egui::Button::new(icon_label(
|
||||
icons::X,
|
||||
"Clear Texture",
|
||||
TypeRole::Control,
|
||||
14.0,
|
||||
palette.text_primary,
|
||||
)))
|
||||
.clicked()
|
||||
{
|
||||
response.clear = true;
|
||||
ui.close();
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
fn picker_heading(ui: &mut egui::Ui, title: &str, subtitle: &str) {
|
||||
let palette = design_system::palette(ui);
|
||||
ui.label(TypeRole::Title.text(title).color(palette.text_primary));
|
||||
ui.label(TypeRole::Small.text(subtitle).color(palette.text_muted));
|
||||
ui.separator();
|
||||
}
|
||||
|
||||
fn picker_section_label(ui: &mut egui::Ui, label: &str) {
|
||||
let palette = design_system::palette(ui);
|
||||
ui.add_space(4.0);
|
||||
ui.label(TypeRole::Caption.text(label).color(palette.text_muted));
|
||||
}
|
||||
|
||||
fn material_menu_row(
|
||||
ui: &mut egui::Ui,
|
||||
candidate: &MaterialPickerCandidate,
|
||||
selected: bool,
|
||||
actions: &mut Vec<MaterialSlotAction>,
|
||||
) {
|
||||
let response = picker_asset_row(
|
||||
ui,
|
||||
&candidate.label,
|
||||
&candidate.detail,
|
||||
candidate.thumbnail,
|
||||
selected,
|
||||
);
|
||||
if response.clicked() {
|
||||
remember_recent(ui, "material_picker_recents", &candidate.reference);
|
||||
actions.push(MaterialSlotAction::Assign {
|
||||
reference: candidate.reference.clone(),
|
||||
from_drop: false,
|
||||
});
|
||||
ui.close();
|
||||
}
|
||||
}
|
||||
|
||||
fn texture_candidate_row(
|
||||
ui: &mut egui::Ui,
|
||||
candidate: &MaterialTextureCandidate,
|
||||
selected: bool,
|
||||
response: &mut TextureSlotResponse,
|
||||
) {
|
||||
let row = picker_asset_row(
|
||||
ui,
|
||||
&candidate.label,
|
||||
&candidate.detail,
|
||||
candidate.thumbnail,
|
||||
selected,
|
||||
);
|
||||
if row.clicked() {
|
||||
remember_recent(ui, "texture_picker_recents", &candidate.reference);
|
||||
response.selected = Some(candidate.clone());
|
||||
ui.close();
|
||||
}
|
||||
}
|
||||
|
||||
fn picker_asset_row(
|
||||
ui: &mut egui::Ui,
|
||||
label: &str,
|
||||
detail: &str,
|
||||
thumbnail: MaterialThumbnailPresentation,
|
||||
selected: bool,
|
||||
) -> egui::Response {
|
||||
let palette = design_system::palette(ui);
|
||||
let (rect, response) = ui.allocate_exact_size(
|
||||
egui::vec2(ui.available_width().max(1.0), PICKER_ROW_HEIGHT),
|
||||
egui::Sense::click(),
|
||||
);
|
||||
let fill = if selected {
|
||||
palette.accent_dark
|
||||
} else if response.hovered() {
|
||||
palette.elevated
|
||||
} else {
|
||||
palette.recessed
|
||||
};
|
||||
ui.painter().rect(
|
||||
rect,
|
||||
5.0,
|
||||
fill,
|
||||
egui::Stroke::new(
|
||||
1.0_f32,
|
||||
if selected {
|
||||
palette.accent
|
||||
} else {
|
||||
palette.border
|
||||
},
|
||||
),
|
||||
egui::StrokeKind::Inside,
|
||||
);
|
||||
let thumb = egui::Rect::from_min_size(
|
||||
rect.left_top() + egui::vec2(4.0, 4.0),
|
||||
egui::vec2(PICKER_THUMBNAIL, PICKER_THUMBNAIL),
|
||||
);
|
||||
paint_thumbnail(ui, thumb, thumbnail);
|
||||
let text_rect = egui::Rect::from_min_max(
|
||||
egui::pos2(thumb.right() + 8.0, rect.top() + 5.0),
|
||||
egui::pos2(rect.right() - 8.0, rect.bottom() - 5.0),
|
||||
);
|
||||
let mut child = ui.new_child(
|
||||
egui::UiBuilder::new()
|
||||
.max_rect(text_rect)
|
||||
.layout(egui::Layout::top_down(egui::Align::Min)),
|
||||
);
|
||||
child.set_clip_rect(rect.intersect(ui.clip_rect()));
|
||||
child
|
||||
.add(egui::Label::new(TypeRole::Body.text(label).color(palette.text_primary)).truncate())
|
||||
.on_hover_text(label);
|
||||
child
|
||||
.add(egui::Label::new(TypeRole::Small.text(detail).color(palette.text_muted)).truncate())
|
||||
.on_hover_text(detail);
|
||||
response
|
||||
}
|
||||
|
||||
fn paint_thumbnail(ui: &egui::Ui, rect: egui::Rect, thumbnail: MaterialThumbnailPresentation) {
|
||||
let palette = design_system::palette(ui);
|
||||
ui.painter().rect_filled(rect, 4.0, palette.control);
|
||||
match thumbnail {
|
||||
MaterialThumbnailPresentation::Ready(texture) => {
|
||||
ui.painter().image(
|
||||
texture,
|
||||
rect,
|
||||
egui::Rect::from_min_max(egui::Pos2::ZERO, egui::pos2(1.0, 1.0)),
|
||||
egui::Color32::WHITE,
|
||||
);
|
||||
}
|
||||
MaterialThumbnailPresentation::Pending => {
|
||||
ui.painter().text(
|
||||
rect.center(),
|
||||
egui::Align2::CENTER_CENTER,
|
||||
icons::CIRCLE_NOTCH.as_str(),
|
||||
egui::FontId::new(14.0, egui::FontFamily::Name("phosphor-bold".into())),
|
||||
palette.text_muted,
|
||||
);
|
||||
}
|
||||
MaterialThumbnailPresentation::Failed => {
|
||||
ui.painter().text(
|
||||
rect.center(),
|
||||
egui::Align2::CENTER_CENTER,
|
||||
icons::WARNING.as_str(),
|
||||
egui::FontId::new(14.0, egui::FontFamily::Name("phosphor-bold".into())),
|
||||
palette.error,
|
||||
);
|
||||
}
|
||||
MaterialThumbnailPresentation::Empty => {
|
||||
ui.painter().text(
|
||||
rect.center(),
|
||||
egui::Align2::CENTER_CENTER,
|
||||
icons::PALETTE.as_str(),
|
||||
egui::FontId::new(14.0, egui::FontFamily::Name("phosphor-bold".into())),
|
||||
palette.text_muted,
|
||||
);
|
||||
}
|
||||
}
|
||||
ui.painter().rect_stroke(
|
||||
rect,
|
||||
4.0,
|
||||
egui::Stroke::new(1.0_f32, palette.border),
|
||||
egui::StrokeKind::Inside,
|
||||
);
|
||||
}
|
||||
|
||||
fn picker_footer(ui: &mut egui::Ui, can_clear: bool, actions: &mut Vec<MaterialSlotAction>) {
|
||||
let palette = design_system::palette(ui);
|
||||
ui.separator();
|
||||
if ui
|
||||
.add(egui::Button::new(icon_label(
|
||||
icons::FOLDER_OPEN,
|
||||
"Browse Asset Library",
|
||||
TypeRole::Control,
|
||||
14.0,
|
||||
palette.text_primary,
|
||||
)))
|
||||
.clicked()
|
||||
{
|
||||
actions.push(MaterialSlotAction::BrowseLibrary);
|
||||
ui.close();
|
||||
}
|
||||
if can_clear
|
||||
&& ui
|
||||
.add(egui::Button::new(icon_label(
|
||||
icons::X,
|
||||
"Clear Material",
|
||||
TypeRole::Control,
|
||||
14.0,
|
||||
palette.text_primary,
|
||||
)))
|
||||
.clicked()
|
||||
{
|
||||
actions.push(MaterialSlotAction::Clear);
|
||||
ui.close();
|
||||
}
|
||||
}
|
||||
|
||||
fn unresolved_material_menu_row(ui: &mut egui::Ui, current: &EditorAssetRef) {
|
||||
let palette = design_system::palette(ui);
|
||||
ui.add_sized(
|
||||
[ui.available_width().max(1.0), 28.0],
|
||||
egui::Button::new(TypeRole::Body.text(¤t.label).color(palette.error)).selected(true),
|
||||
)
|
||||
.on_hover_text("The currently assigned material could not be resolved");
|
||||
}
|
||||
|
||||
fn empty_picker_row(ui: &mut egui::Ui, message: &str) {
|
||||
let palette = design_system::palette(ui);
|
||||
ui.add_sized(
|
||||
[ui.available_width().max(1.0), 32.0],
|
||||
egui::Label::new(TypeRole::Body.text(message).color(palette.text_muted)),
|
||||
);
|
||||
}
|
||||
|
||||
fn same_reference(left: &EditorAssetRef, right: &EditorAssetRef) -> bool {
|
||||
left.asset_id == right.asset_id && left.sub_asset_id == right.sub_asset_id
|
||||
}
|
||||
|
||||
fn find_material_candidate<'a>(
|
||||
candidates: &'a [MaterialPickerCandidate],
|
||||
reference: &EditorAssetRef,
|
||||
) -> Option<&'a MaterialPickerCandidate> {
|
||||
candidates
|
||||
.iter()
|
||||
.find(|candidate| same_reference(&candidate.reference, reference))
|
||||
}
|
||||
|
||||
fn recent_keys(ui: &egui::Ui, salt: &'static str) -> Vec<(String, String)> {
|
||||
let id = ui.make_persistent_id(salt);
|
||||
ui.ctx()
|
||||
.data_mut(|data| data.get_persisted::<Vec<(String, String)>>(id))
|
||||
.unwrap_or_default()
|
||||
}
|
||||
|
||||
fn remember_recent(ui: &egui::Ui, salt: &'static str, reference: &EditorAssetRef) {
|
||||
let id = ui.make_persistent_id(salt);
|
||||
let mut keys = recent_keys(ui, salt);
|
||||
let key = (reference.asset_id.clone(), reference.sub_asset_id.clone());
|
||||
keys.retain(|current| current != &key);
|
||||
keys.insert(0, key);
|
||||
keys.truncate(8);
|
||||
ui.ctx().data_mut(|data| data.insert_persisted(id, keys));
|
||||
}
|
||||
|
||||
fn candidates_for_recent_keys<'a>(
|
||||
candidates: &'a [MaterialPickerCandidate],
|
||||
keys: &[(String, String)],
|
||||
) -> Vec<&'a MaterialPickerCandidate> {
|
||||
keys.iter()
|
||||
.filter_map(|(asset_id, sub_asset_id)| {
|
||||
candidates.iter().find(|candidate| {
|
||||
candidate.reference.asset_id == *asset_id
|
||||
&& candidate.reference.sub_asset_id == *sub_asset_id
|
||||
})
|
||||
})
|
||||
.collect()
|
||||
}
|
||||
|
||||
fn candidates_for_recent_texture_keys<'a>(
|
||||
candidates: &'a [MaterialTextureCandidate],
|
||||
keys: &[(String, String)],
|
||||
) -> Vec<&'a MaterialTextureCandidate> {
|
||||
keys.iter()
|
||||
.filter_map(|(asset_id, sub_asset_id)| {
|
||||
candidates.iter().find(|candidate| {
|
||||
candidate.reference.asset_id == *asset_id
|
||||
&& candidate.reference.sub_asset_id == *sub_asset_id
|
||||
})
|
||||
})
|
||||
.collect()
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn penpot_picker_reference_comparison_uses_stable_identity_not_label() {
|
||||
let left = EditorAssetRef::new("asset", "material:source", "Left");
|
||||
let right = EditorAssetRef::new("asset", "material:source", "Renamed");
|
||||
assert!(same_reference(&left, &right));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn penpot_picker_geometry_matches_penpot_assets() {
|
||||
assert_eq!(MATERIAL_PICKER_WIDTH, 244.0);
|
||||
assert_eq!(TEXTURE_PICKER_WIDTH, 420.0);
|
||||
assert_eq!(PICKER_ROW_HEIGHT, 44.0);
|
||||
assert_eq!(PICKER_THUMBNAIL, 36.0);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,120 @@
|
||||
//! Penpot Surface section backed by shared material document values.
|
||||
|
||||
use egui;
|
||||
use material_schema::{MaterialAlphaMode, MaterialInputSet, MaterialRenderState};
|
||||
|
||||
use super::inputs::{
|
||||
apply_arm_texture_preset, apply_separate_texture_preset, packed_map_mode, PackedMapMode,
|
||||
};
|
||||
use super::layout::{ResponsiveMaterialLayout, SurfaceSectionGeometry};
|
||||
use crate::design_system;
|
||||
|
||||
pub fn material_surface_options_ui(
|
||||
ui: &mut egui::Ui,
|
||||
state: &mut MaterialRenderState,
|
||||
packed_inputs: Option<&mut MaterialInputSet>,
|
||||
) {
|
||||
let palette = design_system::palette(ui);
|
||||
let width = ui.available_width().max(1.0);
|
||||
let height = match ResponsiveMaterialLayout::for_width(width) {
|
||||
ResponsiveMaterialLayout::Reference => design_system::SURFACE_SECTION_HEIGHT,
|
||||
ResponsiveMaterialLayout::Compact => design_system::COMPACT_SURFACE_SECTION_HEIGHT,
|
||||
ResponsiveMaterialLayout::Transient => 100.0,
|
||||
};
|
||||
let (rect, _) = ui.allocate_exact_size(egui::vec2(width, height), egui::Sense::hover());
|
||||
ui.painter().rect(
|
||||
rect,
|
||||
5.0,
|
||||
palette.panel,
|
||||
egui::Stroke::new(1.0_f32, palette.border),
|
||||
egui::StrokeKind::Inside,
|
||||
);
|
||||
let geometry = SurfaceSectionGeometry::for_rect(rect);
|
||||
ui.painter().text(
|
||||
geometry.title.left_center(),
|
||||
egui::Align2::LEFT_CENTER,
|
||||
"Surface",
|
||||
design_system::typography::TypeRole::Section.font(),
|
||||
palette.text_primary,
|
||||
);
|
||||
clipped_rect_ui(ui, geometry.blend, |ui| surface_blend_controls(ui, state));
|
||||
if let Some(inputs) = packed_inputs {
|
||||
clipped_rect_ui(ui, geometry.packed, |ui| packed_mode_controls(ui, inputs));
|
||||
}
|
||||
ui.painter().text(
|
||||
geometry.double_sided.left_center() + egui::vec2(7.0, 0.0),
|
||||
egui::Align2::LEFT_CENTER,
|
||||
"Double Sided",
|
||||
design_system::typography::TypeRole::Body.font(),
|
||||
palette.text_secondary,
|
||||
);
|
||||
let switch_rect = egui::Rect::from_min_size(
|
||||
geometry.double_sided.min + egui::vec2(76.0, 3.0),
|
||||
egui::vec2(31.0, 16.0),
|
||||
);
|
||||
clipped_rect_ui(ui, switch_rect, |ui| {
|
||||
design_system::controls::switch(ui, &mut state.double_sided)
|
||||
.on_hover_text("Render both sides of the surface");
|
||||
});
|
||||
// Explicitly placed blend/packing/switch children do not own vertical flow. Reassert the
|
||||
// Surface rectangle after they render so the following authored section gap starts at the
|
||||
// true 46/100 px boundary.
|
||||
ui.advance_cursor_after_rect(rect);
|
||||
}
|
||||
|
||||
fn packed_mode_controls(ui: &mut egui::Ui, inputs: &mut MaterialInputSet) {
|
||||
let arm = packed_map_mode(inputs) == PackedMapMode::Arm;
|
||||
match design_system::controls::two_option_segmented(ui, "Separate", "ORM", arm) {
|
||||
Some(false) => apply_separate_texture_preset(inputs),
|
||||
Some(true) => apply_arm_texture_preset(inputs),
|
||||
None => {}
|
||||
}
|
||||
}
|
||||
|
||||
fn surface_blend_controls(ui: &mut egui::Ui, state: &mut MaterialRenderState) {
|
||||
let width = ui.available_width().max(1.0);
|
||||
let show_cutoff = state.alpha_mode == MaterialAlphaMode::Cutout;
|
||||
let combo_width = if show_cutoff {
|
||||
(width - 58.0).max(1.0)
|
||||
} else {
|
||||
width
|
||||
};
|
||||
let combo_rect = egui::Rect::from_min_size(ui.min_rect().min, egui::vec2(combo_width, 24.0));
|
||||
clipped_rect_ui(ui, combo_rect, |ui| {
|
||||
egui::ComboBox::from_id_salt("material_alpha_mode")
|
||||
.selected_text(match state.alpha_mode {
|
||||
MaterialAlphaMode::Opaque => "Opaque",
|
||||
MaterialAlphaMode::Cutout => "Cutout",
|
||||
})
|
||||
.width(combo_width)
|
||||
.show_ui(ui, |ui| {
|
||||
ui.selectable_value(&mut state.alpha_mode, MaterialAlphaMode::Opaque, "Opaque");
|
||||
ui.selectable_value(&mut state.alpha_mode, MaterialAlphaMode::Cutout, "Cutout");
|
||||
});
|
||||
});
|
||||
if show_cutoff {
|
||||
let cutoff_rect = egui::Rect::from_min_size(
|
||||
ui.min_rect().min + egui::vec2(combo_width + 4.0, 1.0),
|
||||
egui::vec2(54.0_f32.min(width - combo_width - 4.0), 22.0),
|
||||
);
|
||||
ui.put(
|
||||
cutoff_rect,
|
||||
egui::DragValue::new(&mut state.alpha_cutoff)
|
||||
.range(0.0..=1.0)
|
||||
.speed(0.01),
|
||||
)
|
||||
.on_hover_text("Alpha cutoff");
|
||||
}
|
||||
}
|
||||
|
||||
fn clipped_rect_ui<R>(
|
||||
ui: &mut egui::Ui,
|
||||
rect: egui::Rect,
|
||||
add_contents: impl FnOnce(&mut egui::Ui) -> R,
|
||||
) -> R {
|
||||
ui.scope_builder(egui::UiBuilder::new().max_rect(rect), |ui| {
|
||||
ui.set_clip_rect(rect.intersect(ui.clip_rect()));
|
||||
add_contents(ui)
|
||||
})
|
||||
.inner
|
||||
}
|
||||
@@ -0,0 +1,413 @@
|
||||
//! Texture/channel controls shared by Material and Material Instance input tables.
|
||||
|
||||
use super::*;
|
||||
|
||||
use crate::design_system;
|
||||
use crate::design_system::typography::TypeRole;
|
||||
use egui_phosphor_icons::icons;
|
||||
|
||||
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
|
||||
enum TextureFieldAdornment {
|
||||
TypedThumbnail,
|
||||
BrokenReference,
|
||||
Empty,
|
||||
}
|
||||
|
||||
fn texture_field_adornment(
|
||||
presentation: Option<MaterialThumbnailPresentation>,
|
||||
current_present: bool,
|
||||
) -> TextureFieldAdornment {
|
||||
if presentation.is_some() {
|
||||
TextureFieldAdornment::TypedThumbnail
|
||||
} else if current_present {
|
||||
TextureFieldAdornment::BrokenReference
|
||||
} else {
|
||||
TextureFieldAdornment::Empty
|
||||
}
|
||||
}
|
||||
|
||||
pub(super) fn material_property_texture_binding(
|
||||
textures: &[MaterialTextureBinding],
|
||||
property: &MaterialInputDesc,
|
||||
) -> MaterialTextureBinding {
|
||||
textures
|
||||
.iter()
|
||||
.find(|texture| texture.name == property.name)
|
||||
.cloned()
|
||||
.unwrap_or_else(|| MaterialTextureBinding {
|
||||
name: property.name.clone(),
|
||||
texture: None,
|
||||
channel: property
|
||||
.texture
|
||||
.as_ref()
|
||||
.map_or(TextureChannel::Rgba, |desc| desc.default_channel),
|
||||
})
|
||||
}
|
||||
|
||||
pub(super) fn upsert_material_texture_binding(
|
||||
textures: &mut Vec<MaterialTextureBinding>,
|
||||
binding: MaterialTextureBinding,
|
||||
) {
|
||||
if let Some(existing) = textures
|
||||
.iter_mut()
|
||||
.find(|texture| texture.name == binding.name)
|
||||
{
|
||||
*existing = binding;
|
||||
} else {
|
||||
textures.push(binding);
|
||||
}
|
||||
}
|
||||
|
||||
pub(super) fn material_texture_channel_ui(
|
||||
ui: &mut egui::Ui,
|
||||
property: &MaterialInputDesc,
|
||||
binding: &mut MaterialTextureBinding,
|
||||
) {
|
||||
let allow_override = property
|
||||
.texture
|
||||
.as_ref()
|
||||
.is_some_and(|texture| texture.allow_channel_override);
|
||||
if !allow_override {
|
||||
return;
|
||||
}
|
||||
egui::ComboBox::from_id_salt(("texture_channel", &property.name))
|
||||
.selected_text(texture_channel_label(binding.channel))
|
||||
.width(48.0)
|
||||
.show_ui(ui, |ui| {
|
||||
for channel in [
|
||||
TextureChannel::R,
|
||||
TextureChannel::G,
|
||||
TextureChannel::B,
|
||||
TextureChannel::A,
|
||||
] {
|
||||
ui.selectable_value(
|
||||
&mut binding.channel,
|
||||
channel,
|
||||
texture_channel_label(channel),
|
||||
);
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
pub(super) fn texture_channel_label(channel: TextureChannel) -> &'static str {
|
||||
match channel {
|
||||
TextureChannel::R => "R",
|
||||
TextureChannel::G => "G",
|
||||
TextureChannel::B => "B",
|
||||
TextureChannel::A => "A",
|
||||
TextureChannel::Rgb => "RGB",
|
||||
TextureChannel::Rgba => "RGBA",
|
||||
}
|
||||
}
|
||||
|
||||
pub fn ensure_material_texture_binding<'a>(
|
||||
textures: &'a mut Vec<MaterialTextureBinding>,
|
||||
name: &str,
|
||||
) -> &'a mut MaterialTextureBinding {
|
||||
let index = textures
|
||||
.iter()
|
||||
.position(|texture| texture.name == name)
|
||||
.unwrap_or_else(|| {
|
||||
textures.push(MaterialTextureBinding {
|
||||
name: name.to_string(),
|
||||
texture: None,
|
||||
channel: TextureChannel::Rgba,
|
||||
});
|
||||
textures.len() - 1
|
||||
});
|
||||
&mut textures[index]
|
||||
}
|
||||
|
||||
pub(super) fn texture_binding_ui(
|
||||
ui: &mut egui::Ui,
|
||||
binding: &mut MaterialTextureBinding,
|
||||
texture_assets: &[MaterialTextureCandidate],
|
||||
drop_candidate: Option<&MaterialTextureCandidate>,
|
||||
inline_actions: bool,
|
||||
) -> TextureSlotResponse {
|
||||
let response = texture_slot_ui(
|
||||
ui,
|
||||
format!("binding_{}", binding.name),
|
||||
TextureSlotSelection::Reference(binding.texture.as_ref()),
|
||||
"(none)",
|
||||
texture_assets,
|
||||
drop_candidate,
|
||||
inline_actions,
|
||||
);
|
||||
if response.clear {
|
||||
binding.texture = None;
|
||||
} else if let Some(candidate) = response.selected.as_ref() {
|
||||
binding.texture = Some(candidate.reference.clone());
|
||||
}
|
||||
response
|
||||
}
|
||||
|
||||
pub(super) fn texture_slot_ui(
|
||||
ui: &mut egui::Ui,
|
||||
slot_id: impl std::hash::Hash,
|
||||
current: TextureSlotSelection<'_>,
|
||||
empty_label: &str,
|
||||
candidates: &[MaterialTextureCandidate],
|
||||
drop_candidate: Option<&MaterialTextureCandidate>,
|
||||
inline_actions: bool,
|
||||
) -> TextureSlotResponse {
|
||||
let palette = design_system::palette(ui);
|
||||
let mut result = TextureSlotResponse::default();
|
||||
ui.push_id(slot_id, |ui| {
|
||||
let width = ui.available_width().max(1.0);
|
||||
let (outer, _) = ui.allocate_exact_size(egui::vec2(width, 22.0), egui::Sense::hover());
|
||||
let group = outer;
|
||||
let field_width = if inline_actions {
|
||||
(group.width() - 60.0).max(1.0)
|
||||
} else {
|
||||
(group.width() - 30.0).max(1.0)
|
||||
};
|
||||
let field_rect = egui::Rect::from_min_size(group.min, egui::vec2(field_width, 22.0));
|
||||
let locate_rect = egui::Rect::from_min_size(
|
||||
group.min + egui::vec2(field_width + 6.0, 0.0),
|
||||
egui::vec2(24.0, 22.0),
|
||||
);
|
||||
let clear_rect = inline_actions.then(|| {
|
||||
egui::Rect::from_min_size(
|
||||
group.min + egui::vec2(field_width + 36.0, 0.0),
|
||||
egui::vec2(24.0, 22.0),
|
||||
)
|
||||
});
|
||||
let selected_candidate = candidates.iter().find(|candidate| match current {
|
||||
TextureSlotSelection::Reference(reference) => reference.is_some_and(|reference| {
|
||||
reference.asset_id == candidate.reference.asset_id
|
||||
&& reference.sub_asset_id == candidate.reference.sub_asset_id
|
||||
}),
|
||||
});
|
||||
let current_present = match current {
|
||||
TextureSlotSelection::Reference(reference) => reference.is_some(),
|
||||
};
|
||||
let display_label = selected_candidate
|
||||
.map(|candidate| candidate.label.as_str())
|
||||
.or_else(|| match current {
|
||||
TextureSlotSelection::Reference(reference) => {
|
||||
reference.map(|reference| reference.label.as_str())
|
||||
}
|
||||
})
|
||||
.unwrap_or(empty_label);
|
||||
let presentation = selected_candidate.map(|candidate| candidate.thumbnail);
|
||||
let adornment = texture_field_adornment(presentation, current_present);
|
||||
let label_color = if current_present {
|
||||
palette.text_primary
|
||||
} else {
|
||||
palette.text_muted
|
||||
};
|
||||
ui.painter().rect(
|
||||
field_rect,
|
||||
4.0,
|
||||
palette.control,
|
||||
egui::Stroke::new(1.0_f32, palette.border),
|
||||
egui::StrokeKind::Inside,
|
||||
);
|
||||
let field = ui.interact(
|
||||
field_rect,
|
||||
ui.make_persistent_id("texture_field"),
|
||||
egui::Sense::click(),
|
||||
);
|
||||
let image_rect = egui::Rect::from_center_size(
|
||||
egui::pos2(field_rect.left() + 14.0, field_rect.center().y),
|
||||
egui::vec2(16.0, 16.0),
|
||||
);
|
||||
match selected_candidate.map(|candidate| candidate.thumbnail) {
|
||||
Some(MaterialThumbnailPresentation::Ready(texture)) => {
|
||||
ui.painter().image(
|
||||
texture,
|
||||
image_rect,
|
||||
egui::Rect::from_min_max(egui::Pos2::ZERO, egui::pos2(1.0, 1.0)),
|
||||
egui::Color32::WHITE,
|
||||
);
|
||||
}
|
||||
Some(MaterialThumbnailPresentation::Pending) => {
|
||||
paint_field_icon(ui, image_rect, icons::CIRCLE_NOTCH, palette.text_muted);
|
||||
}
|
||||
Some(MaterialThumbnailPresentation::Failed) => {
|
||||
paint_field_icon(ui, image_rect, icons::WARNING, palette.error);
|
||||
}
|
||||
Some(MaterialThumbnailPresentation::Empty) => {
|
||||
paint_field_icon(ui, image_rect, icons::IMAGE, palette.text_muted);
|
||||
}
|
||||
None => paint_field_icon(
|
||||
ui,
|
||||
image_rect,
|
||||
if adornment == TextureFieldAdornment::BrokenReference {
|
||||
icons::WARNING
|
||||
} else {
|
||||
icons::IMAGE
|
||||
},
|
||||
if adornment == TextureFieldAdornment::BrokenReference {
|
||||
palette.error
|
||||
} else {
|
||||
palette.text_muted
|
||||
},
|
||||
),
|
||||
}
|
||||
let text_rect = egui::Rect::from_min_max(
|
||||
egui::pos2(field_rect.left() + 27.0, field_rect.top()),
|
||||
egui::pos2(field_rect.right() - 6.0, field_rect.bottom()),
|
||||
);
|
||||
// `Label::truncate` centers its galley when forced into the full fixed field rectangle.
|
||||
// Paint the truncated galley at the Penpot text origin instead: the typed thumbnail and
|
||||
// the asset name then form one stable left-aligned identity regardless of field width.
|
||||
let galley =
|
||||
egui::WidgetText::from(TypeRole::AssetLabel.text(display_label).color(label_color))
|
||||
.into_galley(
|
||||
ui,
|
||||
Some(egui::TextWrapMode::Truncate),
|
||||
text_rect.width(),
|
||||
egui::FontSelection::Default,
|
||||
);
|
||||
let text_pos = egui::pos2(
|
||||
text_rect.left(),
|
||||
text_rect.center().y - galley.size().y * 0.5,
|
||||
);
|
||||
let text_painter = ui
|
||||
.painter()
|
||||
.with_clip_rect(text_rect.intersect(ui.clip_rect()));
|
||||
text_painter.galley(text_pos, galley, label_color);
|
||||
field.clone().on_hover_text(display_label);
|
||||
let drop_hovered = drop_candidate.is_some() && field.hovered();
|
||||
if drop_hovered {
|
||||
ui.painter().rect_stroke(
|
||||
field_rect,
|
||||
4.0,
|
||||
egui::Stroke::new(2.0_f32, palette.accent),
|
||||
egui::StrokeKind::Inside,
|
||||
);
|
||||
}
|
||||
super::pickers::texture_picker_popup(
|
||||
ui,
|
||||
field.id.with("texture_picker"),
|
||||
&field,
|
||||
candidates,
|
||||
selected_candidate,
|
||||
&mut result,
|
||||
);
|
||||
if let Some(clear_rect) = clear_rect {
|
||||
let locate = ui.put(
|
||||
locate_rect,
|
||||
egui::Button::new(icon_text(icons::CROSSHAIR, 14.0))
|
||||
.min_size(locate_rect.size())
|
||||
.fill(palette.control)
|
||||
.stroke(egui::Stroke::new(1.0_f32, palette.border)),
|
||||
);
|
||||
if selected_candidate.is_some() && locate.clicked() {
|
||||
result.locate = selected_candidate.map(|candidate| candidate.locate.clone());
|
||||
}
|
||||
locate.on_hover_text(if selected_candidate.is_some() {
|
||||
"Locate texture in Content Browser"
|
||||
} else {
|
||||
"No texture to locate"
|
||||
});
|
||||
let clear = ui.put(
|
||||
clear_rect,
|
||||
egui::Button::new(icon_text(icons::X, 14.0))
|
||||
.min_size(clear_rect.size())
|
||||
.fill(palette.control)
|
||||
.stroke(egui::Stroke::new(1.0_f32, palette.border)),
|
||||
);
|
||||
if current_present && clear.clicked() {
|
||||
result.clear = true;
|
||||
}
|
||||
clear.on_hover_text(if current_present {
|
||||
"Clear texture"
|
||||
} else {
|
||||
"No texture to clear"
|
||||
});
|
||||
} else {
|
||||
transient_texture_actions(
|
||||
ui,
|
||||
locate_rect,
|
||||
selected_candidate,
|
||||
current_present,
|
||||
&mut result,
|
||||
);
|
||||
}
|
||||
if drop_hovered && ui.input(|input| input.pointer.any_released()) {
|
||||
if let Some(candidate) = drop_candidate {
|
||||
result.selected = Some(candidate.clone());
|
||||
result.accepted_drop = true;
|
||||
}
|
||||
}
|
||||
});
|
||||
result
|
||||
}
|
||||
|
||||
fn transient_texture_actions(
|
||||
ui: &mut egui::Ui,
|
||||
rect: egui::Rect,
|
||||
selected_candidate: Option<&MaterialTextureCandidate>,
|
||||
current_present: bool,
|
||||
result: &mut TextureSlotResponse,
|
||||
) {
|
||||
ui.scope_builder(egui::UiBuilder::new().max_rect(rect), |ui| {
|
||||
ui.set_clip_rect(rect.intersect(ui.clip_rect()));
|
||||
ui.menu_button(icon_text(icons::DOTS_THREE, 14.0), |ui| {
|
||||
if ui
|
||||
.add_enabled(selected_candidate.is_some(), egui::Button::new("Locate"))
|
||||
.clicked()
|
||||
{
|
||||
result.locate = selected_candidate.map(|candidate| candidate.locate.clone());
|
||||
ui.close();
|
||||
}
|
||||
if ui
|
||||
.add_enabled(current_present, egui::Button::new("Clear"))
|
||||
.clicked()
|
||||
{
|
||||
result.clear = true;
|
||||
ui.close();
|
||||
}
|
||||
})
|
||||
.response
|
||||
.on_hover_text("Texture actions");
|
||||
});
|
||||
}
|
||||
|
||||
fn paint_field_icon(
|
||||
ui: &egui::Ui,
|
||||
rect: egui::Rect,
|
||||
icon: egui_phosphor_icons::Icon,
|
||||
color: egui::Color32,
|
||||
) {
|
||||
ui.painter().text(
|
||||
rect.center(),
|
||||
egui::Align2::CENTER_CENTER,
|
||||
icon.as_str(),
|
||||
egui::FontId::new(12.0, egui::FontFamily::Name("phosphor-bold".into())),
|
||||
color,
|
||||
);
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn ready_texture_uses_its_thumbnail_without_a_redundant_asset_glyph() {
|
||||
assert_eq!(
|
||||
texture_field_adornment(
|
||||
Some(MaterialThumbnailPresentation::Ready(
|
||||
egui::TextureId::Managed(7)
|
||||
)),
|
||||
true,
|
||||
),
|
||||
TextureFieldAdornment::TypedThumbnail
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn unresolved_and_empty_texture_fields_keep_distinct_fallbacks() {
|
||||
assert_eq!(
|
||||
texture_field_adornment(None, true),
|
||||
TextureFieldAdornment::BrokenReference
|
||||
);
|
||||
assert_eq!(
|
||||
texture_field_adornment(None, false),
|
||||
TextureFieldAdornment::Empty
|
||||
);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,131 @@
|
||||
//! Shared material UV-transform authoring used by Materials and Material Instances.
|
||||
|
||||
use bevy_math::Vec2;
|
||||
use egui;
|
||||
use egui_phosphor_icons::icons;
|
||||
use material_schema::{MaterialInputSet, MaterialParameter, MaterialParameterValue};
|
||||
|
||||
use crate::design_system;
|
||||
use crate::design_system::typography::TypeRole;
|
||||
|
||||
pub(super) fn uv_transform_section(
|
||||
ui: &mut egui::Ui,
|
||||
offset: &mut Vec2,
|
||||
tiling: &mut Vec2,
|
||||
reset_offset: Vec2,
|
||||
reset_tiling: Vec2,
|
||||
) {
|
||||
let palette = design_system::palette(ui);
|
||||
let width = ui.available_width().max(1.0);
|
||||
let height = match super::layout::ResponsiveMaterialLayout::for_width(width) {
|
||||
super::layout::ResponsiveMaterialLayout::Reference => {
|
||||
crate::design_system::UV_SECTION_HEIGHT
|
||||
}
|
||||
super::layout::ResponsiveMaterialLayout::Compact => {
|
||||
crate::design_system::COMPACT_UV_SECTION_HEIGHT
|
||||
}
|
||||
super::layout::ResponsiveMaterialLayout::Transient => 100.0,
|
||||
};
|
||||
let (rect, _) = ui.allocate_exact_size(egui::vec2(width, height), egui::Sense::hover());
|
||||
ui.painter().rect(
|
||||
rect,
|
||||
5.0,
|
||||
palette.panel,
|
||||
egui::Stroke::new(1.0_f32, palette.border),
|
||||
egui::StrokeKind::Inside,
|
||||
);
|
||||
let mut child = ui.new_child(egui::UiBuilder::new().max_rect(rect));
|
||||
child.set_clip_rect(rect.intersect(ui.clip_rect()));
|
||||
let geometry = super::layout::UvSectionGeometry::for_rect(rect);
|
||||
child.painter().text(
|
||||
geometry.title.left_center(),
|
||||
egui::Align2::LEFT_CENTER,
|
||||
"UV",
|
||||
TypeRole::Section.font(),
|
||||
palette.text_primary,
|
||||
);
|
||||
vec2_group(
|
||||
&mut child,
|
||||
geometry.offset,
|
||||
"Offset",
|
||||
offset,
|
||||
reset_offset,
|
||||
"Reset UV offset",
|
||||
);
|
||||
vec2_group(
|
||||
&mut child,
|
||||
geometry.tiling,
|
||||
"Tiling",
|
||||
tiling,
|
||||
reset_tiling,
|
||||
"Reset UV tiling",
|
||||
);
|
||||
}
|
||||
|
||||
fn vec2_group(
|
||||
ui: &mut egui::Ui,
|
||||
geometry: super::layout::UvGroupGeometry,
|
||||
label: &str,
|
||||
value: &mut Vec2,
|
||||
reset: Vec2,
|
||||
tooltip: &str,
|
||||
) {
|
||||
let palette = design_system::palette(ui);
|
||||
ui.painter().text(
|
||||
geometry.label.left_center(),
|
||||
egui::Align2::LEFT_CENTER,
|
||||
label,
|
||||
TypeRole::Small.font(),
|
||||
palette.text_muted,
|
||||
);
|
||||
ui.put(
|
||||
geometry.x,
|
||||
egui::DragValue::new(&mut value.x).speed(0.01).prefix("X "),
|
||||
);
|
||||
ui.put(
|
||||
geometry.y,
|
||||
egui::DragValue::new(&mut value.y).speed(0.01).prefix("Y "),
|
||||
);
|
||||
if let Some(reset_rect) = geometry.reset {
|
||||
let enabled = *value != reset;
|
||||
let response = ui.put(
|
||||
reset_rect,
|
||||
egui::Button::new(
|
||||
egui::RichText::new(icons::ARROW_COUNTER_CLOCKWISE.as_str()).font(
|
||||
egui::FontId::new(14.0, egui::FontFamily::Name("phosphor-bold".into())),
|
||||
),
|
||||
),
|
||||
);
|
||||
if enabled && response.clicked() {
|
||||
*value = reset;
|
||||
}
|
||||
response.on_hover_text(tooltip);
|
||||
}
|
||||
}
|
||||
|
||||
pub(super) fn material_vec2_value(inputs: &MaterialInputSet, name: &str, default: Vec2) -> Vec2 {
|
||||
inputs
|
||||
.values
|
||||
.iter()
|
||||
.find(|parameter| parameter.name == name)
|
||||
.and_then(|parameter| match parameter.value {
|
||||
MaterialParameterValue::Vec2(value) => Some(value),
|
||||
_ => None,
|
||||
})
|
||||
.unwrap_or(default)
|
||||
}
|
||||
|
||||
pub(super) fn set_material_vec2_value(inputs: &mut MaterialInputSet, name: &str, value: Vec2) {
|
||||
if let Some(parameter) = inputs
|
||||
.values
|
||||
.iter_mut()
|
||||
.find(|parameter| parameter.name == name)
|
||||
{
|
||||
parameter.value = MaterialParameterValue::Vec2(value);
|
||||
} else {
|
||||
inputs.values.push(MaterialParameter {
|
||||
name: name.into(),
|
||||
value: MaterialParameterValue::Vec2(value),
|
||||
});
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,412 @@
|
||||
//! Static/skinned renderer-array presentation shared by production and the UI gallery.
|
||||
|
||||
use egui;
|
||||
use egui_phosphor_icons::icons;
|
||||
|
||||
use crate::design_system;
|
||||
use crate::design_system::typography::TypeRole;
|
||||
use crate::theme::{BORDER, PANEL_BG_DARK, WIDGET_BG};
|
||||
|
||||
pub const RENDERER_ARRAY_HEADER_HEIGHT: f32 = 40.0;
|
||||
pub const EXPANDED_RENDERER_HEADER_HEIGHT: f32 = 84.0;
|
||||
pub const COLLAPSED_RENDERER_HEADER_HEIGHT: f32 = 60.0;
|
||||
pub const RENDERER_PROPERTIES_HEADER_HEIGHT: f32 = 38.0;
|
||||
pub const MATERIAL_SLOTS_HEADER_HEIGHT: f32 = 50.0;
|
||||
|
||||
#[derive(Clone, Copy)]
|
||||
pub struct RendererPanelHeaderViewModel<'a> {
|
||||
pub index: usize,
|
||||
pub label: &'a str,
|
||||
pub path: &'a str,
|
||||
pub slot_count: usize,
|
||||
pub texture_id: Option<egui::TextureId>,
|
||||
}
|
||||
|
||||
pub fn renderer_array_header(ui: &mut egui::Ui, count: usize) -> bool {
|
||||
let palette = design_system::palette(ui);
|
||||
let (rect, _) = ui.allocate_exact_size(
|
||||
egui::vec2(ui.available_width().max(1.0), RENDERER_ARRAY_HEADER_HEIGHT),
|
||||
egui::Sense::hover(),
|
||||
);
|
||||
ui.painter().rect_filled(rect, 4.0, palette.elevated);
|
||||
ui.painter().text(
|
||||
rect.left_center() + egui::vec2(12.0, 0.0),
|
||||
egui::Align2::LEFT_CENTER,
|
||||
icons::SQUARES_FOUR.as_str(),
|
||||
egui::FontId::new(16.0, egui::FontFamily::Name("phosphor-regular".into())),
|
||||
palette.text_secondary,
|
||||
);
|
||||
ui.painter().text(
|
||||
rect.left_center() + egui::vec2(32.0, 0.0),
|
||||
egui::Align2::LEFT_CENTER,
|
||||
"Mesh renderers",
|
||||
TypeRole::Section.font(),
|
||||
palette.text_primary,
|
||||
);
|
||||
let badge = egui::Rect::from_center_size(
|
||||
rect.left_center() + egui::vec2(124.0, 0.0),
|
||||
egui::vec2(20.0, 20.0),
|
||||
);
|
||||
ui.painter()
|
||||
.circle_filled(badge.center(), 10.0, palette.accent.linear_multiply(0.22));
|
||||
ui.painter().text(
|
||||
badge.center(),
|
||||
egui::Align2::CENTER_CENTER,
|
||||
format!("{count}"),
|
||||
TypeRole::Small.font(),
|
||||
palette.accent,
|
||||
);
|
||||
ui.painter().text(
|
||||
rect.left_center() + egui::vec2(144.0, 0.0),
|
||||
egui::Align2::LEFT_CENTER,
|
||||
"Each renderer owns the slots exposed by its mesh",
|
||||
TypeRole::Caption.font(),
|
||||
palette.text_muted,
|
||||
);
|
||||
let add_rect = egui::Rect::from_min_size(
|
||||
egui::pos2(rect.right() - 116.0, rect.top() + 7.0),
|
||||
egui::vec2(104.0, 26.0),
|
||||
);
|
||||
ui.put(
|
||||
add_rect,
|
||||
egui::Button::new(design_system::controls::icon_label(
|
||||
icons::PLUS,
|
||||
"Add renderer",
|
||||
TypeRole::Body,
|
||||
12.0,
|
||||
palette.text_primary,
|
||||
)),
|
||||
)
|
||||
.clicked()
|
||||
}
|
||||
|
||||
pub fn renderer_panel(ui: &mut egui::Ui, add_contents: impl FnOnce(&mut egui::Ui)) {
|
||||
egui::Frame::new()
|
||||
.fill(WIDGET_BG.linear_multiply(0.82))
|
||||
.stroke(egui::Stroke::new(1.0_f32, BORDER))
|
||||
.corner_radius(egui::CornerRadius::same(5))
|
||||
.show(ui, |ui| {
|
||||
ui.set_max_width(ui.available_width());
|
||||
add_contents(ui);
|
||||
});
|
||||
ui.add_space(10.0);
|
||||
}
|
||||
|
||||
pub fn renderer_panel_header(
|
||||
ui: &mut egui::Ui,
|
||||
model: RendererPanelHeaderViewModel<'_>,
|
||||
open: &mut bool,
|
||||
add_actions: impl FnOnce(&mut egui::Ui),
|
||||
) {
|
||||
let palette = design_system::palette(ui);
|
||||
let height = if *open {
|
||||
EXPANDED_RENDERER_HEADER_HEIGHT
|
||||
} else {
|
||||
COLLAPSED_RENDERER_HEADER_HEIGHT
|
||||
};
|
||||
let (rect, header_response) = ui.allocate_exact_size(
|
||||
egui::vec2(ui.available_width().max(1.0), height),
|
||||
egui::Sense::click(),
|
||||
);
|
||||
ui.painter().rect_filled(
|
||||
egui::Rect::from_min_size(
|
||||
rect.min + egui::vec2(6.0, 8.0),
|
||||
egui::vec2(3.0, height - 16.0),
|
||||
),
|
||||
2.0,
|
||||
palette.accent,
|
||||
);
|
||||
ui.painter().text(
|
||||
rect.left_center() + egui::vec2(24.0, 0.0),
|
||||
egui::Align2::CENTER_CENTER,
|
||||
if *open {
|
||||
icons::CARET_DOWN.as_str()
|
||||
} else {
|
||||
icons::CARET_RIGHT.as_str()
|
||||
},
|
||||
egui::FontId::new(12.0, egui::FontFamily::Name("phosphor-regular".into())),
|
||||
palette.text_secondary,
|
||||
);
|
||||
let preview_size = if *open { 58.0 } else { 40.0 };
|
||||
let preview = egui::Rect::from_center_size(
|
||||
egui::pos2(rect.left() + 68.0, rect.center().y),
|
||||
egui::vec2(preview_size, preview_size),
|
||||
);
|
||||
ui.painter().rect(
|
||||
preview,
|
||||
4.0,
|
||||
PANEL_BG_DARK,
|
||||
egui::Stroke::new(1.0_f32, BORDER),
|
||||
egui::StrokeKind::Inside,
|
||||
);
|
||||
if let Some(texture_id) = model.texture_id {
|
||||
ui.painter().image(
|
||||
texture_id,
|
||||
preview.shrink(3.0),
|
||||
egui::Rect::from_min_max(egui::Pos2::ZERO, egui::pos2(1.0, 1.0)),
|
||||
egui::Color32::WHITE,
|
||||
);
|
||||
} else {
|
||||
ui.painter().text(
|
||||
preview.center(),
|
||||
egui::Align2::CENTER_CENTER,
|
||||
icons::CUBE.as_str(),
|
||||
egui::FontId::new(20.0, egui::FontFamily::Name("phosphor-bold".into())),
|
||||
palette.text_secondary,
|
||||
);
|
||||
}
|
||||
let label = if model.label.trim().is_empty() {
|
||||
"Mesh renderer"
|
||||
} else {
|
||||
model.label.trim()
|
||||
};
|
||||
let identity_x = rect.left() + 105.0;
|
||||
if *open {
|
||||
ui.painter().text(
|
||||
egui::pos2(identity_x, rect.top() + 28.0),
|
||||
egui::Align2::LEFT_CENTER,
|
||||
format!("RENDERER {}", model.index),
|
||||
TypeRole::Eyebrow.font(),
|
||||
palette.accent,
|
||||
);
|
||||
}
|
||||
ui.painter().text(
|
||||
egui::pos2(
|
||||
identity_x,
|
||||
if *open {
|
||||
rect.top() + 45.0
|
||||
} else {
|
||||
rect.center().y - 7.0
|
||||
},
|
||||
),
|
||||
egui::Align2::LEFT_CENTER,
|
||||
label,
|
||||
TypeRole::AssetTitle.font(),
|
||||
palette.text_primary,
|
||||
);
|
||||
ui.painter().text(
|
||||
egui::pos2(
|
||||
identity_x,
|
||||
if *open {
|
||||
rect.top() + 62.0
|
||||
} else {
|
||||
rect.center().y + 9.0
|
||||
},
|
||||
),
|
||||
egui::Align2::LEFT_CENTER,
|
||||
if *open {
|
||||
model.path.to_owned()
|
||||
} else {
|
||||
format!(
|
||||
"Renderer {} · {} material slot{}",
|
||||
model.index,
|
||||
model.slot_count,
|
||||
if model.slot_count == 1 { "" } else { "s" }
|
||||
)
|
||||
},
|
||||
TypeRole::Small.font(),
|
||||
palette.text_muted,
|
||||
);
|
||||
let slot_badge = egui::Rect::from_min_size(
|
||||
egui::pos2(
|
||||
rect.right() - if *open { 60.0 } else { 78.0 },
|
||||
rect.top() + if *open { 12.0 } else { 8.0 },
|
||||
),
|
||||
egui::vec2(40.0, 20.0),
|
||||
);
|
||||
ui.painter()
|
||||
.rect_filled(slot_badge, 10.0, palette.accent.linear_multiply(0.22));
|
||||
ui.painter().text(
|
||||
slot_badge.center(),
|
||||
egui::Align2::CENTER_CENTER,
|
||||
format!(
|
||||
"{} slot{}",
|
||||
model.slot_count,
|
||||
if model.slot_count == 1 { "" } else { "s" }
|
||||
),
|
||||
TypeRole::Eyebrow.font(),
|
||||
palette.accent,
|
||||
);
|
||||
let action_rect = if *open {
|
||||
ui.painter().circle_filled(
|
||||
egui::pos2(rect.right() - 10.0, rect.top() + 22.0),
|
||||
4.0,
|
||||
palette.healthy,
|
||||
);
|
||||
let action_rect = egui::Rect::from_min_size(
|
||||
egui::pos2(rect.right() - 132.0, rect.bottom() - 38.0),
|
||||
egui::vec2(122.0, 28.0),
|
||||
);
|
||||
ui.scope_builder(egui::UiBuilder::new().max_rect(action_rect), |ui| {
|
||||
ui.with_layout(
|
||||
egui::Layout::right_to_left(egui::Align::Center),
|
||||
add_actions,
|
||||
);
|
||||
});
|
||||
action_rect
|
||||
} else {
|
||||
let action_rect = egui::Rect::from_center_size(
|
||||
egui::pos2(rect.right() - 20.0, rect.center().y),
|
||||
egui::vec2(28.0, 28.0),
|
||||
);
|
||||
ui.scope_builder(egui::UiBuilder::new().max_rect(action_rect), |ui| {
|
||||
design_system::controls::icon_button(
|
||||
ui,
|
||||
icons::DOTS_THREE_VERTICAL,
|
||||
"Renderer actions",
|
||||
true,
|
||||
);
|
||||
});
|
||||
action_rect
|
||||
};
|
||||
if header_response.clicked()
|
||||
&& ui
|
||||
.input(|input| input.pointer.interact_pos())
|
||||
.is_some_and(|pointer| !preview.contains(pointer) && !action_rect.contains(pointer))
|
||||
{
|
||||
*open = !*open;
|
||||
}
|
||||
}
|
||||
|
||||
pub fn renderer_material_slots_header(ui: &mut egui::Ui, count: usize) {
|
||||
let palette = design_system::palette(ui);
|
||||
let (rect, _) = ui.allocate_exact_size(
|
||||
egui::vec2(ui.available_width().max(1.0), MATERIAL_SLOTS_HEADER_HEIGHT),
|
||||
egui::Sense::hover(),
|
||||
);
|
||||
ui.painter().rect_filled(rect, 0.0, palette.elevated);
|
||||
ui.painter().text(
|
||||
rect.left_center() + egui::vec2(15.0, 0.0),
|
||||
egui::Align2::CENTER_CENTER,
|
||||
icons::CARET_DOWN.as_str(),
|
||||
egui::FontId::new(10.0, egui::FontFamily::Name("phosphor-bold".into())),
|
||||
palette.text_secondary,
|
||||
);
|
||||
ui.painter().text(
|
||||
rect.left_center() + egui::vec2(35.0, 0.0),
|
||||
egui::Align2::CENTER_CENTER,
|
||||
icons::PALETTE.as_str(),
|
||||
egui::FontId::new(14.0, egui::FontFamily::Name("phosphor-bold".into())),
|
||||
palette.accent,
|
||||
);
|
||||
ui.painter().text(
|
||||
rect.left_center() + egui::vec2(49.0, 0.0),
|
||||
egui::Align2::LEFT_CENTER,
|
||||
"Material slots",
|
||||
TypeRole::Section.font(),
|
||||
palette.text_primary,
|
||||
);
|
||||
ui.painter().text(
|
||||
rect.left_center() + egui::vec2(122.0, 0.0),
|
||||
egui::Align2::LEFT_CENTER,
|
||||
format!("{count} exposed by mesh"),
|
||||
TypeRole::Caption.font(),
|
||||
palette.text_muted,
|
||||
);
|
||||
ui.painter().line_segment(
|
||||
[
|
||||
egui::pos2(rect.left() + 201.0, rect.center().y),
|
||||
egui::pos2(rect.right() - 93.0, rect.center().y),
|
||||
],
|
||||
egui::Stroke::new(1.0_f32, palette.border),
|
||||
);
|
||||
ui.painter().text(
|
||||
rect.right_center() - egui::vec2(76.0, 0.0),
|
||||
egui::Align2::CENTER_CENTER,
|
||||
icons::LINK.as_str(),
|
||||
egui::FontId::new(12.0, egui::FontFamily::Name("phosphor-bold".into())),
|
||||
palette.text_muted,
|
||||
);
|
||||
ui.painter().text(
|
||||
rect.right_center() - egui::vec2(10.0, 0.0),
|
||||
egui::Align2::RIGHT_CENTER,
|
||||
"Index mapped",
|
||||
TypeRole::Eyebrow.font(),
|
||||
palette.text_muted,
|
||||
);
|
||||
}
|
||||
|
||||
pub fn renderer_properties_header(ui: &mut egui::Ui) {
|
||||
let palette = design_system::palette(ui);
|
||||
let (rect, _) = ui.allocate_exact_size(
|
||||
egui::vec2(
|
||||
ui.available_width().max(1.0),
|
||||
RENDERER_PROPERTIES_HEADER_HEIGHT,
|
||||
),
|
||||
egui::Sense::hover(),
|
||||
);
|
||||
ui.painter().text(
|
||||
rect.left_center() + egui::vec2(4.0, 0.0),
|
||||
egui::Align2::CENTER_CENTER,
|
||||
icons::SLIDERS_HORIZONTAL.as_str(),
|
||||
egui::FontId::new(13.0, egui::FontFamily::Name("phosphor-bold".into())),
|
||||
palette.accent,
|
||||
);
|
||||
ui.painter().text(
|
||||
rect.left_center() + egui::vec2(20.0, 0.0),
|
||||
egui::Align2::LEFT_CENTER,
|
||||
"Renderer properties",
|
||||
TypeRole::AssetLabel.font(),
|
||||
palette.accent,
|
||||
);
|
||||
ui.painter().text(
|
||||
rect.right_center(),
|
||||
egui::Align2::RIGHT_CENTER,
|
||||
"Mesh + render flags",
|
||||
TypeRole::Caption.font(),
|
||||
palette.text_muted,
|
||||
);
|
||||
}
|
||||
|
||||
pub fn renderer_material_slot_row<R>(
|
||||
ui: &mut egui::Ui,
|
||||
index: usize,
|
||||
add_contents: impl FnOnce(&mut egui::Ui) -> R,
|
||||
) -> R {
|
||||
let palette = design_system::palette(ui);
|
||||
let row = ui.horizontal_top(|ui| {
|
||||
let (index_rect, _) = ui.allocate_exact_size(egui::vec2(39.0, 60.0), egui::Sense::hover());
|
||||
ui.painter().text(
|
||||
index_rect.center_top() + egui::vec2(0.0, 8.0),
|
||||
egui::Align2::CENTER_CENTER,
|
||||
"SLOT",
|
||||
TypeRole::Caption.font(),
|
||||
palette.text_muted,
|
||||
);
|
||||
ui.painter().text(
|
||||
index_rect.center_top() + egui::vec2(0.0, 18.0),
|
||||
egui::Align2::CENTER_CENTER,
|
||||
index.to_string(),
|
||||
TypeRole::Body.font(),
|
||||
palette.text_muted,
|
||||
);
|
||||
ui.vertical(|ui| {
|
||||
ui.set_width(ui.available_width().max(1.0));
|
||||
add_contents(ui)
|
||||
})
|
||||
.inner
|
||||
});
|
||||
let rail_x = row.response.rect.left() + 23.0;
|
||||
ui.painter().line_segment(
|
||||
[
|
||||
egui::pos2(rail_x, row.response.rect.top() + 35.0),
|
||||
egui::pos2(rail_x, row.response.rect.bottom() - 8.0),
|
||||
],
|
||||
egui::Stroke::new(1.0_f32, palette.border_strong),
|
||||
);
|
||||
row.inner
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn renderer_headers_match_current_penpot_heights() {
|
||||
assert_eq!(RENDERER_ARRAY_HEADER_HEIGHT, 40.0);
|
||||
assert_eq!(EXPANDED_RENDERER_HEADER_HEIGHT, 84.0);
|
||||
assert_eq!(COLLAPSED_RENDERER_HEADER_HEIGHT, 60.0);
|
||||
assert_eq!(RENDERER_PROPERTIES_HEADER_HEIGHT, 38.0);
|
||||
assert_eq!(MATERIAL_SLOTS_HEADER_HEIGHT, 50.0);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,156 @@
|
||||
//! Semantic Blacksite editor palette shared by production and the UI gallery.
|
||||
|
||||
use egui::{self, Color32, CornerRadius, FontId, Id, Stroke, Visuals};
|
||||
|
||||
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
|
||||
pub struct EditorVisualPalette {
|
||||
pub canvas: Color32,
|
||||
pub panel: Color32,
|
||||
pub panel_dark: Color32,
|
||||
pub widget: Color32,
|
||||
pub elevated: Color32,
|
||||
pub accent: Color32,
|
||||
pub accent_hover: Color32,
|
||||
pub selection: Color32,
|
||||
pub selection_secondary: Color32,
|
||||
pub selection_bg: Color32,
|
||||
pub selection_bg_muted: Color32,
|
||||
pub text: Color32,
|
||||
pub text_selected: Color32,
|
||||
pub text_dim: Color32,
|
||||
pub text_muted: Color32,
|
||||
pub border: Color32,
|
||||
pub border_strong: Color32,
|
||||
pub success: Color32,
|
||||
pub warning: Color32,
|
||||
pub error: Color32,
|
||||
}
|
||||
|
||||
pub const CANVAS_BG: Color32 = Color32::from_rgb(7, 8, 10);
|
||||
pub const PANEL_BG: Color32 = Color32::from_rgb(13, 15, 18);
|
||||
pub const PANEL_BG_DARK: Color32 = Color32::from_rgb(9, 11, 13);
|
||||
pub const WIDGET_BG: Color32 = Color32::from_rgb(21, 24, 28);
|
||||
pub const ELEVATED_BG: Color32 = Color32::from_rgb(31, 35, 40);
|
||||
pub const ACCENT: Color32 = Color32::from_rgb(229, 164, 51);
|
||||
pub const ACCENT_HOVER: Color32 = Color32::from_rgb(249, 193, 79);
|
||||
pub const SELECTION: Color32 = Color32::from_rgb(65, 198, 207);
|
||||
pub const SELECTION_SECONDARY: Color32 = Color32::from_rgb(84, 139, 155);
|
||||
pub const SELECTION_BG: Color32 = Color32::from_rgb(22, 72, 78);
|
||||
pub const SELECTION_BG_MUTED: Color32 = Color32::from_rgb(23, 48, 54);
|
||||
pub const TEXT: Color32 = Color32::from_rgb(220, 225, 229);
|
||||
pub const TEXT_SELECTED: Color32 = Color32::from_rgb(250, 251, 252);
|
||||
pub const TEXT_DIM: Color32 = Color32::from_rgb(155, 163, 171);
|
||||
pub const TEXT_MUTED: Color32 = Color32::from_rgb(96, 105, 114);
|
||||
pub const BORDER: Color32 = Color32::from_rgb(38, 43, 49);
|
||||
pub const BORDER_STRONG: Color32 = Color32::from_rgb(64, 71, 79);
|
||||
pub const SUCCESS: Color32 = Color32::from_rgb(84, 190, 127);
|
||||
pub const WARNING: Color32 = Color32::from_rgb(235, 180, 72);
|
||||
pub const ERROR: Color32 = Color32::from_rgb(226, 94, 94);
|
||||
|
||||
pub const BLACKSITE_PALETTE: EditorVisualPalette = EditorVisualPalette {
|
||||
canvas: CANVAS_BG,
|
||||
panel: PANEL_BG,
|
||||
panel_dark: PANEL_BG_DARK,
|
||||
widget: WIDGET_BG,
|
||||
elevated: ELEVATED_BG,
|
||||
accent: ACCENT,
|
||||
accent_hover: ACCENT_HOVER,
|
||||
selection: SELECTION,
|
||||
selection_secondary: SELECTION_SECONDARY,
|
||||
selection_bg: SELECTION_BG,
|
||||
selection_bg_muted: SELECTION_BG_MUTED,
|
||||
text: TEXT,
|
||||
text_selected: TEXT_SELECTED,
|
||||
text_dim: TEXT_DIM,
|
||||
text_muted: TEXT_MUTED,
|
||||
border: BORDER,
|
||||
border_strong: BORDER_STRONG,
|
||||
success: SUCCESS,
|
||||
warning: WARNING,
|
||||
error: ERROR,
|
||||
};
|
||||
|
||||
const EDITOR_PALETTE_ID: &str = "blacksite.editor.visual_palette";
|
||||
|
||||
pub fn editor_palette(ctx: &egui::Context) -> EditorVisualPalette {
|
||||
ctx.data_mut(|data| {
|
||||
data.get_temp::<EditorVisualPalette>(Id::new(EDITOR_PALETTE_ID))
|
||||
.unwrap_or(BLACKSITE_PALETTE)
|
||||
})
|
||||
}
|
||||
|
||||
pub fn apply_editor_theme(ctx: &egui::Context) {
|
||||
apply_editor_theme_with_palette(ctx, editor_palette(ctx));
|
||||
}
|
||||
|
||||
pub fn apply_editor_theme_with_palette(ctx: &egui::Context, palette: EditorVisualPalette) {
|
||||
ctx.data_mut(|data| data.insert_temp(Id::new(EDITOR_PALETTE_ID), palette));
|
||||
let mut visuals = Visuals::dark();
|
||||
visuals.panel_fill = palette.panel;
|
||||
visuals.window_fill = palette.widget;
|
||||
visuals.extreme_bg_color = palette.canvas;
|
||||
visuals.faint_bg_color = palette.panel_dark;
|
||||
visuals.code_bg_color = palette.panel_dark;
|
||||
visuals.text_edit_bg_color = Some(palette.canvas);
|
||||
visuals.weak_text_color = Some(palette.text_muted);
|
||||
visuals.widgets.noninteractive.bg_fill = palette.panel;
|
||||
visuals.widgets.noninteractive.bg_stroke = Stroke::new(1.0_f32, palette.border);
|
||||
visuals.widgets.noninteractive.fg_stroke = Stroke::new(1.0_f32, palette.text_dim);
|
||||
visuals.widgets.inactive.bg_fill = palette.widget;
|
||||
visuals.widgets.inactive.weak_bg_fill = palette.widget;
|
||||
visuals.widgets.inactive.bg_stroke = Stroke::new(1.0_f32, palette.border);
|
||||
visuals.widgets.inactive.fg_stroke = Stroke::new(1.0_f32, palette.text);
|
||||
visuals.widgets.hovered.bg_fill = palette.elevated;
|
||||
visuals.widgets.hovered.weak_bg_fill = palette.elevated;
|
||||
visuals.widgets.hovered.bg_stroke = Stroke::new(1.0_f32, palette.border_strong);
|
||||
visuals.widgets.hovered.fg_stroke = Stroke::new(1.0_f32, palette.text_selected);
|
||||
visuals.widgets.active.bg_fill = palette.elevated;
|
||||
visuals.widgets.active.weak_bg_fill = palette.elevated;
|
||||
visuals.widgets.active.bg_stroke = Stroke::new(1.0_f32, palette.accent);
|
||||
visuals.widgets.active.fg_stroke = Stroke::new(1.0_f32, palette.text_selected);
|
||||
visuals.widgets.open = visuals.widgets.hovered;
|
||||
visuals.selection.bg_fill = palette.selection_bg;
|
||||
visuals.selection.stroke = Stroke::new(1.0_f32, palette.selection);
|
||||
visuals.hyperlink_color = palette.selection;
|
||||
visuals.warn_fg_color = palette.warning;
|
||||
visuals.error_fg_color = palette.error;
|
||||
visuals.window_stroke = Stroke::new(1.0_f32, palette.border);
|
||||
visuals.window_corner_radius = CornerRadius::same(4);
|
||||
visuals.menu_corner_radius = CornerRadius::same(3);
|
||||
visuals.button_frame = true;
|
||||
visuals.collapsing_header_frame = false;
|
||||
visuals.indent_has_left_vline = true;
|
||||
visuals.striped = true;
|
||||
visuals.slider_trailing_fill = true;
|
||||
visuals.interact_cursor = Some(egui::CursorIcon::PointingHand);
|
||||
|
||||
let mut style = (*ctx.global_style()).clone();
|
||||
style.visuals = visuals;
|
||||
style.spacing.item_spacing = egui::vec2(8.0, 7.0);
|
||||
style.spacing.button_padding = egui::vec2(10.0, 5.0);
|
||||
style.spacing.interact_size = egui::vec2(40.0, 28.0);
|
||||
style.spacing.window_margin = egui::Margin::same(10);
|
||||
style.spacing.menu_margin = egui::Margin::same(8);
|
||||
style.spacing.indent = 17.0;
|
||||
style.interaction.tooltip_delay = 0.32;
|
||||
style.interaction.tooltip_grace_time = 0.18;
|
||||
style.animation_time = 0.12;
|
||||
style.compact_menu_style = true;
|
||||
style.text_styles.insert(
|
||||
egui::TextStyle::Body,
|
||||
FontId::new(14.0, egui::FontFamily::Proportional),
|
||||
);
|
||||
style.text_styles.insert(
|
||||
egui::TextStyle::Button,
|
||||
FontId::new(13.0, egui::FontFamily::Proportional),
|
||||
);
|
||||
style.text_styles.insert(
|
||||
egui::TextStyle::Heading,
|
||||
FontId::new(16.0, egui::FontFamily::Proportional),
|
||||
);
|
||||
style.text_styles.insert(
|
||||
egui::TextStyle::Small,
|
||||
FontId::new(12.0, egui::FontFamily::Proportional),
|
||||
);
|
||||
ctx.set_global_style(style);
|
||||
}
|
||||
@@ -0,0 +1,12 @@
|
||||
[package]
|
||||
name = "material_schema"
|
||||
version.workspace = true
|
||||
edition.workspace = true
|
||||
license.workspace = true
|
||||
description = "Lightweight authored material schema and value types shared by Blacksite tools"
|
||||
|
||||
[dependencies]
|
||||
bevy_color = { version = "0.19", features = ["serialize"] }
|
||||
bevy_math = { version = "0.19", features = ["bevy_reflect", "serialize"] }
|
||||
bevy_reflect = { version = "0.19", features = ["glam"] }
|
||||
serde.workspace = true
|
||||
@@ -0,0 +1,546 @@
|
||||
//! Lightweight authored material values and schemas.
|
||||
//!
|
||||
//! This crate intentionally excludes Bevy's app, asset, rendering, scene, and physics layers so
|
||||
//! headless tooling and the production UI gallery can share the exact authoring contracts without
|
||||
//! compiling the game runtime.
|
||||
|
||||
use bevy_color::Color;
|
||||
use bevy_math::{Vec2, Vec3};
|
||||
use bevy_reflect::prelude::*;
|
||||
use serde::{Deserialize, Serialize};
|
||||
|
||||
/// Reference to an imported content-browser asset or sub-asset.
|
||||
#[derive(Reflect, Default, Debug, Clone, PartialEq, Eq, Hash, Serialize, Deserialize)]
|
||||
#[reflect(Default, Debug, PartialEq, Serialize, Deserialize)]
|
||||
#[type_path = "shared::components"]
|
||||
pub struct EditorAssetRef {
|
||||
/// Stable project asset registry UUID string.
|
||||
pub asset_id: String,
|
||||
/// Stable imported sub-asset ID inside the generated artifact.
|
||||
#[serde(default, alias = "mesh_label")]
|
||||
pub sub_asset_id: String,
|
||||
/// UI label cached for inspectors. The asset registry/artifact remains authoritative.
|
||||
#[serde(default)]
|
||||
pub label: String,
|
||||
/// Optional loadable project path cached for runtime hydration.
|
||||
#[serde(default)]
|
||||
pub source_path: Option<String>,
|
||||
}
|
||||
|
||||
impl EditorAssetRef {
|
||||
pub fn new(
|
||||
asset_id: impl Into<String>,
|
||||
sub_asset_id: impl Into<String>,
|
||||
label: impl Into<String>,
|
||||
) -> Self {
|
||||
Self {
|
||||
asset_id: asset_id.into(),
|
||||
sub_asset_id: sub_asset_id.into(),
|
||||
label: label.into(),
|
||||
source_path: None,
|
||||
}
|
||||
}
|
||||
|
||||
pub fn with_source_path(mut self, source_path: impl Into<String>) -> Self {
|
||||
self.source_path = Some(source_path.into());
|
||||
self
|
||||
}
|
||||
|
||||
pub fn is_resolved(&self) -> bool {
|
||||
!self.asset_id.trim().is_empty() && !self.sub_asset_id.trim().is_empty()
|
||||
}
|
||||
}
|
||||
|
||||
/// How a material should be resolved at runtime.
|
||||
#[derive(Reflect, Default, Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
|
||||
#[reflect(Default, Debug, PartialEq, Serialize, Deserialize)]
|
||||
#[type_path = "shared::components"]
|
||||
pub enum MaterialShaderKind {
|
||||
#[default]
|
||||
StandardLit,
|
||||
Unlit,
|
||||
Custom,
|
||||
}
|
||||
|
||||
/// Reference to a built-in or custom shader schema.
|
||||
#[derive(Reflect, Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
|
||||
#[reflect(Default, Debug, PartialEq, Serialize, Deserialize)]
|
||||
#[type_path = "shared::components"]
|
||||
pub struct ShaderRefDesc {
|
||||
pub kind: MaterialShaderKind,
|
||||
#[serde(default)]
|
||||
pub schema_path: Option<String>,
|
||||
#[serde(default)]
|
||||
pub shader_path: Option<String>,
|
||||
}
|
||||
|
||||
impl Default for ShaderRefDesc {
|
||||
fn default() -> Self {
|
||||
Self {
|
||||
kind: MaterialShaderKind::StandardLit,
|
||||
schema_path: None,
|
||||
shader_path: None,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Serializable color description used by authored material documents.
|
||||
#[derive(Reflect, Debug, Clone, Copy, PartialEq, Serialize, Deserialize)]
|
||||
#[reflect(Default, Debug, Serialize, Deserialize)]
|
||||
#[type_path = "shared::components"]
|
||||
pub struct ColorDesc {
|
||||
pub r: f32,
|
||||
pub g: f32,
|
||||
pub b: f32,
|
||||
pub a: f32,
|
||||
}
|
||||
|
||||
impl ColorDesc {
|
||||
pub const fn srgb(r: f32, g: f32, b: f32) -> Self {
|
||||
Self { r, g, b, a: 1.0 }
|
||||
}
|
||||
|
||||
pub fn to_color(self) -> Color {
|
||||
Color::srgba(self.r, self.g, self.b, self.a)
|
||||
}
|
||||
}
|
||||
|
||||
impl Default for ColorDesc {
|
||||
fn default() -> Self {
|
||||
Self::srgb(0.8, 0.8, 0.8)
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Reflect, Debug, Clone, PartialEq, Serialize, Deserialize)]
|
||||
#[reflect(Default, Debug, PartialEq, Serialize, Deserialize)]
|
||||
#[type_path = "shared::components"]
|
||||
pub enum MaterialParameterValue {
|
||||
Bool(bool),
|
||||
Float(f32),
|
||||
Vec2(Vec2),
|
||||
Vec3(Vec3),
|
||||
Color(ColorDesc),
|
||||
Enum(String),
|
||||
}
|
||||
|
||||
impl Default for MaterialParameterValue {
|
||||
fn default() -> Self {
|
||||
Self::Float(0.0)
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Reflect, Default, Debug, Clone, PartialEq, Serialize, Deserialize)]
|
||||
#[reflect(Default, Debug, PartialEq, Serialize, Deserialize)]
|
||||
#[type_path = "shared::components"]
|
||||
pub struct MaterialParameter {
|
||||
pub name: String,
|
||||
pub value: MaterialParameterValue,
|
||||
}
|
||||
|
||||
/// Channels sampled from a texture binding.
|
||||
#[derive(Reflect, Default, Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
|
||||
#[reflect(Default, Debug, PartialEq, Serialize, Deserialize)]
|
||||
#[type_path = "shared::components"]
|
||||
pub enum TextureChannel {
|
||||
R,
|
||||
G,
|
||||
B,
|
||||
A,
|
||||
Rgb,
|
||||
#[default]
|
||||
Rgba,
|
||||
}
|
||||
|
||||
#[derive(Reflect, Default, Debug, Clone, PartialEq, Serialize, Deserialize)]
|
||||
#[reflect(Default, Debug, PartialEq, Serialize, Deserialize)]
|
||||
#[type_path = "shared::components"]
|
||||
pub struct MaterialTextureBinding {
|
||||
pub name: String,
|
||||
pub texture: Option<EditorAssetRef>,
|
||||
#[serde(default)]
|
||||
pub channel: TextureChannel,
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, Copy, Default, Serialize, Deserialize, PartialEq, Eq)]
|
||||
pub enum MaterialAlphaMode {
|
||||
#[default]
|
||||
Opaque,
|
||||
Cutout,
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, Copy, Serialize, Deserialize, PartialEq)]
|
||||
pub struct MaterialRenderState {
|
||||
#[serde(default)]
|
||||
pub alpha_mode: MaterialAlphaMode,
|
||||
#[serde(default = "default_alpha_cutoff")]
|
||||
pub alpha_cutoff: f32,
|
||||
#[serde(default)]
|
||||
pub double_sided: bool,
|
||||
}
|
||||
|
||||
const fn default_alpha_cutoff() -> f32 {
|
||||
0.5
|
||||
}
|
||||
|
||||
impl Default for MaterialRenderState {
|
||||
fn default() -> Self {
|
||||
Self {
|
||||
alpha_mode: MaterialAlphaMode::Opaque,
|
||||
alpha_cutoff: default_alpha_cutoff(),
|
||||
double_sided: false,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Canonical values and texture bindings consumed by built-in and custom material schemas.
|
||||
#[derive(Debug, Clone, Default, Serialize, Deserialize, PartialEq)]
|
||||
pub struct MaterialInputSet {
|
||||
#[serde(default)]
|
||||
pub values: Vec<MaterialParameter>,
|
||||
#[serde(default)]
|
||||
pub textures: Vec<MaterialTextureBinding>,
|
||||
}
|
||||
|
||||
impl MaterialInputSet {
|
||||
pub fn from_material_desc<T: MaterialInputSource>(source: &T) -> Self {
|
||||
source.to_material_inputs()
|
||||
}
|
||||
|
||||
pub fn apply_to_material_desc<T: MaterialInputTarget>(&self, target: &mut T) {
|
||||
target.apply_material_inputs(self);
|
||||
}
|
||||
|
||||
pub fn texture(&self, name: &str) -> Option<&MaterialTextureBinding> {
|
||||
self.textures.iter().find(|binding| binding.name == name)
|
||||
}
|
||||
|
||||
pub fn validate_unique(&self) -> Result<(), String> {
|
||||
let mut names = std::collections::HashSet::new();
|
||||
for value in &self.values {
|
||||
if !names.insert(("value", value.name.as_str())) {
|
||||
return Err(format!(
|
||||
"material value `{}` is assigned more than once",
|
||||
value.name
|
||||
));
|
||||
}
|
||||
}
|
||||
for texture in &self.textures {
|
||||
if !names.insert(("texture", texture.name.as_str())) {
|
||||
return Err(format!(
|
||||
"material texture `{}` is assigned more than once",
|
||||
texture.name
|
||||
));
|
||||
}
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
}
|
||||
|
||||
/// Runtime-owned descriptors implement this bridge without making the schema crate depend on the
|
||||
/// renderer or scene representation.
|
||||
pub trait MaterialInputSource {
|
||||
fn to_material_inputs(&self) -> MaterialInputSet;
|
||||
}
|
||||
|
||||
/// Runtime-owned descriptors implement this bridge without making lightweight authoring tools
|
||||
/// depend on those descriptors.
|
||||
pub trait MaterialInputTarget {
|
||||
fn apply_material_inputs(&mut self, inputs: &MaterialInputSet);
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
|
||||
pub enum ShaderPropertyType {
|
||||
Bool,
|
||||
Float { min: Option<f32>, max: Option<f32> },
|
||||
Vec2,
|
||||
Vec3,
|
||||
Color,
|
||||
Enum { options: Vec<String> },
|
||||
Texture,
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, Default, Serialize, Deserialize, PartialEq, Eq)]
|
||||
pub struct MaterialInputGroupDesc {
|
||||
pub id: String,
|
||||
pub display_name: String,
|
||||
#[serde(default)]
|
||||
pub order: i32,
|
||||
#[serde(default)]
|
||||
pub advanced: bool,
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, Copy, Default, Serialize, Deserialize, PartialEq, Eq)]
|
||||
pub enum TextureSemantic {
|
||||
#[default]
|
||||
Auto,
|
||||
Color,
|
||||
Normal,
|
||||
Scalar,
|
||||
Mask,
|
||||
Hdr,
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
|
||||
pub struct MaterialTextureInputDesc {
|
||||
#[serde(default)]
|
||||
pub semantic: TextureSemantic,
|
||||
#[serde(default)]
|
||||
pub default_channel: TextureChannel,
|
||||
#[serde(default)]
|
||||
pub allow_channel_override: bool,
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, Default, Serialize, Deserialize, PartialEq, Eq)]
|
||||
pub enum MaterialInputPresentation {
|
||||
#[default]
|
||||
Row,
|
||||
Companion {
|
||||
owner: String,
|
||||
},
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
|
||||
pub struct MaterialInputDesc {
|
||||
pub name: String,
|
||||
pub display_name: String,
|
||||
#[serde(default)]
|
||||
pub group: String,
|
||||
#[serde(default)]
|
||||
pub order: i32,
|
||||
pub property_type: ShaderPropertyType,
|
||||
#[serde(default)]
|
||||
pub default_value: Option<MaterialParameterValue>,
|
||||
#[serde(default)]
|
||||
pub texture: Option<MaterialTextureInputDesc>,
|
||||
#[serde(default)]
|
||||
pub tooltip: String,
|
||||
#[serde(default)]
|
||||
pub advanced: bool,
|
||||
#[serde(default)]
|
||||
pub presentation: MaterialInputPresentation,
|
||||
}
|
||||
|
||||
impl Default for MaterialInputDesc {
|
||||
fn default() -> Self {
|
||||
Self {
|
||||
name: String::new(),
|
||||
display_name: String::new(),
|
||||
group: String::new(),
|
||||
order: 0,
|
||||
property_type: ShaderPropertyType::Float {
|
||||
min: None,
|
||||
max: None,
|
||||
},
|
||||
default_value: None,
|
||||
texture: None,
|
||||
tooltip: String::new(),
|
||||
advanced: false,
|
||||
presentation: MaterialInputPresentation::Row,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Compatibility source alias for code that has not yet adopted material-input terminology.
|
||||
pub type ShaderPropertyDesc = MaterialInputDesc;
|
||||
|
||||
#[derive(Debug, Clone, Default, Serialize, Deserialize, PartialEq)]
|
||||
pub struct MaterialInputSchema {
|
||||
#[serde(default)]
|
||||
pub groups: Vec<MaterialInputGroupDesc>,
|
||||
#[serde(default)]
|
||||
pub inputs: Vec<MaterialInputDesc>,
|
||||
}
|
||||
|
||||
/// Engine-owned Standard Lit authoring schema. Custom Surface schemas use the same shape.
|
||||
pub fn standard_lit_input_schema() -> MaterialInputSchema {
|
||||
let groups = vec![
|
||||
MaterialInputGroupDesc {
|
||||
id: "surface_inputs".into(),
|
||||
display_name: "Surface Inputs".into(),
|
||||
order: 0,
|
||||
advanced: false,
|
||||
},
|
||||
MaterialInputGroupDesc {
|
||||
id: "advanced_inputs".into(),
|
||||
display_name: "Advanced Inputs".into(),
|
||||
order: 100,
|
||||
advanced: true,
|
||||
},
|
||||
MaterialInputGroupDesc {
|
||||
id: "uv_transform".into(),
|
||||
display_name: "UV Transform".into(),
|
||||
order: 90,
|
||||
advanced: false,
|
||||
},
|
||||
];
|
||||
let scalar_texture = |channel| MaterialTextureInputDesc {
|
||||
semantic: TextureSemantic::Scalar,
|
||||
default_channel: channel,
|
||||
allow_channel_override: true,
|
||||
};
|
||||
let inputs = vec![
|
||||
MaterialInputDesc {
|
||||
name: "base_color".into(),
|
||||
display_name: "Base Color".into(),
|
||||
group: "surface_inputs".into(),
|
||||
order: 0,
|
||||
property_type: ShaderPropertyType::Color,
|
||||
default_value: Some(MaterialParameterValue::Color(ColorDesc::default())),
|
||||
texture: Some(MaterialTextureInputDesc {
|
||||
semantic: TextureSemantic::Color,
|
||||
default_channel: TextureChannel::Rgba,
|
||||
allow_channel_override: false,
|
||||
}),
|
||||
tooltip: "Color multiplier applied to the base-color texture.".into(),
|
||||
advanced: false,
|
||||
presentation: MaterialInputPresentation::Row,
|
||||
},
|
||||
MaterialInputDesc {
|
||||
name: "metallic".into(),
|
||||
display_name: "Metallic".into(),
|
||||
group: "surface_inputs".into(),
|
||||
order: 10,
|
||||
property_type: ShaderPropertyType::Float {
|
||||
min: Some(0.0),
|
||||
max: Some(1.0),
|
||||
},
|
||||
default_value: Some(MaterialParameterValue::Float(0.0)),
|
||||
texture: Some(scalar_texture(TextureChannel::B)),
|
||||
tooltip: "Scalar multiplier; ARM/ORM uses the blue channel.".into(),
|
||||
advanced: false,
|
||||
presentation: MaterialInputPresentation::Row,
|
||||
},
|
||||
MaterialInputDesc {
|
||||
name: "roughness".into(),
|
||||
display_name: "Roughness".into(),
|
||||
group: "surface_inputs".into(),
|
||||
order: 20,
|
||||
property_type: ShaderPropertyType::Float {
|
||||
min: Some(0.0),
|
||||
max: Some(1.0),
|
||||
},
|
||||
default_value: Some(MaterialParameterValue::Float(0.65)),
|
||||
texture: Some(scalar_texture(TextureChannel::G)),
|
||||
tooltip: "Scalar multiplier; ARM/ORM uses the green channel.".into(),
|
||||
advanced: false,
|
||||
presentation: MaterialInputPresentation::Row,
|
||||
},
|
||||
MaterialInputDesc {
|
||||
name: "occlusion".into(),
|
||||
display_name: "Occlusion".into(),
|
||||
group: "surface_inputs".into(),
|
||||
order: 30,
|
||||
property_type: ShaderPropertyType::Float {
|
||||
min: Some(0.0),
|
||||
max: Some(1.0),
|
||||
},
|
||||
default_value: Some(MaterialParameterValue::Float(1.0)),
|
||||
texture: Some(scalar_texture(TextureChannel::R)),
|
||||
tooltip: "Ambient-occlusion strength; ARM/ORM uses the red channel.".into(),
|
||||
advanced: false,
|
||||
presentation: MaterialInputPresentation::Row,
|
||||
},
|
||||
MaterialInputDesc {
|
||||
name: "normal".into(),
|
||||
display_name: "Normal".into(),
|
||||
group: "surface_inputs".into(),
|
||||
order: 40,
|
||||
property_type: ShaderPropertyType::Float {
|
||||
min: Some(0.0),
|
||||
max: Some(1.0),
|
||||
},
|
||||
default_value: Some(MaterialParameterValue::Float(0.85)),
|
||||
texture: Some(MaterialTextureInputDesc {
|
||||
semantic: TextureSemantic::Normal,
|
||||
default_channel: TextureChannel::Rgb,
|
||||
allow_channel_override: false,
|
||||
}),
|
||||
tooltip: String::new(),
|
||||
advanced: false,
|
||||
presentation: MaterialInputPresentation::Row,
|
||||
},
|
||||
MaterialInputDesc {
|
||||
name: "emissive_color".into(),
|
||||
display_name: "Emissive".into(),
|
||||
group: "surface_inputs".into(),
|
||||
order: 50,
|
||||
property_type: ShaderPropertyType::Color,
|
||||
default_value: Some(MaterialParameterValue::Color(ColorDesc::srgb(
|
||||
1.0, 1.0, 1.0,
|
||||
))),
|
||||
texture: Some(MaterialTextureInputDesc {
|
||||
semantic: TextureSemantic::Color,
|
||||
default_channel: TextureChannel::Rgb,
|
||||
allow_channel_override: false,
|
||||
}),
|
||||
tooltip: "Emissive color multiplied by the texture and intensity.".into(),
|
||||
advanced: false,
|
||||
presentation: MaterialInputPresentation::Row,
|
||||
},
|
||||
MaterialInputDesc {
|
||||
name: "emissive_intensity".into(),
|
||||
display_name: "Emissive Intensity".into(),
|
||||
group: "surface_inputs".into(),
|
||||
order: 60,
|
||||
property_type: ShaderPropertyType::Float {
|
||||
min: Some(0.0),
|
||||
max: Some(50_000.0),
|
||||
},
|
||||
default_value: Some(MaterialParameterValue::Float(0.0)),
|
||||
texture: None,
|
||||
tooltip: "Emissive luminance multiplier in nits.".into(),
|
||||
advanced: false,
|
||||
presentation: MaterialInputPresentation::Companion {
|
||||
owner: "emissive_color".into(),
|
||||
},
|
||||
},
|
||||
MaterialInputDesc {
|
||||
name: "uv_offset".into(),
|
||||
display_name: "Offset".into(),
|
||||
group: "uv_transform".into(),
|
||||
order: 0,
|
||||
property_type: ShaderPropertyType::Vec2,
|
||||
default_value: Some(MaterialParameterValue::Vec2(Vec2::ZERO)),
|
||||
texture: None,
|
||||
tooltip: "Shared UV translation for every texture on this material.".into(),
|
||||
advanced: false,
|
||||
presentation: MaterialInputPresentation::Row,
|
||||
},
|
||||
MaterialInputDesc {
|
||||
name: "uv_tiling".into(),
|
||||
display_name: "Tiling".into(),
|
||||
group: "uv_transform".into(),
|
||||
order: 10,
|
||||
property_type: ShaderPropertyType::Vec2,
|
||||
default_value: Some(MaterialParameterValue::Vec2(Vec2::ONE)),
|
||||
texture: None,
|
||||
tooltip: "Shared UV scale for every texture on this material.".into(),
|
||||
advanced: false,
|
||||
presentation: MaterialInputPresentation::Row,
|
||||
},
|
||||
];
|
||||
MaterialInputSchema { groups, inputs }
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn standard_lit_has_six_primary_surface_rows() {
|
||||
let schema = standard_lit_input_schema();
|
||||
let surface = schema
|
||||
.inputs
|
||||
.iter()
|
||||
.filter(|input| input.group == "surface_inputs")
|
||||
.collect::<Vec<_>>();
|
||||
assert_eq!(surface.len(), 7);
|
||||
assert_eq!(
|
||||
surface
|
||||
.iter()
|
||||
.filter(|input| matches!(input.presentation, MaterialInputPresentation::Row))
|
||||
.count(),
|
||||
6
|
||||
);
|
||||
}
|
||||
}
|
||||
@@ -9,6 +9,7 @@ description = "Shared reflectable authoring types and scene hydration for the FP
|
||||
avian3d.workspace = true
|
||||
bevy.workspace = true
|
||||
blake3 = "1"
|
||||
material_schema.workspace = true
|
||||
ron = "0.8"
|
||||
serde.workspace = true
|
||||
settings.workspace = true
|
||||
|
||||
@@ -2,7 +2,7 @@ use avian3d::prelude::ColliderConstructor;
|
||||
use bevy::prelude::*;
|
||||
use serde::{Deserialize, Serialize};
|
||||
|
||||
use crate::{ColorDesc, MaterialDesc};
|
||||
use crate::{ColorDesc, EditorAssetRef, MaterialDesc};
|
||||
|
||||
/// Stable persisted identity for an actor. Bevy [`Entity`] IDs are runtime-only.
|
||||
#[derive(
|
||||
@@ -412,48 +412,6 @@ pub const COMPONENT_AUDIO_LISTENER_DESC: &str = "shared::components::AudioListen
|
||||
/// Stable imported sub-asset identifier used by authored audio clip references.
|
||||
pub const AUDIO_CLIP_SUB_ASSET_ID: &str = "audio:source";
|
||||
|
||||
/// Reference to an imported content-browser asset or sub-asset.
|
||||
#[derive(Reflect, Default, Debug, Clone, PartialEq, Eq, Hash, Serialize, Deserialize)]
|
||||
#[reflect(Default, Debug, PartialEq, Serialize, Deserialize)]
|
||||
pub struct EditorAssetRef {
|
||||
/// Stable project asset registry UUID string.
|
||||
pub asset_id: String,
|
||||
/// Stable imported sub-asset ID inside the generated artifact.
|
||||
#[serde(default, alias = "mesh_label")]
|
||||
pub sub_asset_id: String,
|
||||
/// UI label cached for inspectors. The asset registry/artifact remains authoritative.
|
||||
#[serde(default)]
|
||||
pub label: String,
|
||||
/// Optional loadable project path cached for runtime hydration when the
|
||||
/// referenced asset is not available through an imported artifact lookup.
|
||||
#[serde(default)]
|
||||
pub source_path: Option<String>,
|
||||
}
|
||||
|
||||
impl EditorAssetRef {
|
||||
pub fn new(
|
||||
asset_id: impl Into<String>,
|
||||
sub_asset_id: impl Into<String>,
|
||||
label: impl Into<String>,
|
||||
) -> Self {
|
||||
Self {
|
||||
asset_id: asset_id.into(),
|
||||
sub_asset_id: sub_asset_id.into(),
|
||||
label: label.into(),
|
||||
source_path: None,
|
||||
}
|
||||
}
|
||||
|
||||
pub fn with_source_path(mut self, source_path: impl Into<String>) -> Self {
|
||||
self.source_path = Some(source_path.into());
|
||||
self
|
||||
}
|
||||
|
||||
pub fn is_resolved(&self) -> bool {
|
||||
!self.asset_id.trim().is_empty() && !self.sub_asset_id.trim().is_empty()
|
||||
}
|
||||
}
|
||||
|
||||
/// Distance curve used by an authored spatial audio source.
|
||||
#[derive(Reflect, Default, Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
|
||||
#[reflect(Default, Debug, PartialEq, Serialize, Deserialize)]
|
||||
@@ -1237,37 +1195,6 @@ fn default_true() -> bool {
|
||||
true
|
||||
}
|
||||
|
||||
/// How a material should be resolved at runtime.
|
||||
#[derive(Reflect, Default, Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
|
||||
#[reflect(Default, Debug, PartialEq, Serialize, Deserialize)]
|
||||
pub enum MaterialShaderKind {
|
||||
#[default]
|
||||
StandardLit,
|
||||
Unlit,
|
||||
Custom,
|
||||
}
|
||||
|
||||
/// Reference to a built-in or custom shader schema.
|
||||
#[derive(Reflect, Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
|
||||
#[reflect(Default, Debug, PartialEq, Serialize, Deserialize)]
|
||||
pub struct ShaderRefDesc {
|
||||
pub kind: MaterialShaderKind,
|
||||
#[serde(default)]
|
||||
pub schema_path: Option<String>,
|
||||
#[serde(default)]
|
||||
pub shader_path: Option<String>,
|
||||
}
|
||||
|
||||
impl Default for ShaderRefDesc {
|
||||
fn default() -> Self {
|
||||
Self {
|
||||
kind: MaterialShaderKind::StandardLit,
|
||||
schema_path: None,
|
||||
shader_path: None,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Typed material parameter value exposed by a shader schema.
|
||||
/// Reflectable reference to an imported 3D model scene (glTF/GLB or FBX).
|
||||
/// Hydration turns this into a `WorldAssetRoot` on the entity.
|
||||
|
||||
@@ -19,6 +19,14 @@ mod prefab_overrides;
|
||||
mod renderer_material;
|
||||
mod rendering_profile_asset;
|
||||
|
||||
pub use material_schema::{
|
||||
standard_lit_input_schema, ColorDesc, EditorAssetRef, MaterialAlphaMode, MaterialInputDesc,
|
||||
MaterialInputGroupDesc, MaterialInputPresentation, MaterialInputSchema, MaterialInputSet,
|
||||
MaterialInputSource, MaterialInputTarget, MaterialParameter, MaterialParameterValue,
|
||||
MaterialRenderState, MaterialShaderKind, MaterialTextureBinding, MaterialTextureInputDesc,
|
||||
ShaderPropertyDesc, ShaderPropertyType, ShaderRefDesc, TextureChannel, TextureSemantic,
|
||||
};
|
||||
|
||||
pub use actor::{infer_actor_kind, validate_actor, ActorValidationError};
|
||||
pub use animation::*;
|
||||
pub use asset_fingerprint::AssetSourceFingerprint;
|
||||
@@ -33,12 +41,9 @@ pub use hydration::{
|
||||
StaticMeshArtifactCache,
|
||||
};
|
||||
pub use material_asset::{
|
||||
load_resolved_material_from_path, standard_lit_input_schema, MaterialAlphaMode, MaterialAsset,
|
||||
MaterialInputDesc, MaterialInputGroupDesc, MaterialInputPresentation, MaterialInputSchema,
|
||||
MaterialInputSet, MaterialInstanceAsset, MaterialProvenance, MaterialRenderState,
|
||||
MaterialTextureInputDesc, ShaderPropertyDesc, ShaderPropertyType, ShaderSchemaAsset,
|
||||
TextureSemantic, MATERIAL_ASSET_SCHEMA_VERSION, MATERIAL_INSTANCE_SCHEMA_VERSION,
|
||||
SURFACE_SHADER_SCHEMA_VERSION,
|
||||
apply_material_inputs_to_desc, load_resolved_material_from_path, material_inputs_from_desc,
|
||||
MaterialAsset, MaterialInstanceAsset, MaterialProvenance, ShaderSchemaAsset,
|
||||
MATERIAL_ASSET_SCHEMA_VERSION, MATERIAL_INSTANCE_SCHEMA_VERSION, SURFACE_SHADER_SCHEMA_VERSION,
|
||||
};
|
||||
pub use material_desc::*;
|
||||
pub use navigation::*;
|
||||
|
||||
+116
-451
@@ -4,8 +4,9 @@ use bevy::prelude::*;
|
||||
use serde::{Deserialize, Serialize};
|
||||
|
||||
use crate::{
|
||||
ColorDesc, EditorAssetRef, MaterialDesc, MaterialParameter, MaterialParameterValue,
|
||||
MaterialRef, MaterialShaderKind, MaterialTextureBinding, ShaderRefDesc, TextureChannel,
|
||||
EditorAssetRef, MaterialDesc, MaterialInputSchema, MaterialInputSet, MaterialInputSource,
|
||||
MaterialInputTarget, MaterialParameter, MaterialParameterValue, MaterialRef,
|
||||
MaterialRenderState, MaterialShaderKind, MaterialTextureBinding, ShaderRefDesc, TextureChannel,
|
||||
};
|
||||
|
||||
pub const MATERIAL_ASSET_SCHEMA_VERSION: u32 = 2;
|
||||
@@ -24,182 +25,124 @@ const fn default_surface_shader_schema_version() -> u32 {
|
||||
SURFACE_SHADER_SCHEMA_VERSION
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, Copy, Default, Serialize, Deserialize, PartialEq, Eq)]
|
||||
pub enum MaterialAlphaMode {
|
||||
#[default]
|
||||
Opaque,
|
||||
Cutout,
|
||||
/// Converts the runtime/legacy descriptor into the lightweight authored input representation.
|
||||
pub fn material_inputs_from_desc(material: &MaterialDesc) -> MaterialInputSet {
|
||||
let mut values = vec![
|
||||
MaterialParameter {
|
||||
name: "base_color".into(),
|
||||
value: MaterialParameterValue::Color(material.base_color),
|
||||
},
|
||||
MaterialParameter {
|
||||
name: "metallic".into(),
|
||||
value: MaterialParameterValue::Float(material.metallic),
|
||||
},
|
||||
MaterialParameter {
|
||||
name: "roughness".into(),
|
||||
value: MaterialParameterValue::Float(material.roughness),
|
||||
},
|
||||
MaterialParameter {
|
||||
name: "emissive_color".into(),
|
||||
value: MaterialParameterValue::Color(material.emissive_color),
|
||||
},
|
||||
MaterialParameter {
|
||||
name: "emissive_intensity".into(),
|
||||
value: MaterialParameterValue::Float(material.emissive_intensity),
|
||||
},
|
||||
MaterialParameter {
|
||||
name: "uv_offset".into(),
|
||||
value: MaterialParameterValue::Vec2(material.uv_offset),
|
||||
},
|
||||
MaterialParameter {
|
||||
name: "uv_tiling".into(),
|
||||
value: MaterialParameterValue::Vec2(material.uv_tiling),
|
||||
},
|
||||
];
|
||||
for parameter in &material.parameters {
|
||||
if !is_standard_value_name(¶meter.name) {
|
||||
upsert_parameter(&mut values, parameter.clone());
|
||||
}
|
||||
}
|
||||
|
||||
let mut textures = Vec::new();
|
||||
if let Some(path) = material.base_color_texture.as_deref() {
|
||||
textures.push(path_texture_binding(
|
||||
"base_color",
|
||||
path,
|
||||
TextureChannel::Rgba,
|
||||
));
|
||||
}
|
||||
if let Some(path) = material.normal_map_texture.as_deref() {
|
||||
textures.push(path_texture_binding("normal", path, TextureChannel::Rgb));
|
||||
}
|
||||
if let Some(path) = material.metallic_roughness_texture.as_deref() {
|
||||
textures.push(path_texture_binding("occlusion", path, TextureChannel::R));
|
||||
textures.push(path_texture_binding("roughness", path, TextureChannel::G));
|
||||
textures.push(path_texture_binding("metallic", path, TextureChannel::B));
|
||||
}
|
||||
if let Some(path) = material.occlusion_texture.as_deref() {
|
||||
upsert_texture(
|
||||
&mut textures,
|
||||
path_texture_binding("occlusion", path, TextureChannel::R),
|
||||
);
|
||||
}
|
||||
if let Some(path) = material.emissive_texture.as_deref() {
|
||||
textures.push(path_texture_binding("emissive", path, TextureChannel::Rgb));
|
||||
}
|
||||
for texture in &material.textures {
|
||||
if !is_standard_texture_name(&texture.name) {
|
||||
upsert_texture(&mut textures, texture.clone());
|
||||
}
|
||||
}
|
||||
MaterialInputSet { values, textures }
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, Copy, Serialize, Deserialize, PartialEq)]
|
||||
pub struct MaterialRenderState {
|
||||
#[serde(default)]
|
||||
pub alpha_mode: MaterialAlphaMode,
|
||||
#[serde(default = "default_alpha_cutoff")]
|
||||
pub alpha_cutoff: f32,
|
||||
#[serde(default)]
|
||||
pub double_sided: bool,
|
||||
}
|
||||
|
||||
const fn default_alpha_cutoff() -> f32 {
|
||||
0.5
|
||||
}
|
||||
|
||||
impl Default for MaterialRenderState {
|
||||
fn default() -> Self {
|
||||
Self {
|
||||
alpha_mode: MaterialAlphaMode::Opaque,
|
||||
alpha_cutoff: default_alpha_cutoff(),
|
||||
double_sided: false,
|
||||
/// Applies authored values to the runtime/legacy material representation.
|
||||
pub fn apply_material_inputs_to_desc(inputs: &MaterialInputSet, material: &mut MaterialDesc) {
|
||||
material.parameters.clear();
|
||||
material.textures.clear();
|
||||
for parameter in &inputs.values {
|
||||
match (parameter.name.as_str(), ¶meter.value) {
|
||||
("base_color", MaterialParameterValue::Color(value)) => material.base_color = *value,
|
||||
("metallic", MaterialParameterValue::Float(value)) => material.metallic = *value,
|
||||
("roughness", MaterialParameterValue::Float(value)) => material.roughness = *value,
|
||||
("emissive_color", MaterialParameterValue::Color(value)) => {
|
||||
material.emissive_color = *value
|
||||
}
|
||||
("emissive_intensity", MaterialParameterValue::Float(value)) => {
|
||||
material.emissive_intensity = *value
|
||||
}
|
||||
("uv_offset", MaterialParameterValue::Vec2(value)) => material.uv_offset = *value,
|
||||
("uv_tiling", MaterialParameterValue::Vec2(value)) => material.uv_tiling = *value,
|
||||
_ => upsert_parameter(&mut material.parameters, parameter.clone()),
|
||||
}
|
||||
}
|
||||
material.base_color_texture = binding_path(inputs.texture("base_color"));
|
||||
material.normal_map_texture = binding_path(inputs.texture("normal"));
|
||||
material.emissive_texture = binding_path(inputs.texture("emissive"));
|
||||
let roughness = binding_path(inputs.texture("roughness"));
|
||||
let metallic = binding_path(inputs.texture("metallic"));
|
||||
material.metallic_roughness_texture = match (roughness, metallic) {
|
||||
(Some(roughness), Some(metallic)) if roughness == metallic => Some(roughness),
|
||||
(Some(path), None) | (None, Some(path)) => Some(path),
|
||||
_ => None,
|
||||
};
|
||||
material.occlusion_texture = binding_path(inputs.texture("occlusion"));
|
||||
for texture in &inputs.textures {
|
||||
if !is_standard_texture_name(&texture.name) {
|
||||
upsert_texture(&mut material.textures, texture.clone());
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Canonical values and texture bindings consumed by both built-in and custom material schemas.
|
||||
///
|
||||
/// Values are keyed by stable input names. Validation rejects duplicates before publication;
|
||||
/// vectors are retained instead of maps so shader-defined presentation order remains serializable.
|
||||
#[derive(Debug, Clone, Default, Serialize, Deserialize, PartialEq)]
|
||||
pub struct MaterialInputSet {
|
||||
#[serde(default)]
|
||||
pub values: Vec<MaterialParameter>,
|
||||
#[serde(default)]
|
||||
pub textures: Vec<MaterialTextureBinding>,
|
||||
impl MaterialInputSource for MaterialDesc {
|
||||
fn to_material_inputs(&self) -> MaterialInputSet {
|
||||
material_inputs_from_desc(self)
|
||||
}
|
||||
}
|
||||
|
||||
impl MaterialInputSet {
|
||||
pub fn from_material_desc(material: &MaterialDesc) -> Self {
|
||||
let mut values = vec![
|
||||
MaterialParameter {
|
||||
name: "base_color".into(),
|
||||
value: MaterialParameterValue::Color(material.base_color),
|
||||
},
|
||||
MaterialParameter {
|
||||
name: "metallic".into(),
|
||||
value: MaterialParameterValue::Float(material.metallic),
|
||||
},
|
||||
MaterialParameter {
|
||||
name: "roughness".into(),
|
||||
value: MaterialParameterValue::Float(material.roughness),
|
||||
},
|
||||
MaterialParameter {
|
||||
name: "emissive_color".into(),
|
||||
value: MaterialParameterValue::Color(material.emissive_color),
|
||||
},
|
||||
MaterialParameter {
|
||||
name: "emissive_intensity".into(),
|
||||
value: MaterialParameterValue::Float(material.emissive_intensity),
|
||||
},
|
||||
MaterialParameter {
|
||||
name: "uv_offset".into(),
|
||||
value: MaterialParameterValue::Vec2(material.uv_offset),
|
||||
},
|
||||
MaterialParameter {
|
||||
name: "uv_tiling".into(),
|
||||
value: MaterialParameterValue::Vec2(material.uv_tiling),
|
||||
},
|
||||
];
|
||||
for parameter in &material.parameters {
|
||||
if !is_standard_value_name(¶meter.name) {
|
||||
upsert_parameter(&mut values, parameter.clone());
|
||||
}
|
||||
}
|
||||
|
||||
let mut textures = Vec::new();
|
||||
if let Some(path) = material.base_color_texture.as_deref() {
|
||||
textures.push(path_texture_binding(
|
||||
"base_color",
|
||||
path,
|
||||
TextureChannel::Rgba,
|
||||
));
|
||||
}
|
||||
if let Some(path) = material.normal_map_texture.as_deref() {
|
||||
textures.push(path_texture_binding("normal", path, TextureChannel::Rgb));
|
||||
}
|
||||
if let Some(path) = material.metallic_roughness_texture.as_deref() {
|
||||
textures.push(path_texture_binding("occlusion", path, TextureChannel::R));
|
||||
textures.push(path_texture_binding("roughness", path, TextureChannel::G));
|
||||
textures.push(path_texture_binding("metallic", path, TextureChannel::B));
|
||||
}
|
||||
if let Some(path) = material.occlusion_texture.as_deref() {
|
||||
upsert_texture(
|
||||
&mut textures,
|
||||
path_texture_binding("occlusion", path, TextureChannel::R),
|
||||
);
|
||||
}
|
||||
if let Some(path) = material.emissive_texture.as_deref() {
|
||||
textures.push(path_texture_binding("emissive", path, TextureChannel::Rgb));
|
||||
}
|
||||
for texture in &material.textures {
|
||||
if !is_standard_texture_name(&texture.name) {
|
||||
upsert_texture(&mut textures, texture.clone());
|
||||
}
|
||||
}
|
||||
Self { values, textures }
|
||||
}
|
||||
|
||||
pub fn apply_to_material_desc(&self, material: &mut MaterialDesc) {
|
||||
material.parameters.clear();
|
||||
material.textures.clear();
|
||||
for parameter in &self.values {
|
||||
match (parameter.name.as_str(), ¶meter.value) {
|
||||
("base_color", MaterialParameterValue::Color(value)) => {
|
||||
material.base_color = *value
|
||||
}
|
||||
("metallic", MaterialParameterValue::Float(value)) => material.metallic = *value,
|
||||
("roughness", MaterialParameterValue::Float(value)) => material.roughness = *value,
|
||||
("emissive_color", MaterialParameterValue::Color(value)) => {
|
||||
material.emissive_color = *value
|
||||
}
|
||||
("emissive_intensity", MaterialParameterValue::Float(value)) => {
|
||||
material.emissive_intensity = *value
|
||||
}
|
||||
("uv_offset", MaterialParameterValue::Vec2(value)) => material.uv_offset = *value,
|
||||
("uv_tiling", MaterialParameterValue::Vec2(value)) => material.uv_tiling = *value,
|
||||
_ => upsert_parameter(&mut material.parameters, parameter.clone()),
|
||||
}
|
||||
}
|
||||
material.base_color_texture = binding_path(self.texture("base_color"));
|
||||
material.normal_map_texture = binding_path(self.texture("normal"));
|
||||
material.emissive_texture = binding_path(self.texture("emissive"));
|
||||
let roughness = binding_path(self.texture("roughness"));
|
||||
let metallic = binding_path(self.texture("metallic"));
|
||||
material.metallic_roughness_texture = match (roughness, metallic) {
|
||||
(Some(roughness), Some(metallic)) if roughness == metallic => Some(roughness),
|
||||
(Some(path), None) | (None, Some(path)) => Some(path),
|
||||
_ => None,
|
||||
};
|
||||
material.occlusion_texture = binding_path(self.texture("occlusion"));
|
||||
for texture in &self.textures {
|
||||
if !is_standard_texture_name(&texture.name) {
|
||||
upsert_texture(&mut material.textures, texture.clone());
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
pub fn texture(&self, name: &str) -> Option<&MaterialTextureBinding> {
|
||||
self.textures.iter().find(|binding| binding.name == name)
|
||||
}
|
||||
|
||||
pub fn validate_unique(&self) -> Result<(), String> {
|
||||
let mut names = std::collections::HashSet::new();
|
||||
for value in &self.values {
|
||||
if !names.insert(("value", value.name.as_str())) {
|
||||
return Err(format!(
|
||||
"material value `{}` is assigned more than once",
|
||||
value.name
|
||||
));
|
||||
}
|
||||
}
|
||||
for texture in &self.textures {
|
||||
if !names.insert(("texture", texture.name.as_str())) {
|
||||
return Err(format!(
|
||||
"material texture `{}` is assigned more than once",
|
||||
texture.name
|
||||
));
|
||||
}
|
||||
}
|
||||
Ok(())
|
||||
impl MaterialInputTarget for MaterialDesc {
|
||||
fn apply_material_inputs(&mut self, inputs: &MaterialInputSet) {
|
||||
apply_material_inputs_to_desc(inputs, self);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -420,115 +363,6 @@ fn upsert_texture(values: &mut Vec<MaterialTextureBinding>, value: MaterialTextu
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
|
||||
pub enum ShaderPropertyType {
|
||||
Bool,
|
||||
Float { min: Option<f32>, max: Option<f32> },
|
||||
Vec2,
|
||||
Vec3,
|
||||
Color,
|
||||
Enum { options: Vec<String> },
|
||||
Texture,
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, Default, Serialize, Deserialize, PartialEq, Eq)]
|
||||
pub struct MaterialInputGroupDesc {
|
||||
pub id: String,
|
||||
pub display_name: String,
|
||||
#[serde(default)]
|
||||
pub order: i32,
|
||||
#[serde(default)]
|
||||
pub advanced: bool,
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, Copy, Default, Serialize, Deserialize, PartialEq, Eq)]
|
||||
pub enum TextureSemantic {
|
||||
#[default]
|
||||
Auto,
|
||||
Color,
|
||||
Normal,
|
||||
Scalar,
|
||||
Mask,
|
||||
Hdr,
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
|
||||
pub struct MaterialTextureInputDesc {
|
||||
#[serde(default)]
|
||||
pub semantic: TextureSemantic,
|
||||
#[serde(default)]
|
||||
pub default_channel: TextureChannel,
|
||||
#[serde(default)]
|
||||
pub allow_channel_override: bool,
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
|
||||
pub struct MaterialInputDesc {
|
||||
pub name: String,
|
||||
pub display_name: String,
|
||||
#[serde(default)]
|
||||
pub group: String,
|
||||
#[serde(default)]
|
||||
pub order: i32,
|
||||
pub property_type: ShaderPropertyType,
|
||||
#[serde(default)]
|
||||
pub default_value: Option<MaterialParameterValue>,
|
||||
#[serde(default)]
|
||||
pub texture: Option<MaterialTextureInputDesc>,
|
||||
#[serde(default)]
|
||||
pub tooltip: String,
|
||||
#[serde(default)]
|
||||
pub advanced: bool,
|
||||
/// Authoring presentation only. Runtime evaluation continues to address inputs by `name`.
|
||||
#[serde(default)]
|
||||
pub presentation: MaterialInputPresentation,
|
||||
}
|
||||
|
||||
impl Default for MaterialInputDesc {
|
||||
fn default() -> Self {
|
||||
Self {
|
||||
name: String::new(),
|
||||
display_name: String::new(),
|
||||
group: String::new(),
|
||||
order: 0,
|
||||
property_type: ShaderPropertyType::Float {
|
||||
min: None,
|
||||
max: None,
|
||||
},
|
||||
default_value: None,
|
||||
texture: None,
|
||||
tooltip: String::new(),
|
||||
advanced: false,
|
||||
presentation: MaterialInputPresentation::Row,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Declares whether an input owns a visible row or is edited through another input's row.
|
||||
///
|
||||
/// Companion values remain independent in [`MaterialInputSet`]. This keeps the schema suitable for
|
||||
/// generated/custom shaders while allowing related controls such as emissive color and intensity
|
||||
/// to share one coherent Inspector row.
|
||||
#[derive(Debug, Clone, Default, Serialize, Deserialize, PartialEq, Eq)]
|
||||
pub enum MaterialInputPresentation {
|
||||
#[default]
|
||||
Row,
|
||||
Companion {
|
||||
owner: String,
|
||||
},
|
||||
}
|
||||
|
||||
/// Compatibility source alias for code that has not yet adopted the material-input terminology.
|
||||
pub type ShaderPropertyDesc = MaterialInputDesc;
|
||||
|
||||
#[derive(Debug, Clone, Default, Serialize, Deserialize, PartialEq)]
|
||||
pub struct MaterialInputSchema {
|
||||
#[serde(default)]
|
||||
pub groups: Vec<MaterialInputGroupDesc>,
|
||||
#[serde(default)]
|
||||
pub inputs: Vec<MaterialInputDesc>,
|
||||
}
|
||||
|
||||
/// RON shader schema describing material inspector parameters.
|
||||
#[derive(Asset, TypePath, Debug, Clone, Serialize, Deserialize, PartialEq)]
|
||||
#[serde(deny_unknown_fields)]
|
||||
@@ -552,181 +386,12 @@ impl ShaderSchemaAsset {
|
||||
}
|
||||
}
|
||||
|
||||
/// Engine-owned Standard Lit authoring schema. It is consumed by the same renderer used for
|
||||
/// project Surface schemas, so a future graph compiler only needs to emit this descriptor shape.
|
||||
pub fn standard_lit_input_schema() -> MaterialInputSchema {
|
||||
let groups = vec![
|
||||
MaterialInputGroupDesc {
|
||||
id: "surface_inputs".into(),
|
||||
display_name: "Surface Inputs".into(),
|
||||
order: 0,
|
||||
advanced: false,
|
||||
},
|
||||
MaterialInputGroupDesc {
|
||||
id: "advanced_inputs".into(),
|
||||
display_name: "Advanced Inputs".into(),
|
||||
order: 100,
|
||||
advanced: true,
|
||||
},
|
||||
MaterialInputGroupDesc {
|
||||
id: "uv_transform".into(),
|
||||
display_name: "UV Transform".into(),
|
||||
order: 90,
|
||||
advanced: false,
|
||||
},
|
||||
];
|
||||
let scalar_texture = |channel| MaterialTextureInputDesc {
|
||||
semantic: TextureSemantic::Scalar,
|
||||
default_channel: channel,
|
||||
allow_channel_override: true,
|
||||
};
|
||||
let inputs = vec![
|
||||
MaterialInputDesc {
|
||||
name: "base_color".into(),
|
||||
display_name: "Base Color".into(),
|
||||
group: "surface_inputs".into(),
|
||||
order: 0,
|
||||
property_type: ShaderPropertyType::Color,
|
||||
default_value: Some(MaterialParameterValue::Color(ColorDesc::default())),
|
||||
texture: Some(MaterialTextureInputDesc {
|
||||
semantic: TextureSemantic::Color,
|
||||
default_channel: TextureChannel::Rgba,
|
||||
allow_channel_override: false,
|
||||
}),
|
||||
tooltip: "Color multiplier applied to the base-color texture.".into(),
|
||||
advanced: false,
|
||||
presentation: MaterialInputPresentation::Row,
|
||||
},
|
||||
MaterialInputDesc {
|
||||
name: "metallic".into(),
|
||||
display_name: "Metallic".into(),
|
||||
group: "surface_inputs".into(),
|
||||
order: 10,
|
||||
property_type: ShaderPropertyType::Float {
|
||||
min: Some(0.0),
|
||||
max: Some(1.0),
|
||||
},
|
||||
default_value: Some(MaterialParameterValue::Float(0.0)),
|
||||
texture: Some(scalar_texture(TextureChannel::B)),
|
||||
tooltip: "Scalar multiplier; ARM/ORM uses the blue channel.".into(),
|
||||
advanced: false,
|
||||
presentation: MaterialInputPresentation::Row,
|
||||
},
|
||||
MaterialInputDesc {
|
||||
name: "roughness".into(),
|
||||
display_name: "Roughness".into(),
|
||||
group: "surface_inputs".into(),
|
||||
order: 20,
|
||||
property_type: ShaderPropertyType::Float {
|
||||
min: Some(0.0),
|
||||
max: Some(1.0),
|
||||
},
|
||||
default_value: Some(MaterialParameterValue::Float(0.65)),
|
||||
texture: Some(scalar_texture(TextureChannel::G)),
|
||||
tooltip: "Scalar multiplier; ARM/ORM uses the green channel.".into(),
|
||||
advanced: false,
|
||||
presentation: MaterialInputPresentation::Row,
|
||||
},
|
||||
MaterialInputDesc {
|
||||
name: "occlusion".into(),
|
||||
display_name: "Occlusion".into(),
|
||||
group: "surface_inputs".into(),
|
||||
order: 30,
|
||||
property_type: ShaderPropertyType::Float {
|
||||
min: Some(0.0),
|
||||
max: Some(1.0),
|
||||
},
|
||||
default_value: Some(MaterialParameterValue::Float(1.0)),
|
||||
texture: Some(scalar_texture(TextureChannel::R)),
|
||||
tooltip: "Ambient-occlusion strength; ARM/ORM uses the red channel.".into(),
|
||||
advanced: false,
|
||||
presentation: MaterialInputPresentation::Row,
|
||||
},
|
||||
MaterialInputDesc {
|
||||
name: "normal".into(),
|
||||
display_name: "Normal".into(),
|
||||
group: "surface_inputs".into(),
|
||||
order: 40,
|
||||
property_type: ShaderPropertyType::Float {
|
||||
min: Some(0.0),
|
||||
max: Some(1.0),
|
||||
},
|
||||
default_value: Some(MaterialParameterValue::Float(0.85)),
|
||||
texture: Some(MaterialTextureInputDesc {
|
||||
semantic: TextureSemantic::Normal,
|
||||
default_channel: TextureChannel::Rgb,
|
||||
allow_channel_override: false,
|
||||
}),
|
||||
tooltip: String::new(),
|
||||
advanced: false,
|
||||
presentation: MaterialInputPresentation::Row,
|
||||
},
|
||||
MaterialInputDesc {
|
||||
name: "emissive_color".into(),
|
||||
display_name: "Emissive".into(),
|
||||
group: "surface_inputs".into(),
|
||||
order: 50,
|
||||
property_type: ShaderPropertyType::Color,
|
||||
default_value: Some(MaterialParameterValue::Color(ColorDesc::srgb(
|
||||
1.0, 1.0, 1.0,
|
||||
))),
|
||||
texture: Some(MaterialTextureInputDesc {
|
||||
semantic: TextureSemantic::Color,
|
||||
default_channel: TextureChannel::Rgb,
|
||||
allow_channel_override: false,
|
||||
}),
|
||||
tooltip: "Emissive color multiplied by the texture and intensity.".into(),
|
||||
advanced: false,
|
||||
presentation: MaterialInputPresentation::Row,
|
||||
},
|
||||
MaterialInputDesc {
|
||||
name: "emissive_intensity".into(),
|
||||
display_name: "Emissive Intensity".into(),
|
||||
group: "surface_inputs".into(),
|
||||
order: 60,
|
||||
property_type: ShaderPropertyType::Float {
|
||||
min: Some(0.0),
|
||||
max: Some(50_000.0),
|
||||
},
|
||||
default_value: Some(MaterialParameterValue::Float(0.0)),
|
||||
texture: None,
|
||||
tooltip: "Emissive luminance multiplier in nits.".into(),
|
||||
advanced: false,
|
||||
presentation: MaterialInputPresentation::Companion {
|
||||
owner: "emissive_color".into(),
|
||||
},
|
||||
},
|
||||
MaterialInputDesc {
|
||||
name: "uv_offset".into(),
|
||||
display_name: "Offset".into(),
|
||||
group: "uv_transform".into(),
|
||||
order: 0,
|
||||
property_type: ShaderPropertyType::Vec2,
|
||||
default_value: Some(MaterialParameterValue::Vec2(Vec2::ZERO)),
|
||||
texture: None,
|
||||
tooltip: "Shared UV translation for every texture on this material.".into(),
|
||||
advanced: false,
|
||||
presentation: MaterialInputPresentation::Row,
|
||||
},
|
||||
MaterialInputDesc {
|
||||
name: "uv_tiling".into(),
|
||||
display_name: "Tiling".into(),
|
||||
group: "uv_transform".into(),
|
||||
order: 10,
|
||||
property_type: ShaderPropertyType::Vec2,
|
||||
default_value: Some(MaterialParameterValue::Vec2(Vec2::ONE)),
|
||||
texture: None,
|
||||
tooltip: "Shared UV scale for every texture on this material.".into(),
|
||||
advanced: false,
|
||||
presentation: MaterialInputPresentation::Row,
|
||||
},
|
||||
];
|
||||
MaterialInputSchema { groups, inputs }
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
use crate::{
|
||||
standard_lit_input_schema, MaterialAlphaMode, MaterialInputPresentation, ShaderPropertyType,
|
||||
};
|
||||
|
||||
#[test]
|
||||
fn material_v2_defaults_to_opaque() {
|
||||
|
||||
@@ -3,58 +3,10 @@
|
||||
use bevy::prelude::*;
|
||||
use serde::{Deserialize, Serialize};
|
||||
|
||||
use crate::{ComponentInstanceId, EditorAssetRef, ShaderRefDesc};
|
||||
|
||||
#[derive(Reflect, Debug, Clone, PartialEq, Serialize, Deserialize)]
|
||||
#[reflect(Default, Debug, PartialEq, Serialize, Deserialize)]
|
||||
#[type_path = "shared::components"]
|
||||
pub enum MaterialParameterValue {
|
||||
Bool(bool),
|
||||
Float(f32),
|
||||
Vec2(Vec2),
|
||||
Vec3(Vec3),
|
||||
Color(ColorDesc),
|
||||
Enum(String),
|
||||
}
|
||||
|
||||
impl Default for MaterialParameterValue {
|
||||
fn default() -> Self {
|
||||
Self::Float(0.0)
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Reflect, Default, Debug, Clone, PartialEq, Serialize, Deserialize)]
|
||||
#[reflect(Default, Debug, PartialEq, Serialize, Deserialize)]
|
||||
#[type_path = "shared::components"]
|
||||
pub struct MaterialParameter {
|
||||
pub name: String,
|
||||
pub value: MaterialParameterValue,
|
||||
}
|
||||
|
||||
/// Channels sampled from a texture binding. Scalar material inputs use one channel while
|
||||
/// color/normal inputs use RGB or RGBA. The default preserves the pre-v2 whole-texture behavior.
|
||||
#[derive(Reflect, Default, Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
|
||||
#[reflect(Default, Debug, PartialEq, Serialize, Deserialize)]
|
||||
#[type_path = "shared::components"]
|
||||
pub enum TextureChannel {
|
||||
R,
|
||||
G,
|
||||
B,
|
||||
A,
|
||||
Rgb,
|
||||
#[default]
|
||||
Rgba,
|
||||
}
|
||||
|
||||
#[derive(Reflect, Default, Debug, Clone, PartialEq, Serialize, Deserialize)]
|
||||
#[reflect(Default, Debug, PartialEq, Serialize, Deserialize)]
|
||||
#[type_path = "shared::components"]
|
||||
pub struct MaterialTextureBinding {
|
||||
pub name: String,
|
||||
pub texture: Option<EditorAssetRef>,
|
||||
#[serde(default)]
|
||||
pub channel: TextureChannel,
|
||||
}
|
||||
use crate::{
|
||||
ColorDesc, ComponentInstanceId, EditorAssetRef, MaterialParameter, MaterialTextureBinding,
|
||||
ShaderRefDesc,
|
||||
};
|
||||
|
||||
/// Per-render-slot material override stored on scene actors.
|
||||
#[derive(Reflect, Default, Debug, Clone, PartialEq, Serialize, Deserialize)]
|
||||
@@ -76,34 +28,6 @@ pub struct MaterialOverride {
|
||||
pub slots: Vec<MaterialSlotOverride>,
|
||||
}
|
||||
|
||||
/// Serializable color description. This avoids coupling saved scenes to any internal color
|
||||
/// representation details.
|
||||
#[derive(Reflect, Debug, Clone, Copy, PartialEq, Serialize, Deserialize)]
|
||||
#[reflect(Default, Debug, Serialize, Deserialize)]
|
||||
#[type_path = "shared::components"]
|
||||
pub struct ColorDesc {
|
||||
pub r: f32,
|
||||
pub g: f32,
|
||||
pub b: f32,
|
||||
pub a: f32,
|
||||
}
|
||||
|
||||
impl ColorDesc {
|
||||
pub const fn srgb(r: f32, g: f32, b: f32) -> Self {
|
||||
Self { r, g, b, a: 1.0 }
|
||||
}
|
||||
|
||||
pub fn to_color(self) -> Color {
|
||||
Color::srgba(self.r, self.g, self.b, self.a)
|
||||
}
|
||||
}
|
||||
|
||||
impl Default for ColorDesc {
|
||||
fn default() -> Self {
|
||||
Self::srgb(0.8, 0.8, 0.8)
|
||||
}
|
||||
}
|
||||
|
||||
/// Resolved runtime and legacy-compatible material representation. Project authoring uses
|
||||
/// `MaterialAsset`/`MaterialInputSet`; hydration maps this descriptor to renderer materials.
|
||||
#[derive(Component, Reflect, Debug, Clone, PartialEq, Serialize, Deserialize)]
|
||||
|
||||
@@ -0,0 +1,16 @@
|
||||
[package]
|
||||
name = "ui_gallery"
|
||||
version.workspace = true
|
||||
edition.workspace = true
|
||||
license.workspace = true
|
||||
description = "Focused Blacksite editor UI gallery and Penpot comparison harness"
|
||||
|
||||
[dependencies]
|
||||
eframe.workspace = true
|
||||
editor_ui.workspace = true
|
||||
egui.workspace = true
|
||||
egui_phosphor_icons.workspace = true
|
||||
image = { version = "0.25", default-features = false, features = ["png"] }
|
||||
material_schema.workspace = true
|
||||
serde.workspace = true
|
||||
serde_json = "1"
|
||||
@@ -0,0 +1,10 @@
|
||||
{
|
||||
"material_label": "M_Wood_Planks",
|
||||
"material_path": "materials/wood/M_Wood_Planks.mat",
|
||||
"metallic": 0.72,
|
||||
"roughness": 0.72,
|
||||
"occlusion": 0.72,
|
||||
"normal_strength": 0.72,
|
||||
"emissive_intensity": 0.0,
|
||||
"uv_tiling": [1.0, 1.0]
|
||||
}
|
||||
@@ -0,0 +1,16 @@
|
||||
{
|
||||
"accent": "#E5A433",
|
||||
"selection": "#41C6CF",
|
||||
"panel": "#0D0F12",
|
||||
"panel_dark": "#090B0D",
|
||||
"widget": "#15181C",
|
||||
"elevated": "#1F2328",
|
||||
"text": "#DCE1E5",
|
||||
"text_dim": "#9BA3AB",
|
||||
"text_muted": "#606972",
|
||||
"border": "#262B31",
|
||||
"border_strong": "#40474F",
|
||||
"success": "#54BE7F",
|
||||
"warning": "#EBB448",
|
||||
"error": "#E25E5E"
|
||||
}
|
||||
@@ -0,0 +1,818 @@
|
||||
use std::path::PathBuf;
|
||||
|
||||
use editor_ui::inspector::{ComponentCardOptions, ComponentCardViewModel};
|
||||
use editor_ui::materials::{
|
||||
material_input_schema_editor, material_slot_panel, material_surface_options_ui,
|
||||
materials_section, MaterialHealth, MaterialSlotAction, MaterialThumbnailPresentation,
|
||||
MaterialsSectionViewModel,
|
||||
};
|
||||
use editor_ui::renderer::{
|
||||
renderer_array_header, renderer_material_slot_row, renderer_material_slots_header,
|
||||
renderer_panel, renderer_panel_header, renderer_properties_header,
|
||||
RendererPanelHeaderViewModel,
|
||||
};
|
||||
use egui_phosphor_icons::icons;
|
||||
use material_schema::{standard_lit_input_schema, MaterialShaderKind};
|
||||
|
||||
use crate::fixtures::{FixtureId, FixtureModel};
|
||||
use crate::reference::{
|
||||
difference_image, ComparisonMode, DifferenceStats, GalleryPreset, ReferenceImage,
|
||||
};
|
||||
use crate::reload::RuntimeDocuments;
|
||||
|
||||
pub struct UiGalleryApp {
|
||||
preset: GalleryPreset,
|
||||
comparison: ComparisonMode,
|
||||
overlay_opacity: f32,
|
||||
fixture_id: FixtureId,
|
||||
fixture: FixtureModel,
|
||||
fixture_textures: Vec<egui::TextureHandle>,
|
||||
documents: RuntimeDocuments,
|
||||
references: Vec<(GalleryPreset, ReferenceImage)>,
|
||||
reference_error: Option<String>,
|
||||
last_live_rect: Option<egui::Rect>,
|
||||
last_reference_rect: Option<egui::Rect>,
|
||||
difference_texture: Option<egui::TextureHandle>,
|
||||
difference_stats: Option<DifferenceStats>,
|
||||
difference_dirty: bool,
|
||||
capture: Option<CaptureRequest>,
|
||||
renderer_open: [bool; 3],
|
||||
}
|
||||
|
||||
#[derive(Clone, Copy)]
|
||||
struct CaptureRequest {
|
||||
preset: GalleryPreset,
|
||||
live_rect: egui::Rect,
|
||||
reference_rect: egui::Rect,
|
||||
pixels_per_point: f32,
|
||||
}
|
||||
|
||||
impl UiGalleryApp {
|
||||
pub fn new(creation: &eframe::CreationContext<'_>) -> Self {
|
||||
creation
|
||||
.egui_ctx
|
||||
.set_fonts(editor_ui::fonts::font_definitions());
|
||||
editor_ui::theme::apply_editor_theme(&creation.egui_ctx);
|
||||
let root = PathBuf::from(env!("CARGO_MANIFEST_DIR"))
|
||||
.join("../..")
|
||||
.canonicalize()
|
||||
.unwrap_or_else(|_| PathBuf::from(env!("CARGO_MANIFEST_DIR")).join("../.."));
|
||||
let mut documents = RuntimeDocuments::new(&root);
|
||||
documents.poll(0.0);
|
||||
if let Ok(palette) = documents.theme_value.palette() {
|
||||
editor_ui::theme::apply_editor_theme_with_palette(&creation.egui_ctx, palette);
|
||||
}
|
||||
let fixture_textures = make_fixture_textures(&creation.egui_ctx);
|
||||
let (material_thumbnail, texture_thumbnails) = fixture_thumbnail_ids(&fixture_textures);
|
||||
let fixture_id = FixtureId::Reference;
|
||||
let fixture = FixtureModel::new(
|
||||
fixture_id,
|
||||
&documents.fixture_value,
|
||||
material_thumbnail,
|
||||
texture_thumbnails,
|
||||
);
|
||||
let mut references = Vec::new();
|
||||
let mut reference_error = None;
|
||||
for preset in GalleryPreset::ALL {
|
||||
match ReferenceImage::load(&creation.egui_ctx, &root, preset) {
|
||||
Ok(reference) => references.push((preset, reference)),
|
||||
Err(error) => reference_error = Some(error),
|
||||
}
|
||||
}
|
||||
Self {
|
||||
preset: GalleryPreset::Materials620,
|
||||
comparison: ComparisonMode::SideBySide,
|
||||
overlay_opacity: 0.5,
|
||||
fixture_id,
|
||||
fixture,
|
||||
fixture_textures,
|
||||
documents,
|
||||
references,
|
||||
reference_error,
|
||||
last_live_rect: None,
|
||||
last_reference_rect: None,
|
||||
difference_texture: None,
|
||||
difference_stats: None,
|
||||
difference_dirty: true,
|
||||
capture: None,
|
||||
renderer_open: [true, false, false],
|
||||
}
|
||||
}
|
||||
|
||||
fn rebuild_fixture(&mut self, ctx: &egui::Context) {
|
||||
let (material_thumbnail, texture_thumbnails) =
|
||||
fixture_thumbnail_ids(&self.fixture_textures);
|
||||
self.fixture = FixtureModel::new(
|
||||
self.fixture_id,
|
||||
&self.documents.fixture_value,
|
||||
material_thumbnail,
|
||||
texture_thumbnails,
|
||||
);
|
||||
ctx.request_repaint();
|
||||
self.difference_dirty = true;
|
||||
}
|
||||
|
||||
fn select_preset(&mut self, ctx: &egui::Context, preset: GalleryPreset) {
|
||||
if self.preset == preset {
|
||||
return;
|
||||
}
|
||||
self.preset = preset;
|
||||
if preset.is_renderer() && !self.fixture_id.is_renderer() {
|
||||
self.fixture_id = FixtureId::StaticMesh;
|
||||
self.rebuild_fixture(ctx);
|
||||
}
|
||||
self.difference_dirty = true;
|
||||
}
|
||||
|
||||
fn select_fixture(&mut self, ctx: &egui::Context, fixture: FixtureId) {
|
||||
if self.fixture_id == fixture {
|
||||
return;
|
||||
}
|
||||
self.fixture_id = fixture;
|
||||
self.rebuild_fixture(ctx);
|
||||
}
|
||||
|
||||
fn select_comparison(&mut self, comparison: ComparisonMode) {
|
||||
if self.comparison == comparison {
|
||||
return;
|
||||
}
|
||||
self.comparison = comparison;
|
||||
self.difference_dirty = true;
|
||||
}
|
||||
|
||||
fn handle_shortcuts(&mut self, ctx: &egui::Context) {
|
||||
let (function_key, shift, previous_fixture, next_fixture) = ctx.input(|input| {
|
||||
let function_key = [egui::Key::F1, egui::Key::F2, egui::Key::F3, egui::Key::F4]
|
||||
.into_iter()
|
||||
.position(|key| input.key_pressed(key));
|
||||
(
|
||||
function_key,
|
||||
input.modifiers.shift,
|
||||
input.key_pressed(egui::Key::PageUp),
|
||||
input.key_pressed(egui::Key::PageDown),
|
||||
)
|
||||
});
|
||||
if let Some(index) = function_key {
|
||||
if shift {
|
||||
self.select_comparison(ComparisonMode::ALL[index]);
|
||||
} else {
|
||||
self.select_preset(ctx, GalleryPreset::ALL[index]);
|
||||
}
|
||||
}
|
||||
if previous_fixture || next_fixture {
|
||||
let current = FixtureId::ALL
|
||||
.iter()
|
||||
.position(|fixture| *fixture == self.fixture_id)
|
||||
.unwrap_or_default();
|
||||
let next = if previous_fixture {
|
||||
current.checked_sub(1).unwrap_or(FixtureId::ALL.len() - 1)
|
||||
} else {
|
||||
(current + 1) % FixtureId::ALL.len()
|
||||
};
|
||||
self.select_fixture(ctx, FixtureId::ALL[next]);
|
||||
}
|
||||
}
|
||||
|
||||
fn reference(&self) -> Option<&ReferenceImage> {
|
||||
self.references
|
||||
.iter()
|
||||
.find_map(|(preset, image)| (*preset == self.preset).then_some(image))
|
||||
}
|
||||
|
||||
fn handle_screenshot_events(&mut self, ctx: &egui::Context) {
|
||||
let screenshots = ctx.input(|input| {
|
||||
input
|
||||
.raw
|
||||
.events
|
||||
.iter()
|
||||
.filter_map(|event| match event {
|
||||
egui::Event::Screenshot { image, .. } => Some(image.clone()),
|
||||
_ => None,
|
||||
})
|
||||
.collect::<Vec<_>>()
|
||||
});
|
||||
let Some(request) = self.capture.take() else {
|
||||
return;
|
||||
};
|
||||
let Some(screenshot) = screenshots.last() else {
|
||||
self.capture = Some(request);
|
||||
return;
|
||||
};
|
||||
let (difference, stats) = difference_image(
|
||||
screenshot,
|
||||
request.live_rect,
|
||||
request.reference_rect,
|
||||
request.pixels_per_point,
|
||||
request.preset,
|
||||
);
|
||||
if let Some(texture) = &mut self.difference_texture {
|
||||
texture.set(difference, egui::TextureOptions::NEAREST);
|
||||
} else {
|
||||
self.difference_texture = Some(ctx.load_texture(
|
||||
"blacksite-ui-gallery-difference",
|
||||
difference,
|
||||
egui::TextureOptions::NEAREST,
|
||||
));
|
||||
}
|
||||
self.difference_stats = Some(stats);
|
||||
self.difference_dirty = false;
|
||||
}
|
||||
|
||||
fn toolbar(&mut self, ctx: &egui::Context, ui: &mut egui::Ui) {
|
||||
ui.horizontal_wrapped(|ui| {
|
||||
ui.strong("Blacksite UI Gallery");
|
||||
ui.separator();
|
||||
egui::ComboBox::from_id_salt("gallery_preset")
|
||||
.selected_text(self.preset.label())
|
||||
.show_ui(ui, |ui| {
|
||||
for preset in GalleryPreset::ALL {
|
||||
let selected = self.preset == preset;
|
||||
if ui.selectable_label(selected, preset.label()).clicked() {
|
||||
self.select_preset(ctx, preset);
|
||||
}
|
||||
}
|
||||
});
|
||||
egui::ComboBox::from_id_salt("gallery_fixture")
|
||||
.selected_text(self.fixture_id.label())
|
||||
.show_ui(ui, |ui| {
|
||||
for fixture in FixtureId::ALL {
|
||||
let selected = self.fixture_id == fixture;
|
||||
if ui.selectable_label(selected, fixture.label()).clicked() {
|
||||
self.select_fixture(ctx, fixture);
|
||||
}
|
||||
}
|
||||
});
|
||||
for mode in ComparisonMode::ALL {
|
||||
let selected = self.comparison == mode;
|
||||
if ui.selectable_label(selected, mode.label()).clicked() {
|
||||
self.select_comparison(mode);
|
||||
}
|
||||
}
|
||||
if self.comparison == ComparisonMode::Overlay {
|
||||
ui.add(
|
||||
egui::Slider::new(&mut self.overlay_opacity, 0.0..=1.0)
|
||||
.text("Reference opacity")
|
||||
.show_value(false),
|
||||
);
|
||||
}
|
||||
if self.comparison == ComparisonMode::Difference
|
||||
&& ui.button("Refresh difference").clicked()
|
||||
{
|
||||
self.difference_dirty = true;
|
||||
}
|
||||
});
|
||||
ui.horizontal_wrapped(|ui| {
|
||||
ui.small(format!(
|
||||
"Canvas: {} px · reference: {}",
|
||||
self.preset.width() as u32,
|
||||
self.preset.file_name()
|
||||
));
|
||||
ui.separator();
|
||||
ui.small("Theme and fixture JSON reload without rebuilding");
|
||||
ui.separator();
|
||||
ui.small("F1–F4 presets · Shift+F1–F4 modes · PgUp/PgDn fixtures");
|
||||
if let Some(stats) = self.difference_stats {
|
||||
ui.separator();
|
||||
ui.small(format!(
|
||||
"Δ mean {:.2} · max {} · {:.1}% pixels > 8",
|
||||
stats.mean_channel_delta, stats.max_channel_delta, stats.changed_percent
|
||||
));
|
||||
}
|
||||
if let Some(error) = self
|
||||
.documents
|
||||
.error
|
||||
.as_deref()
|
||||
.or(self.reference_error.as_deref())
|
||||
{
|
||||
ui.colored_label(editor_ui::theme::ERROR, error);
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
fn render_comparison(&mut self, ui: &mut egui::Ui) {
|
||||
let preset = self.preset;
|
||||
match self.comparison {
|
||||
ComparisonMode::Live => {
|
||||
self.last_live_rect = Some(self.render_live_canvas(ui));
|
||||
}
|
||||
ComparisonMode::SideBySide => {
|
||||
ui.horizontal_top(|ui| {
|
||||
ui.vertical(|ui| {
|
||||
ui.strong("Penpot reference");
|
||||
if let Some(reference) = self.reference() {
|
||||
reference.paint(ui, preset, 1.0);
|
||||
}
|
||||
});
|
||||
ui.add_space(16.0);
|
||||
ui.vertical(|ui| {
|
||||
ui.strong("Production component");
|
||||
self.last_live_rect = Some(self.render_live_canvas(ui));
|
||||
});
|
||||
});
|
||||
}
|
||||
ComparisonMode::Overlay => {
|
||||
self.last_live_rect = Some(self.render_live_canvas(ui));
|
||||
if let (Some(rect), Some(reference)) = (self.last_live_rect, self.reference()) {
|
||||
let mut overlay_ui = ui.new_child(
|
||||
egui::UiBuilder::new()
|
||||
.max_rect(rect)
|
||||
.layout(egui::Layout::top_down(egui::Align::Min)),
|
||||
);
|
||||
reference.paint(&mut overlay_ui, preset, self.overlay_opacity);
|
||||
}
|
||||
}
|
||||
ComparisonMode::Difference => {
|
||||
ui.horizontal_top(|ui| {
|
||||
self.last_live_rect = Some(self.render_live_canvas(ui));
|
||||
ui.add_space(16.0);
|
||||
if self.difference_dirty || self.capture.is_some() {
|
||||
self.last_reference_rect = self
|
||||
.reference()
|
||||
.map(|reference| reference.paint(ui, preset, 1.0).rect);
|
||||
} else if let Some(texture) = &self.difference_texture {
|
||||
self.last_reference_rect = None;
|
||||
ui.image((
|
||||
texture.id(),
|
||||
egui::vec2(preset.width(), preset.target_height()),
|
||||
));
|
||||
} else {
|
||||
ui.allocate_ui(egui::vec2(preset.width(), preset.target_height()), |ui| {
|
||||
ui.centered_and_justified(|ui| {
|
||||
ui.label("Difference capture pending…");
|
||||
});
|
||||
});
|
||||
}
|
||||
});
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fn render_live_canvas(&mut self, ui: &mut egui::Ui) -> egui::Rect {
|
||||
let size = egui::vec2(self.preset.width(), self.preset.target_height());
|
||||
let (rect, _) = ui.allocate_exact_size(size, egui::Sense::hover());
|
||||
let palette = editor_ui::design_system::palette(ui);
|
||||
let (canvas_fill, canvas_radius) = if self.preset.is_renderer() {
|
||||
(palette.recessed, 4.0)
|
||||
} else {
|
||||
(palette.panel, 7.0)
|
||||
};
|
||||
ui.painter().rect(
|
||||
rect,
|
||||
canvas_radius,
|
||||
canvas_fill,
|
||||
egui::Stroke::new(1.0_f32, palette.border_strong),
|
||||
egui::StrokeKind::Inside,
|
||||
);
|
||||
// Penpot material boards are complete Inspector canvases, while renderer boards include a
|
||||
// authored top inset before the component card. The preset owns both cases.
|
||||
let content_rect = self.preset.content_rect(rect);
|
||||
let mut child = ui.new_child(
|
||||
egui::UiBuilder::new()
|
||||
.max_rect(content_rect)
|
||||
.layout(egui::Layout::top_down(egui::Align::Min)),
|
||||
);
|
||||
child.set_clip_rect(rect.intersect(ui.clip_rect()));
|
||||
let previous_inputs = self.fixture.inputs.clone();
|
||||
let previous_renderer_inputs = self
|
||||
.fixture
|
||||
.renderer_slots
|
||||
.iter()
|
||||
.map(|fixture| fixture.inputs.clone())
|
||||
.collect::<Vec<_>>();
|
||||
if self.preset.is_renderer() {
|
||||
self.render_renderer_fixture(&mut child);
|
||||
} else {
|
||||
self.render_material_fixture(&mut child);
|
||||
}
|
||||
if previous_inputs != self.fixture.inputs
|
||||
|| previous_renderer_inputs
|
||||
!= self
|
||||
.fixture
|
||||
.renderer_slots
|
||||
.iter()
|
||||
.map(|fixture| fixture.inputs.clone())
|
||||
.collect::<Vec<_>>()
|
||||
{
|
||||
self.difference_dirty = true;
|
||||
}
|
||||
rect
|
||||
}
|
||||
|
||||
fn render_renderer_fixture(&mut self, ui: &mut egui::Ui) {
|
||||
let title = if self.fixture_id == FixtureId::SkinnedMesh {
|
||||
"Skinned Mesh Renderer"
|
||||
} else {
|
||||
"Static Mesh Renderer"
|
||||
};
|
||||
let component = ComponentCardViewModel {
|
||||
options: ComponentCardOptions {
|
||||
type_name: "gallery::Renderer",
|
||||
title,
|
||||
icon: icons::CUBE,
|
||||
active_toggle: true,
|
||||
removable: true,
|
||||
reorderable: true,
|
||||
resettable: true,
|
||||
copyable: true,
|
||||
summary: "3 renderers · 5 material slots",
|
||||
body_margin: 0,
|
||||
},
|
||||
active: true,
|
||||
collapsed: false,
|
||||
pasteable: false,
|
||||
can_move_up: false,
|
||||
can_move_down: true,
|
||||
};
|
||||
editor_ui::inspector::component_card(ui, &component, |ui| {
|
||||
let _ = renderer_array_header(ui, self.renderer_open.len());
|
||||
ui.add_space(26.0);
|
||||
for renderer_index in 0..self.renderer_open.len() {
|
||||
let renderer_label = match renderer_index {
|
||||
0 => "metal_office_desk / Primitive 0",
|
||||
1 => "metal_office_desk_drawer_06 / Primitive 0",
|
||||
_ => "metal_office_desk_tray_01 / Primitive 0",
|
||||
};
|
||||
renderer_panel(ui, |ui| {
|
||||
renderer_panel_header(
|
||||
ui,
|
||||
RendererPanelHeaderViewModel {
|
||||
index: renderer_index,
|
||||
label: renderer_label,
|
||||
path: "draw:scene0:node2:mesh2:primitive0",
|
||||
slot_count: if renderer_index == 0 { 3 } else { 1 },
|
||||
texture_id: None,
|
||||
},
|
||||
&mut self.renderer_open[renderer_index],
|
||||
|ui| {
|
||||
editor_ui::design_system::controls::icon_button(
|
||||
ui,
|
||||
icons::DOTS_THREE_VERTICAL,
|
||||
"Renderer actions",
|
||||
true,
|
||||
);
|
||||
editor_ui::design_system::controls::icon_button(
|
||||
ui,
|
||||
icons::X,
|
||||
"Remove renderer",
|
||||
true,
|
||||
);
|
||||
editor_ui::design_system::controls::icon_button(
|
||||
ui,
|
||||
icons::CROSSHAIR,
|
||||
"Locate mesh",
|
||||
true,
|
||||
);
|
||||
editor_ui::design_system::controls::icon_button(
|
||||
ui,
|
||||
icons::FOLDER_OPEN,
|
||||
"Browse mesh",
|
||||
true,
|
||||
);
|
||||
},
|
||||
);
|
||||
if !self.renderer_open[renderer_index] {
|
||||
return;
|
||||
}
|
||||
renderer_properties_fixture(ui, renderer_label);
|
||||
let slot_count = if renderer_index == 0 { 3 } else { 1 };
|
||||
renderer_material_slots_header(ui, slot_count);
|
||||
if renderer_index == 0 {
|
||||
for slot_index in 0..self.fixture.renderer_slots.len() {
|
||||
renderer_material_slot_row(ui, slot_index, |ui| {
|
||||
self.render_renderer_material_slot(ui, slot_index);
|
||||
});
|
||||
}
|
||||
}
|
||||
});
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
fn render_material_fixture(&mut self, ui: &mut egui::Ui) {
|
||||
let section = MaterialsSectionViewModel {
|
||||
slot_ids: vec![self.fixture.slot.slot_id.clone()],
|
||||
};
|
||||
materials_section(ui, §ion, |ui| {
|
||||
let slot = &mut self.fixture.slot;
|
||||
let render_state = &mut self.fixture.render_state;
|
||||
let inputs = &mut self.fixture.inputs;
|
||||
let textures = &self.fixture.textures;
|
||||
let response = material_slot_panel(
|
||||
ui,
|
||||
("gallery-slot", &slot.slot_id),
|
||||
slot,
|
||||
|ui| {
|
||||
material_surface_options_ui(ui, render_state, Some(inputs));
|
||||
ui.add_space(4.0);
|
||||
material_input_schema_editor(
|
||||
ui,
|
||||
&standard_lit_input_schema(),
|
||||
inputs,
|
||||
textures,
|
||||
None,
|
||||
);
|
||||
},
|
||||
|ui| {
|
||||
ui.label(format!("Stable slot: {}", slot.slot_id));
|
||||
ui.label("Gallery fixture — no project state is loaded");
|
||||
},
|
||||
);
|
||||
for action in response.actions {
|
||||
apply_slot_action(slot, action.action);
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
fn render_renderer_material_slot(&mut self, ui: &mut egui::Ui, slot_index: usize) {
|
||||
let preset_label = self.preset.label();
|
||||
let fixture = &mut self.fixture.renderer_slots[slot_index];
|
||||
let slot_id = fixture.slot.slot_id.clone();
|
||||
fixture.slot.expanded_header_when_parameters_closed = true;
|
||||
fixture.slot.parameters_initially_open =
|
||||
slot_index == 0 && self.preset == GalleryPreset::Renderer760;
|
||||
let textures = &self.fixture.textures;
|
||||
ui.push_id(
|
||||
(
|
||||
"gallery-renderer-slot-scope",
|
||||
preset_label,
|
||||
slot_id.as_str(),
|
||||
),
|
||||
|ui| {
|
||||
let response = material_slot_panel(
|
||||
ui,
|
||||
"material-panel",
|
||||
&fixture.slot,
|
||||
|ui| {
|
||||
material_surface_options_ui(
|
||||
ui,
|
||||
&mut fixture.render_state,
|
||||
Some(&mut fixture.inputs),
|
||||
);
|
||||
ui.add_space(4.0);
|
||||
material_input_schema_editor(
|
||||
ui,
|
||||
&standard_lit_input_schema(),
|
||||
&mut fixture.inputs,
|
||||
textures,
|
||||
None,
|
||||
);
|
||||
},
|
||||
|ui| {
|
||||
ui.label(format!("Stable slot: {}", fixture.slot.slot_id));
|
||||
ui.label("Gallery renderer fixture — no project state is loaded");
|
||||
},
|
||||
);
|
||||
for action in response.actions {
|
||||
apply_slot_action(&mut fixture.slot, action.action);
|
||||
}
|
||||
},
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
impl eframe::App for UiGalleryApp {
|
||||
fn logic(&mut self, ctx: &egui::Context, _frame: &mut eframe::Frame) {
|
||||
self.handle_screenshot_events(ctx);
|
||||
self.handle_shortcuts(ctx);
|
||||
let now = ctx.input(|input| input.time);
|
||||
if self.documents.poll(now) {
|
||||
if let Ok(palette) = self.documents.theme_value.palette() {
|
||||
editor_ui::theme::apply_editor_theme_with_palette(ctx, palette);
|
||||
}
|
||||
self.rebuild_fixture(ctx);
|
||||
}
|
||||
ctx.request_repaint_after(std::time::Duration::from_millis(250));
|
||||
}
|
||||
|
||||
fn ui(&mut self, root: &mut egui::Ui, _frame: &mut eframe::Frame) {
|
||||
let ctx = root.ctx().clone();
|
||||
egui::CentralPanel::default().show_inside(root, |ui| {
|
||||
self.toolbar(&ctx, ui);
|
||||
ui.separator();
|
||||
egui::ScrollArea::both()
|
||||
.id_salt("gallery_canvas_scroll")
|
||||
.auto_shrink([false, false])
|
||||
.show(ui, |ui| self.render_comparison(ui));
|
||||
if self.comparison == ComparisonMode::Difference
|
||||
&& self.difference_dirty
|
||||
&& self.capture.is_none()
|
||||
{
|
||||
if let (Some(live_rect), Some(reference_rect)) =
|
||||
(self.last_live_rect, self.last_reference_rect)
|
||||
{
|
||||
self.capture = Some(CaptureRequest {
|
||||
preset: self.preset,
|
||||
live_rect,
|
||||
reference_rect,
|
||||
pixels_per_point: ctx.pixels_per_point(),
|
||||
});
|
||||
ctx.send_viewport_cmd(egui::ViewportCommand::Screenshot(egui::UserData::new(
|
||||
"blacksite-ui-gallery-difference",
|
||||
)));
|
||||
}
|
||||
}
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
fn renderer_properties_fixture(ui: &mut egui::Ui, name: &str) {
|
||||
let palette = editor_ui::design_system::palette(ui);
|
||||
let mut name_buffer = name.to_owned();
|
||||
egui::Frame::new()
|
||||
.inner_margin(egui::Margin::symmetric(12, 10))
|
||||
.show(ui, |ui| {
|
||||
renderer_properties_header(ui);
|
||||
ui.add_space(2.0);
|
||||
property_fixture_row(ui, "Name", |ui| {
|
||||
ui.add_sized(
|
||||
[ui.available_width().max(1.0), 24.0],
|
||||
egui::TextEdit::singleline(&mut name_buffer),
|
||||
);
|
||||
});
|
||||
ui.add_space(4.0);
|
||||
property_fixture_row(ui, "Mesh", |ui| {
|
||||
let field = ui.available_rect_before_wrap();
|
||||
let field =
|
||||
egui::Rect::from_min_size(field.min, egui::vec2(field.width().max(1.0), 38.0));
|
||||
ui.allocate_rect(field, egui::Sense::hover());
|
||||
ui.painter().rect(
|
||||
field,
|
||||
4.0,
|
||||
palette.control,
|
||||
egui::Stroke::new(1.0_f32, palette.border),
|
||||
egui::StrokeKind::Inside,
|
||||
);
|
||||
ui.painter().text(
|
||||
field.left_center() + egui::vec2(10.0, -7.0),
|
||||
egui::Align2::LEFT_CENTER,
|
||||
name,
|
||||
editor_ui::design_system::typography::TypeRole::Body.font(),
|
||||
palette.text_primary,
|
||||
);
|
||||
ui.painter().text(
|
||||
field.left_center() + egui::vec2(10.0, 8.0),
|
||||
egui::Align2::LEFT_CENTER,
|
||||
"assets/Furniture/Office/metal_office_desk.mesh",
|
||||
editor_ui::design_system::typography::TypeRole::Small.font(),
|
||||
palette.text_muted,
|
||||
);
|
||||
});
|
||||
ui.add_space(4.0);
|
||||
property_fixture_row(ui, "Flags", |ui| {
|
||||
let mut visible = true;
|
||||
let mut cast_shadows = true;
|
||||
let mut receive_shadows = true;
|
||||
ui.horizontal_wrapped(|ui| {
|
||||
ui.checkbox(&mut visible, "Visible");
|
||||
ui.checkbox(&mut cast_shadows, "Cast shadows");
|
||||
ui.checkbox(&mut receive_shadows, "Receive shadows");
|
||||
});
|
||||
});
|
||||
ui.add_space(4.0);
|
||||
});
|
||||
}
|
||||
|
||||
fn property_fixture_row(ui: &mut egui::Ui, label: &str, add_value: impl FnOnce(&mut egui::Ui)) {
|
||||
ui.horizontal_top(|ui| {
|
||||
ui.allocate_ui_with_layout(
|
||||
egui::vec2(72.0, 28.0),
|
||||
egui::Layout::left_to_right(egui::Align::Center),
|
||||
|ui| {
|
||||
ui.label(label);
|
||||
},
|
||||
);
|
||||
ui.vertical(add_value);
|
||||
});
|
||||
}
|
||||
|
||||
fn apply_slot_action(
|
||||
slot: &mut editor_ui::materials::MaterialSlotPanelViewModel,
|
||||
action: MaterialSlotAction,
|
||||
) {
|
||||
match action {
|
||||
MaterialSlotAction::Assign { reference, .. } => {
|
||||
slot.label = reference.label.clone();
|
||||
slot.path = reference.source_path.clone();
|
||||
slot.assigned = Some(reference);
|
||||
slot.health = MaterialHealth::Dirty;
|
||||
}
|
||||
MaterialSlotAction::Clear => {
|
||||
slot.assigned = None;
|
||||
slot.health = MaterialHealth::Dirty;
|
||||
}
|
||||
MaterialSlotAction::SetShader(kind) => {
|
||||
slot.shader_kind = Some(kind);
|
||||
slot.shader = match kind {
|
||||
MaterialShaderKind::StandardLit => "Standard Lit",
|
||||
MaterialShaderKind::Unlit => "Unlit",
|
||||
MaterialShaderKind::Custom => "Custom Surface",
|
||||
}
|
||||
.to_owned();
|
||||
slot.health = MaterialHealth::Dirty;
|
||||
}
|
||||
MaterialSlotAction::BrowseLibrary
|
||||
| MaterialSlotAction::Locate
|
||||
| MaterialSlotAction::ExtractEditable
|
||||
| MaterialSlotAction::CreateInstance => {}
|
||||
}
|
||||
}
|
||||
|
||||
fn make_fixture_textures(ctx: &egui::Context) -> Vec<egui::TextureHandle> {
|
||||
let mut handles = vec![make_material_thumbnail(ctx)];
|
||||
handles.extend([
|
||||
checker_thumbnail(ctx, "gallery-base-color", [126, 100, 74], [87, 69, 51]),
|
||||
checker_thumbnail(ctx, "gallery-orm", [198, 238, 18], [103, 164, 8]),
|
||||
checker_thumbnail(ctx, "gallery-normal", [116, 92, 232], [73, 145, 242]),
|
||||
]);
|
||||
handles
|
||||
}
|
||||
|
||||
fn fixture_thumbnail_ids(
|
||||
handles: &[egui::TextureHandle],
|
||||
) -> (
|
||||
MaterialThumbnailPresentation,
|
||||
[MaterialThumbnailPresentation; 3],
|
||||
) {
|
||||
(
|
||||
MaterialThumbnailPresentation::Ready(handles[0].id()),
|
||||
[
|
||||
MaterialThumbnailPresentation::Ready(handles[1].id()),
|
||||
MaterialThumbnailPresentation::Ready(handles[2].id()),
|
||||
MaterialThumbnailPresentation::Ready(handles[3].id()),
|
||||
],
|
||||
)
|
||||
}
|
||||
|
||||
fn make_material_thumbnail(ctx: &egui::Context) -> egui::TextureHandle {
|
||||
let size = 64;
|
||||
let mut image = egui::ColorImage::new([size, size], vec![egui::Color32::BLACK; size * size]);
|
||||
for y in 0..size {
|
||||
for x in 0..size {
|
||||
image[(x, y)] = if (x / 16 + y / 16) % 2 == 0 {
|
||||
egui::Color32::from_rgb(32, 37, 43)
|
||||
} else {
|
||||
egui::Color32::from_rgb(43, 50, 58)
|
||||
};
|
||||
}
|
||||
}
|
||||
paint_fixture_ellipse(&mut image, [37.0, 42.0], [19.0, 19.0], [17, 22, 27], 0.8);
|
||||
paint_fixture_ellipse(&mut image, [34.0, 38.0], [20.0, 20.0], [109, 123, 138], 1.0);
|
||||
paint_fixture_ellipse(&mut image, [27.0, 28.5], [6.0, 4.5], [199, 211, 221], 0.85);
|
||||
paint_fixture_ellipse(&mut image, [38.0, 42.0], [9.0, 9.0], [63, 74, 86], 1.0);
|
||||
ctx.load_texture(
|
||||
"gallery-material-sphere",
|
||||
image,
|
||||
egui::TextureOptions::NEAREST,
|
||||
)
|
||||
}
|
||||
|
||||
fn paint_fixture_ellipse(
|
||||
image: &mut egui::ColorImage,
|
||||
center: [f32; 2],
|
||||
radius: [f32; 2],
|
||||
color: [u8; 3],
|
||||
opacity: f32,
|
||||
) {
|
||||
for y in 0..image.size[1] {
|
||||
for x in 0..image.size[0] {
|
||||
let dx = (x as f32 + 0.5 - center[0]) / radius[0];
|
||||
let dy = (y as f32 + 0.5 - center[1]) / radius[1];
|
||||
let distance = (dx * dx + dy * dy).sqrt();
|
||||
let coverage = ((1.0 - distance) * radius[0].min(radius[1])).clamp(0.0, 1.0);
|
||||
let alpha = coverage * opacity;
|
||||
if alpha <= 0.0 {
|
||||
continue;
|
||||
}
|
||||
let previous = image[(x, y)];
|
||||
let blend = |source: u8, destination: u8| {
|
||||
(source as f32 * alpha + destination as f32 * (1.0 - alpha)).round() as u8
|
||||
};
|
||||
image[(x, y)] = egui::Color32::from_rgb(
|
||||
blend(color[0], previous.r()),
|
||||
blend(color[1], previous.g()),
|
||||
blend(color[2], previous.b()),
|
||||
);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fn checker_thumbnail(
|
||||
ctx: &egui::Context,
|
||||
name: &str,
|
||||
first: [u8; 3],
|
||||
second: [u8; 3],
|
||||
) -> egui::TextureHandle {
|
||||
let size = 18;
|
||||
let mut image = egui::ColorImage::new([size, size], vec![egui::Color32::BLACK; size * size]);
|
||||
for y in 0..size {
|
||||
for x in 0..size {
|
||||
let color = if (x / 3 + y / 3) % 2 == 0 {
|
||||
first
|
||||
} else {
|
||||
second
|
||||
};
|
||||
image[(x, y)] = egui::Color32::from_rgb(color[0], color[1], color[2]);
|
||||
}
|
||||
}
|
||||
ctx.load_texture(name, image, egui::TextureOptions::NEAREST)
|
||||
}
|
||||
@@ -0,0 +1,457 @@
|
||||
use editor_ui::materials::{
|
||||
MaterialHealth, MaterialLayerBadge, MaterialLocateTarget, MaterialPickerCandidate,
|
||||
MaterialSlotPanelViewModel, MaterialTextureCandidate, MaterialThumbnailPresentation,
|
||||
};
|
||||
use material_schema::{
|
||||
standard_lit_input_schema, ColorDesc, EditorAssetRef, MaterialInputSet, MaterialParameter,
|
||||
MaterialParameterValue, MaterialRenderState, MaterialShaderKind, MaterialTextureBinding,
|
||||
TextureChannel,
|
||||
};
|
||||
use serde::{Deserialize, Serialize};
|
||||
|
||||
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
|
||||
#[serde(rename_all = "snake_case")]
|
||||
pub enum FixtureId {
|
||||
Reference,
|
||||
Primitive,
|
||||
StaticMesh,
|
||||
SkinnedMesh,
|
||||
Inherited,
|
||||
Imported,
|
||||
Dirty,
|
||||
Processing,
|
||||
Failed,
|
||||
ReadOnly,
|
||||
BuiltIn,
|
||||
}
|
||||
|
||||
impl FixtureId {
|
||||
pub const ALL: [Self; 11] = [
|
||||
Self::Reference,
|
||||
Self::Primitive,
|
||||
Self::StaticMesh,
|
||||
Self::SkinnedMesh,
|
||||
Self::Inherited,
|
||||
Self::Imported,
|
||||
Self::Dirty,
|
||||
Self::Processing,
|
||||
Self::Failed,
|
||||
Self::ReadOnly,
|
||||
Self::BuiltIn,
|
||||
];
|
||||
|
||||
pub const fn label(self) -> &'static str {
|
||||
match self {
|
||||
Self::Reference => "Penpot Layout",
|
||||
Self::Primitive => "Primitive",
|
||||
Self::StaticMesh => "Static Mesh",
|
||||
Self::SkinnedMesh => "Skinned Mesh",
|
||||
Self::Inherited => "Inherited",
|
||||
Self::Imported => "Imported Source",
|
||||
Self::Dirty => "Dirty",
|
||||
Self::Processing => "Processing",
|
||||
Self::Failed => "Failed",
|
||||
Self::ReadOnly => "Read only",
|
||||
Self::BuiltIn => "Built-in DefaultGrid",
|
||||
}
|
||||
}
|
||||
|
||||
pub const fn is_renderer(self) -> bool {
|
||||
matches!(self, Self::StaticMesh | Self::SkinnedMesh)
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, Default, Serialize, Deserialize)]
|
||||
#[serde(default)]
|
||||
pub struct FixtureOverrides {
|
||||
pub material_label: Option<String>,
|
||||
pub material_path: Option<String>,
|
||||
pub metallic: Option<f32>,
|
||||
pub roughness: Option<f32>,
|
||||
pub occlusion: Option<f32>,
|
||||
pub normal_strength: Option<f32>,
|
||||
pub emissive_intensity: Option<f32>,
|
||||
pub uv_tiling: Option<[f32; 2]>,
|
||||
}
|
||||
|
||||
pub struct FixtureModel {
|
||||
pub slot: MaterialSlotPanelViewModel,
|
||||
pub render_state: MaterialRenderState,
|
||||
pub inputs: MaterialInputSet,
|
||||
pub renderer_slots: Vec<RendererMaterialFixture>,
|
||||
pub textures: Vec<MaterialTextureCandidate>,
|
||||
}
|
||||
|
||||
pub struct RendererMaterialFixture {
|
||||
pub slot: MaterialSlotPanelViewModel,
|
||||
pub render_state: MaterialRenderState,
|
||||
pub inputs: MaterialInputSet,
|
||||
}
|
||||
|
||||
impl FixtureModel {
|
||||
pub fn new(
|
||||
id: FixtureId,
|
||||
overrides: &FixtureOverrides,
|
||||
material_thumbnail: MaterialThumbnailPresentation,
|
||||
texture_thumbnails: [MaterialThumbnailPresentation; 3],
|
||||
) -> Self {
|
||||
let material_ref = EditorAssetRef::new(
|
||||
"c07a5b05-f27d-46c6-8b8c-9de9cdd1472c",
|
||||
"material:source",
|
||||
"M_Wood_Planks",
|
||||
)
|
||||
.with_source_path("materials/wood/M_Wood_Planks.mat");
|
||||
let label = overrides
|
||||
.material_label
|
||||
.clone()
|
||||
.unwrap_or_else(|| fixture_material_label(id).to_owned());
|
||||
let path = overrides
|
||||
.material_path
|
||||
.clone()
|
||||
.unwrap_or_else(|| fixture_material_path(id).to_owned());
|
||||
let (health, inherited, can_edit_shader, can_clear) = fixture_state(id);
|
||||
let slot = MaterialSlotPanelViewModel {
|
||||
slot_id: fixture_slot_id(id).to_owned(),
|
||||
label,
|
||||
path: Some(path),
|
||||
shader: "Standard Lit".to_owned(),
|
||||
shader_kind: Some(MaterialShaderKind::StandardLit),
|
||||
can_edit_shader,
|
||||
thumbnail: material_thumbnail,
|
||||
inherited,
|
||||
health,
|
||||
assigned: (!matches!(id, FixtureId::Inherited | FixtureId::BuiltIn))
|
||||
.then_some(material_ref.clone()),
|
||||
effective: Some(material_ref),
|
||||
candidates: material_candidates(material_thumbnail),
|
||||
drop_candidate: None,
|
||||
invalid_drop_reason: None,
|
||||
can_locate: !matches!(id, FixtureId::BuiltIn),
|
||||
can_clear,
|
||||
can_extract: matches!(id, FixtureId::Imported),
|
||||
can_create_instance: !matches!(id, FixtureId::Imported | FixtureId::BuiltIn),
|
||||
parameters_initially_open: true,
|
||||
expanded_header_when_parameters_closed: false,
|
||||
};
|
||||
let textures = texture_candidates(texture_thumbnails);
|
||||
let inputs = fixture_inputs(id, overrides, &textures);
|
||||
let renderer_slots = renderer_material_fixtures(&slot, &inputs);
|
||||
Self {
|
||||
slot,
|
||||
render_state: MaterialRenderState::default(),
|
||||
inputs,
|
||||
renderer_slots,
|
||||
textures,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fn renderer_material_fixtures(
|
||||
primary: &MaterialSlotPanelViewModel,
|
||||
inputs: &MaterialInputSet,
|
||||
) -> Vec<RendererMaterialFixture> {
|
||||
let mut painted = primary.clone();
|
||||
painted.slot_id = "slot:draw:scene0:node2:mesh2:primitive1".to_owned();
|
||||
painted.label = "M_Painted_Metal".to_owned();
|
||||
painted.path = Some("assets/materials/office/M_Painted_Metal.mat".to_owned());
|
||||
painted.assigned = painted.assigned.as_ref().map(|_| {
|
||||
EditorAssetRef::new(
|
||||
"gallery-painted-metal",
|
||||
"material:source",
|
||||
"M_Painted_Metal",
|
||||
)
|
||||
.with_source_path("assets/materials/office/M_Painted_Metal.mat")
|
||||
});
|
||||
painted.effective = painted.assigned.clone();
|
||||
painted.parameters_initially_open = false;
|
||||
|
||||
let mut empty = primary.clone();
|
||||
empty.slot_id = "slot:draw:scene0:node2:mesh2:primitive2".to_owned();
|
||||
empty.label = "No material assigned".to_owned();
|
||||
empty.path = None;
|
||||
empty.shader.clear();
|
||||
empty.shader_kind = None;
|
||||
empty.can_edit_shader = false;
|
||||
empty.thumbnail = MaterialThumbnailPresentation::Empty;
|
||||
empty.health = MaterialHealth::Healthy;
|
||||
empty.assigned = None;
|
||||
empty.effective = None;
|
||||
empty.can_locate = false;
|
||||
empty.can_clear = false;
|
||||
empty.can_create_instance = false;
|
||||
empty.parameters_initially_open = false;
|
||||
|
||||
[primary.clone(), painted, empty]
|
||||
.into_iter()
|
||||
.map(|slot| RendererMaterialFixture {
|
||||
slot,
|
||||
render_state: MaterialRenderState::default(),
|
||||
inputs: inputs.clone(),
|
||||
})
|
||||
.collect()
|
||||
}
|
||||
|
||||
fn fixture_state(id: FixtureId) -> (MaterialHealth, Option<MaterialLayerBadge>, bool, bool) {
|
||||
match id {
|
||||
FixtureId::Inherited => (
|
||||
MaterialHealth::Healthy,
|
||||
Some(MaterialLayerBadge::ModelDefault),
|
||||
false,
|
||||
false,
|
||||
),
|
||||
FixtureId::Imported => (
|
||||
MaterialHealth::ReadOnly,
|
||||
Some(MaterialLayerBadge::ModelSource),
|
||||
false,
|
||||
false,
|
||||
),
|
||||
FixtureId::Dirty => (MaterialHealth::Dirty, None, true, true),
|
||||
FixtureId::Processing => (MaterialHealth::Processing, None, true, true),
|
||||
FixtureId::Failed => (MaterialHealth::Broken, None, false, true),
|
||||
FixtureId::ReadOnly => (MaterialHealth::ReadOnly, None, false, false),
|
||||
FixtureId::BuiltIn => (
|
||||
MaterialHealth::ReadOnly,
|
||||
Some(MaterialLayerBadge::DefaultGrid),
|
||||
false,
|
||||
false,
|
||||
),
|
||||
FixtureId::Reference
|
||||
| FixtureId::Primitive
|
||||
| FixtureId::StaticMesh
|
||||
| FixtureId::SkinnedMesh => (MaterialHealth::Healthy, None, true, true),
|
||||
}
|
||||
}
|
||||
|
||||
fn fixture_slot_id(id: FixtureId) -> &'static str {
|
||||
match id {
|
||||
FixtureId::Reference => "slot:gallery:penpot-reference",
|
||||
FixtureId::Primitive => "slot:primitive:surface",
|
||||
FixtureId::StaticMesh => "slot:draw:scene0:node2:mesh2:primitive0",
|
||||
FixtureId::SkinnedMesh => "slot:skin:scene0:node1:mesh0:primitive0",
|
||||
_ => "slot:gallery:surface",
|
||||
}
|
||||
}
|
||||
|
||||
fn fixture_material_label(id: FixtureId) -> &'static str {
|
||||
match id {
|
||||
FixtureId::Imported => "metal_office_desk",
|
||||
FixtureId::BuiltIn => "Default Grid — Engine Built-in",
|
||||
FixtureId::Failed => "Missing explicit material",
|
||||
_ => "M_Wood_Planks",
|
||||
}
|
||||
}
|
||||
|
||||
fn fixture_material_path(id: FixtureId) -> &'static str {
|
||||
match id {
|
||||
FixtureId::Imported => "assets/Furniture/Office/metal_office_desk_2k.gltf#material:0",
|
||||
FixtureId::BuiltIn => "builtin://materials/default-grid",
|
||||
FixtureId::Failed => "assets/materials/missing.material.ron",
|
||||
_ => "materials/wood/M_Wood_Planks.mat",
|
||||
}
|
||||
}
|
||||
|
||||
fn material_candidates(thumbnail: MaterialThumbnailPresentation) -> Vec<MaterialPickerCandidate> {
|
||||
["M_Wood_Planks", "M_Painted_Metal", "M_Concrete"]
|
||||
.into_iter()
|
||||
.enumerate()
|
||||
.map(|(index, label)| MaterialPickerCandidate {
|
||||
reference: EditorAssetRef::new(
|
||||
format!("gallery-material-{index}"),
|
||||
"material:source",
|
||||
label,
|
||||
)
|
||||
.with_source_path(format!("assets/materials/{label}.material.ron")),
|
||||
label: label.to_owned(),
|
||||
detail: format!("assets/materials/{label}.material.ron"),
|
||||
thumbnail,
|
||||
})
|
||||
.collect()
|
||||
}
|
||||
|
||||
fn texture_candidates(
|
||||
thumbnails: [MaterialThumbnailPresentation; 3],
|
||||
) -> Vec<MaterialTextureCandidate> {
|
||||
[
|
||||
("T_Wood_ORM", "materials/textures/T_Wood_ORM.png"),
|
||||
("T_Wood_ORM", "materials/textures/T_Wood_ORM.png"),
|
||||
("T_Wood_ORM", "materials/textures/T_Wood_ORM.png"),
|
||||
]
|
||||
.into_iter()
|
||||
.enumerate()
|
||||
.map(|(index, (label, path))| MaterialTextureCandidate {
|
||||
label: label.to_owned(),
|
||||
detail: path.to_owned(),
|
||||
reference: EditorAssetRef::new(format!("gallery-texture-{index}"), "texture:source", label)
|
||||
.with_source_path(path),
|
||||
locate: MaterialLocateTarget::File(path.to_owned()),
|
||||
thumbnail: thumbnails[index],
|
||||
})
|
||||
.collect()
|
||||
}
|
||||
|
||||
fn fixture_inputs(
|
||||
id: FixtureId,
|
||||
overrides: &FixtureOverrides,
|
||||
textures: &[MaterialTextureCandidate],
|
||||
) -> MaterialInputSet {
|
||||
let schema = standard_lit_input_schema();
|
||||
let mut set = MaterialInputSet::default();
|
||||
for input in &schema.inputs {
|
||||
if let Some(value) = input.default_value.clone() {
|
||||
set.values.push(MaterialParameter {
|
||||
name: input.name.clone(),
|
||||
value,
|
||||
});
|
||||
}
|
||||
if let Some(texture) = input.texture.as_ref() {
|
||||
set.textures.push(MaterialTextureBinding {
|
||||
name: input.name.clone(),
|
||||
texture: None,
|
||||
channel: texture.default_channel,
|
||||
});
|
||||
}
|
||||
}
|
||||
set_value(
|
||||
&mut set,
|
||||
"base_color",
|
||||
MaterialParameterValue::Color(ColorDesc::srgb(231.0 / 255.0, 212.0 / 255.0, 180.0 / 255.0)),
|
||||
);
|
||||
set_value(
|
||||
&mut set,
|
||||
"emissive_color",
|
||||
MaterialParameterValue::Color(ColorDesc::srgb(231.0 / 255.0, 212.0 / 255.0, 180.0 / 255.0)),
|
||||
);
|
||||
set_float(&mut set, "metallic", overrides.metallic.unwrap_or(0.72));
|
||||
set_float(&mut set, "roughness", overrides.roughness.unwrap_or(0.72));
|
||||
set_float(&mut set, "occlusion", overrides.occlusion.unwrap_or(0.72));
|
||||
set_float(
|
||||
&mut set,
|
||||
"normal",
|
||||
overrides.normal_strength.unwrap_or(0.72),
|
||||
);
|
||||
set_float(
|
||||
&mut set,
|
||||
"emissive_intensity",
|
||||
overrides.emissive_intensity.unwrap_or(0.0),
|
||||
);
|
||||
if let Some([x, y]) = overrides.uv_tiling {
|
||||
if let Some(parameter) = set
|
||||
.values
|
||||
.iter_mut()
|
||||
.find(|value| value.name == "uv_tiling")
|
||||
{
|
||||
if let MaterialParameterValue::Vec2(value) = &mut parameter.value {
|
||||
value.x = x;
|
||||
value.y = y;
|
||||
}
|
||||
}
|
||||
}
|
||||
bind(&mut set, "base_color", &textures[0], TextureChannel::Rgba);
|
||||
for (name, channel) in [
|
||||
("occlusion", TextureChannel::R),
|
||||
("roughness", TextureChannel::G),
|
||||
("metallic", TextureChannel::B),
|
||||
] {
|
||||
bind(&mut set, name, &textures[1], channel);
|
||||
}
|
||||
bind(&mut set, "normal", &textures[2], TextureChannel::Rgb);
|
||||
if id == FixtureId::Reference {
|
||||
// Penpot's sample binds the same mock texture to Emissive. Its all-G scalar labels conflict
|
||||
// with the simultaneously selected ORM mode; keep Blacksite's valid R/G/B contract and
|
||||
// document those three sample glyphs as an intentional handoff delta.
|
||||
bind(
|
||||
&mut set,
|
||||
"emissive_color",
|
||||
&textures[1],
|
||||
TextureChannel::Rgb,
|
||||
);
|
||||
}
|
||||
set
|
||||
}
|
||||
|
||||
fn set_float(inputs: &mut MaterialInputSet, name: &str, value: f32) {
|
||||
set_value(inputs, name, MaterialParameterValue::Float(value));
|
||||
}
|
||||
|
||||
fn set_value(inputs: &mut MaterialInputSet, name: &str, value: MaterialParameterValue) {
|
||||
if let Some(parameter) = inputs.values.iter_mut().find(|item| item.name == name) {
|
||||
parameter.value = value;
|
||||
}
|
||||
}
|
||||
|
||||
fn bind(
|
||||
inputs: &mut MaterialInputSet,
|
||||
name: &str,
|
||||
candidate: &MaterialTextureCandidate,
|
||||
channel: TextureChannel,
|
||||
) {
|
||||
if let Some(binding) = inputs.textures.iter_mut().find(|item| item.name == name) {
|
||||
binding.texture = Some(candidate.reference.clone());
|
||||
binding.channel = channel;
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
fn test_textures() -> Vec<MaterialTextureCandidate> {
|
||||
texture_candidates([MaterialThumbnailPresentation::Pending; 3])
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn reference_fixture_keeps_valid_orm_channels_and_adds_penpot_emissive_sample() {
|
||||
let textures = test_textures();
|
||||
let reference = fixture_inputs(
|
||||
FixtureId::Reference,
|
||||
&FixtureOverrides::default(),
|
||||
&textures,
|
||||
);
|
||||
assert_eq!(
|
||||
reference
|
||||
.texture("occlusion")
|
||||
.map(|binding| binding.channel),
|
||||
Some(TextureChannel::R)
|
||||
);
|
||||
assert_eq!(
|
||||
reference
|
||||
.texture("roughness")
|
||||
.map(|binding| binding.channel),
|
||||
Some(TextureChannel::G)
|
||||
);
|
||||
assert_eq!(
|
||||
reference.texture("metallic").map(|binding| binding.channel),
|
||||
Some(TextureChannel::B)
|
||||
);
|
||||
assert!(reference
|
||||
.texture("emissive_color")
|
||||
.and_then(|binding| binding.texture.as_ref())
|
||||
.is_some());
|
||||
|
||||
let primitive = fixture_inputs(
|
||||
FixtureId::Primitive,
|
||||
&FixtureOverrides::default(),
|
||||
&textures,
|
||||
);
|
||||
assert_eq!(
|
||||
primitive
|
||||
.texture("occlusion")
|
||||
.map(|binding| binding.channel),
|
||||
Some(TextureChannel::R)
|
||||
);
|
||||
assert_eq!(
|
||||
primitive
|
||||
.texture("roughness")
|
||||
.map(|binding| binding.channel),
|
||||
Some(TextureChannel::G)
|
||||
);
|
||||
assert_eq!(
|
||||
primitive.texture("metallic").map(|binding| binding.channel),
|
||||
Some(TextureChannel::B)
|
||||
);
|
||||
assert!(primitive
|
||||
.texture("emissive_color")
|
||||
.and_then(|binding| binding.texture.as_ref())
|
||||
.is_none());
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,19 @@
|
||||
mod app;
|
||||
mod fixtures;
|
||||
mod reference;
|
||||
mod reload;
|
||||
|
||||
fn main() -> eframe::Result {
|
||||
let options = eframe::NativeOptions {
|
||||
viewport: egui::ViewportBuilder::default()
|
||||
.with_title("Blacksite UI Gallery")
|
||||
.with_inner_size([1420.0, 940.0])
|
||||
.with_min_inner_size([900.0, 620.0]),
|
||||
..Default::default()
|
||||
};
|
||||
eframe::run_native(
|
||||
"Blacksite UI Gallery",
|
||||
options,
|
||||
Box::new(|creation| Ok(Box::new(app::UiGalleryApp::new(creation)))),
|
||||
)
|
||||
}
|
||||
@@ -0,0 +1,318 @@
|
||||
use std::path::{Path, PathBuf};
|
||||
|
||||
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
|
||||
pub enum GalleryPreset {
|
||||
Materials620,
|
||||
Materials420,
|
||||
Renderer760,
|
||||
Renderer480,
|
||||
}
|
||||
|
||||
impl GalleryPreset {
|
||||
pub const ALL: [Self; 4] = [
|
||||
Self::Materials620,
|
||||
Self::Materials420,
|
||||
Self::Renderer760,
|
||||
Self::Renderer480,
|
||||
];
|
||||
|
||||
pub const fn label(self) -> &'static str {
|
||||
match self {
|
||||
Self::Materials620 => "Materials · 620",
|
||||
Self::Materials420 => "Materials · 420",
|
||||
Self::Renderer760 => "Renderer · 760",
|
||||
Self::Renderer480 => "Renderer · 480",
|
||||
}
|
||||
}
|
||||
|
||||
pub const fn width(self) -> f32 {
|
||||
match self {
|
||||
Self::Materials620 => 620.0,
|
||||
Self::Materials420 => 420.0,
|
||||
Self::Renderer760 => 760.0,
|
||||
Self::Renderer480 => 480.0,
|
||||
}
|
||||
}
|
||||
|
||||
pub const fn target_height(self) -> f32 {
|
||||
match self {
|
||||
Self::Materials620 => 539.0,
|
||||
Self::Materials420 => 735.0,
|
||||
Self::Renderer760 => 1233.0,
|
||||
Self::Renderer480 => 828.0,
|
||||
}
|
||||
}
|
||||
|
||||
pub const fn file_name(self) -> &'static str {
|
||||
match self {
|
||||
Self::Materials620 => "materials-wide-620.png",
|
||||
Self::Materials420 => "materials-narrow-420.png",
|
||||
Self::Renderer760 => "static-mesh-renderer-wide-760.png",
|
||||
Self::Renderer480 => "static-mesh-renderer-narrow-480.png",
|
||||
}
|
||||
}
|
||||
|
||||
pub const fn is_renderer(self) -> bool {
|
||||
matches!(self, Self::Renderer760 | Self::Renderer480)
|
||||
}
|
||||
|
||||
/// Production-content canvas inside the exported Penpot reference.
|
||||
///
|
||||
/// Material boards include the Inspector border and its 12 px horizontal / 10 px top inset;
|
||||
/// renderer boards are already complete component canvases.
|
||||
pub fn content_rect(self, canvas: egui::Rect) -> egui::Rect {
|
||||
if self.is_renderer() {
|
||||
egui::Rect::from_min_max(
|
||||
canvas.min + egui::vec2(0.0, 12.0),
|
||||
egui::pos2(canvas.right(), canvas.bottom()),
|
||||
)
|
||||
} else {
|
||||
egui::Rect::from_min_max(
|
||||
canvas.min + egui::vec2(12.0, 10.0),
|
||||
egui::pos2(canvas.right() - 12.0, canvas.bottom()),
|
||||
)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
|
||||
pub enum ComparisonMode {
|
||||
Live,
|
||||
SideBySide,
|
||||
Overlay,
|
||||
Difference,
|
||||
}
|
||||
|
||||
impl ComparisonMode {
|
||||
pub const ALL: [Self; 4] = [
|
||||
Self::Live,
|
||||
Self::SideBySide,
|
||||
Self::Overlay,
|
||||
Self::Difference,
|
||||
];
|
||||
|
||||
pub const fn label(self) -> &'static str {
|
||||
match self {
|
||||
Self::Live => "Live",
|
||||
Self::SideBySide => "Side by side",
|
||||
Self::Overlay => "Overlay",
|
||||
Self::Difference => "Difference",
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
pub struct ReferenceImage {
|
||||
pub source_size: [usize; 2],
|
||||
pub texture: egui::TextureHandle,
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
|
||||
struct ReferenceCrop {
|
||||
origin: [usize; 2],
|
||||
size: [usize; 2],
|
||||
}
|
||||
|
||||
fn reference_crop(source_size: [usize; 2], preset: GalleryPreset) -> ReferenceCrop {
|
||||
let target_width = preset.width().round().max(1.0) as usize;
|
||||
let target_height = preset.target_height().round().max(1.0) as usize;
|
||||
// Penpot's material exports include the frame's one-pixel outer stroke in their viewBox,
|
||||
// producing 622/422 px PNGs for 620/420 px boards. That stroke is export overscan, not part of
|
||||
// the authored canvas. Cropping it preserves direct 1:1 pixels; scaling it into the canvas
|
||||
// blurs text and introduces a false global geometry delta.
|
||||
let overscan = source_size[0].saturating_sub(target_width);
|
||||
let inset = usize::from(overscan == 2);
|
||||
ReferenceCrop {
|
||||
origin: [inset, inset],
|
||||
size: [
|
||||
target_width.min(source_size[0].saturating_sub(inset)),
|
||||
target_height.min(source_size[1].saturating_sub(inset)),
|
||||
],
|
||||
}
|
||||
}
|
||||
|
||||
impl ReferenceImage {
|
||||
pub fn load(ctx: &egui::Context, root: &Path, preset: GalleryPreset) -> Result<Self, String> {
|
||||
let path = reference_path(root, preset);
|
||||
let bytes = std::fs::read(&path).map_err(|error| format!("{}: {error}", path.display()))?;
|
||||
let decoded = image::load_from_memory(&bytes)
|
||||
.map_err(|error| format!("{}: {error}", path.display()))?
|
||||
.to_rgba8();
|
||||
let source_size = [decoded.width() as usize, decoded.height() as usize];
|
||||
let pixels = egui::ColorImage::from_rgba_unmultiplied(source_size, decoded.as_raw());
|
||||
let texture = ctx.load_texture(
|
||||
format!("penpot-reference-{}", preset.label()),
|
||||
pixels.clone(),
|
||||
egui::TextureOptions::NEAREST,
|
||||
);
|
||||
Ok(Self {
|
||||
source_size,
|
||||
texture,
|
||||
})
|
||||
}
|
||||
|
||||
pub fn paint(&self, ui: &mut egui::Ui, preset: GalleryPreset, opacity: f32) -> egui::Response {
|
||||
let size = egui::vec2(preset.width(), preset.target_height());
|
||||
let crop = reference_crop(self.source_size, preset);
|
||||
let uv_min = egui::pos2(
|
||||
crop.origin[0] as f32 / self.source_size[0] as f32,
|
||||
crop.origin[1] as f32 / self.source_size[1] as f32,
|
||||
);
|
||||
let uv_max = egui::pos2(
|
||||
(crop.origin[0] + crop.size[0]) as f32 / self.source_size[0] as f32,
|
||||
(crop.origin[1] + crop.size[1]) as f32 / self.source_size[1] as f32,
|
||||
);
|
||||
ui.add(
|
||||
egui::Image::new((self.texture.id(), size))
|
||||
.uv(egui::Rect::from_min_max(uv_min, uv_max))
|
||||
.tint(egui::Color32::from_white_alpha((opacity * 255.0) as u8)),
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
pub fn difference_image(
|
||||
screenshot: &egui::ColorImage,
|
||||
live_rect: egui::Rect,
|
||||
reference_rect: egui::Rect,
|
||||
pixels_per_point: f32,
|
||||
preset: GalleryPreset,
|
||||
) -> (egui::ColorImage, DifferenceStats) {
|
||||
let width = preset.width().round().max(1.0) as usize;
|
||||
let height = preset.target_height().round().max(1.0) as usize;
|
||||
let mut output =
|
||||
egui::ColorImage::new([width, height], vec![egui::Color32::BLACK; width * height]);
|
||||
let mut total = 0_u64;
|
||||
let mut max_delta = 0_u8;
|
||||
let mut changed = 0_u64;
|
||||
for y in 0..height {
|
||||
for x in 0..width {
|
||||
let live =
|
||||
sample_screenshot(screenshot, live_rect, pixels_per_point, x, y, width, height);
|
||||
let reference_color = sample_screenshot(
|
||||
screenshot,
|
||||
reference_rect,
|
||||
pixels_per_point,
|
||||
x,
|
||||
y,
|
||||
width,
|
||||
height,
|
||||
);
|
||||
let delta = [
|
||||
live.r().abs_diff(reference_color.r()),
|
||||
live.g().abs_diff(reference_color.g()),
|
||||
live.b().abs_diff(reference_color.b()),
|
||||
];
|
||||
let peak = *delta.iter().max().unwrap_or(&0);
|
||||
max_delta = max_delta.max(peak);
|
||||
total += delta.into_iter().map(u64::from).sum::<u64>();
|
||||
changed += u64::from(peak > 8);
|
||||
let amplified = |value: u8| value.saturating_mul(4);
|
||||
output[(x, y)] = egui::Color32::from_rgb(
|
||||
amplified(delta[0]),
|
||||
amplified(delta[1]),
|
||||
amplified(delta[2]),
|
||||
);
|
||||
}
|
||||
}
|
||||
let samples = (width * height * 3).max(1) as f32;
|
||||
let pixels = (width * height).max(1) as f32;
|
||||
(
|
||||
output,
|
||||
DifferenceStats {
|
||||
mean_channel_delta: total as f32 / samples,
|
||||
max_channel_delta: max_delta,
|
||||
changed_percent: changed as f32 * 100.0 / pixels,
|
||||
},
|
||||
)
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, Copy, Default)]
|
||||
pub struct DifferenceStats {
|
||||
pub mean_channel_delta: f32,
|
||||
pub max_channel_delta: u8,
|
||||
pub changed_percent: f32,
|
||||
}
|
||||
|
||||
fn reference_path(root: &Path, preset: GalleryPreset) -> PathBuf {
|
||||
root.join("docs/editor/evaluations/content-workspace-m2/penpot")
|
||||
.join(preset.file_name())
|
||||
}
|
||||
|
||||
fn sample_screenshot(
|
||||
image: &egui::ColorImage,
|
||||
rect: egui::Rect,
|
||||
pixels_per_point: f32,
|
||||
x: usize,
|
||||
y: usize,
|
||||
width: usize,
|
||||
height: usize,
|
||||
) -> egui::Color32 {
|
||||
let px = ((rect.left() + (x as f32 + 0.5) * rect.width() / width as f32) * pixels_per_point)
|
||||
.floor() as isize;
|
||||
let py = ((rect.top() + (y as f32 + 0.5) * rect.height() / height as f32) * pixels_per_point)
|
||||
.floor() as isize;
|
||||
if px < 0 || py < 0 || px as usize >= image.size[0] || py as usize >= image.size[1] {
|
||||
return egui::Color32::BLACK;
|
||||
}
|
||||
image[(px as usize, py as usize)]
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn material_presets_supply_exported_slot_widths() {
|
||||
for (preset, expected_width) in [
|
||||
(GalleryPreset::Materials620, 596.0),
|
||||
(GalleryPreset::Materials420, 396.0),
|
||||
] {
|
||||
let canvas = egui::Rect::from_min_size(
|
||||
egui::Pos2::ZERO,
|
||||
egui::vec2(preset.width(), preset.target_height()),
|
||||
);
|
||||
let content = preset.content_rect(canvas);
|
||||
assert_eq!(content.left(), 12.0);
|
||||
assert_eq!(content.top(), 10.0);
|
||||
assert_eq!(content.width(), expected_width);
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn renderer_presets_preserve_the_exported_top_inset() {
|
||||
for preset in [GalleryPreset::Renderer760, GalleryPreset::Renderer480] {
|
||||
let canvas = egui::Rect::from_min_size(
|
||||
egui::Pos2::ZERO,
|
||||
egui::vec2(preset.width(), preset.target_height()),
|
||||
);
|
||||
let content = preset.content_rect(canvas);
|
||||
assert_eq!(content.left(), 0.0);
|
||||
assert_eq!(content.top(), 12.0);
|
||||
assert_eq!(content.width(), preset.width());
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn material_export_overscan_is_cropped_instead_of_scaled() {
|
||||
assert_eq!(
|
||||
reference_crop([622, 661], GalleryPreset::Materials620),
|
||||
ReferenceCrop {
|
||||
origin: [1, 1],
|
||||
size: [620, 539],
|
||||
}
|
||||
);
|
||||
assert_eq!(
|
||||
reference_crop([422, 857], GalleryPreset::Materials420),
|
||||
ReferenceCrop {
|
||||
origin: [1, 1],
|
||||
size: [420, 735],
|
||||
}
|
||||
);
|
||||
assert_eq!(
|
||||
reference_crop([760, 1233], GalleryPreset::Renderer760),
|
||||
ReferenceCrop {
|
||||
origin: [0, 0],
|
||||
size: [760, 1233],
|
||||
}
|
||||
);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,243 @@
|
||||
use std::fs;
|
||||
use std::path::{Path, PathBuf};
|
||||
use std::time::{Duration, SystemTime};
|
||||
|
||||
use editor_ui::theme::{EditorVisualPalette, BLACKSITE_PALETTE};
|
||||
use serde::{Deserialize, Serialize};
|
||||
|
||||
use crate::fixtures::FixtureOverrides;
|
||||
|
||||
const POLL_INTERVAL: Duration = Duration::from_millis(300);
|
||||
|
||||
#[derive(Debug, Clone, Default, Serialize, Deserialize)]
|
||||
#[serde(default)]
|
||||
pub struct ThemeOverrides {
|
||||
pub canvas: Option<String>,
|
||||
pub panel: Option<String>,
|
||||
pub panel_dark: Option<String>,
|
||||
pub widget: Option<String>,
|
||||
pub elevated: Option<String>,
|
||||
pub accent: Option<String>,
|
||||
pub selection: Option<String>,
|
||||
pub text: Option<String>,
|
||||
pub text_dim: Option<String>,
|
||||
pub text_muted: Option<String>,
|
||||
pub border: Option<String>,
|
||||
pub border_strong: Option<String>,
|
||||
pub success: Option<String>,
|
||||
pub warning: Option<String>,
|
||||
pub error: Option<String>,
|
||||
}
|
||||
|
||||
impl ThemeOverrides {
|
||||
pub fn palette(&self) -> Result<EditorVisualPalette, String> {
|
||||
let mut palette = BLACKSITE_PALETTE;
|
||||
macro_rules! apply {
|
||||
($field:ident) => {
|
||||
if let Some(value) = self.$field.as_deref() {
|
||||
palette.$field = parse_color(value)?;
|
||||
}
|
||||
};
|
||||
}
|
||||
apply!(canvas);
|
||||
apply!(panel);
|
||||
apply!(panel_dark);
|
||||
apply!(widget);
|
||||
apply!(elevated);
|
||||
apply!(accent);
|
||||
apply!(selection);
|
||||
apply!(text);
|
||||
apply!(text_dim);
|
||||
apply!(text_muted);
|
||||
apply!(border);
|
||||
apply!(border_strong);
|
||||
apply!(success);
|
||||
apply!(warning);
|
||||
apply!(error);
|
||||
Ok(palette)
|
||||
}
|
||||
}
|
||||
|
||||
pub struct RuntimeDocuments {
|
||||
theme: ReloadableDocument<ThemeOverrides>,
|
||||
fixture: ReloadableDocument<FixtureOverrides>,
|
||||
pub theme_value: ThemeOverrides,
|
||||
pub fixture_value: FixtureOverrides,
|
||||
pub error: Option<String>,
|
||||
}
|
||||
|
||||
impl RuntimeDocuments {
|
||||
pub fn new(root: &Path) -> Self {
|
||||
Self::from_directory(root.join("crates/ui_gallery/fixtures"))
|
||||
}
|
||||
|
||||
fn from_directory(directory: PathBuf) -> Self {
|
||||
Self {
|
||||
theme: ReloadableDocument::new(directory.join("theme.json")),
|
||||
fixture: ReloadableDocument::new(directory.join("material.json")),
|
||||
theme_value: ThemeOverrides::default(),
|
||||
fixture_value: FixtureOverrides::default(),
|
||||
error: None,
|
||||
}
|
||||
}
|
||||
|
||||
pub fn poll(&mut self, now: f64) -> bool {
|
||||
let mut changed = false;
|
||||
match self.theme.poll(now) {
|
||||
Ok(Some(value)) => {
|
||||
self.theme_value = value;
|
||||
self.error = None;
|
||||
changed = true;
|
||||
}
|
||||
Err(error) => self.error = Some(error),
|
||||
Ok(None) => {}
|
||||
}
|
||||
match self.fixture.poll(now) {
|
||||
Ok(Some(value)) => {
|
||||
self.fixture_value = value;
|
||||
self.error = None;
|
||||
changed = true;
|
||||
}
|
||||
Err(error) => self.error = Some(error),
|
||||
Ok(None) => {}
|
||||
}
|
||||
changed
|
||||
}
|
||||
}
|
||||
|
||||
struct ReloadableDocument<T> {
|
||||
path: PathBuf,
|
||||
modified: Option<SystemTime>,
|
||||
next_poll: f64,
|
||||
marker: std::marker::PhantomData<T>,
|
||||
}
|
||||
|
||||
impl<T> ReloadableDocument<T>
|
||||
where
|
||||
T: for<'de> Deserialize<'de>,
|
||||
{
|
||||
fn new(path: PathBuf) -> Self {
|
||||
Self {
|
||||
path,
|
||||
modified: None,
|
||||
next_poll: 0.0,
|
||||
marker: std::marker::PhantomData,
|
||||
}
|
||||
}
|
||||
|
||||
fn poll(&mut self, now: f64) -> Result<Option<T>, String> {
|
||||
if now < self.next_poll {
|
||||
return Ok(None);
|
||||
}
|
||||
self.next_poll = now + POLL_INTERVAL.as_secs_f64();
|
||||
let metadata = fs::metadata(&self.path)
|
||||
.map_err(|error| format!("{}: {error}", self.path.display()))?;
|
||||
let modified = metadata.modified().ok();
|
||||
if self.modified == modified {
|
||||
return Ok(None);
|
||||
}
|
||||
let bytes =
|
||||
fs::read(&self.path).map_err(|error| format!("{}: {error}", self.path.display()))?;
|
||||
let value = serde_json::from_slice(&bytes)
|
||||
.map_err(|error| format!("{}: {error}", self.path.display()))?;
|
||||
self.modified = modified;
|
||||
Ok(Some(value))
|
||||
}
|
||||
}
|
||||
|
||||
fn parse_color(value: &str) -> Result<egui::Color32, String> {
|
||||
let value = value.trim().trim_start_matches('#');
|
||||
if value.len() != 6 && value.len() != 8 {
|
||||
return Err(format!("expected #RRGGBB or #RRGGBBAA, got {value}"));
|
||||
}
|
||||
let byte = |offset| {
|
||||
u8::from_str_radix(&value[offset..offset + 2], 16)
|
||||
.map_err(|error| format!("invalid color {value}: {error}"))
|
||||
};
|
||||
Ok(egui::Color32::from_rgba_unmultiplied(
|
||||
byte(0)?,
|
||||
byte(2)?,
|
||||
byte(4)?,
|
||||
if value.len() == 8 { byte(6)? } else { 255 },
|
||||
))
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
fn temporary_directory() -> PathBuf {
|
||||
let nonce = SystemTime::now()
|
||||
.duration_since(SystemTime::UNIX_EPOCH)
|
||||
.expect("system clock after epoch")
|
||||
.as_nanos();
|
||||
let directory = std::env::temp_dir().join(format!(
|
||||
"blacksite-ui-gallery-reload-{}-{nonce}",
|
||||
std::process::id()
|
||||
));
|
||||
fs::create_dir_all(&directory).expect("create temporary fixture directory");
|
||||
directory
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn runtime_documents_reload_fixture_without_reconstruction() {
|
||||
let directory = temporary_directory();
|
||||
fs::write(directory.join("theme.json"), "{}\n").expect("write theme fixture");
|
||||
fs::write(directory.join("material.json"), "{}\n").expect("write material fixture");
|
||||
let mut documents = RuntimeDocuments::from_directory(directory.clone());
|
||||
assert!(documents.poll(0.0));
|
||||
assert_eq!(documents.fixture_value.material_label, None);
|
||||
|
||||
fs::write(
|
||||
directory.join("material.json"),
|
||||
r#"{"material_label":"LIVE_RELOAD_PROOF"}"#,
|
||||
)
|
||||
.expect("update material fixture");
|
||||
assert!(documents.poll(1.0));
|
||||
assert_eq!(
|
||||
documents.fixture_value.material_label.as_deref(),
|
||||
Some("LIVE_RELOAD_PROOF")
|
||||
);
|
||||
assert_eq!(documents.error, None);
|
||||
fs::remove_dir_all(directory).expect("remove temporary fixture directory");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn invalid_reload_keeps_the_last_valid_document_and_reports_the_error() {
|
||||
let directory = temporary_directory();
|
||||
fs::write(directory.join("theme.json"), "{}\n").expect("write theme fixture");
|
||||
fs::write(
|
||||
directory.join("material.json"),
|
||||
r#"{"material_label":"baseline"}"#,
|
||||
)
|
||||
.expect("write material fixture");
|
||||
let mut documents = RuntimeDocuments::from_directory(directory.clone());
|
||||
assert!(documents.poll(0.0));
|
||||
|
||||
fs::write(directory.join("material.json"), "{ invalid json\n")
|
||||
.expect("write invalid material fixture");
|
||||
assert!(!documents.poll(1.0));
|
||||
assert_eq!(
|
||||
documents.fixture_value.material_label.as_deref(),
|
||||
Some("baseline")
|
||||
);
|
||||
assert!(documents
|
||||
.error
|
||||
.as_deref()
|
||||
.is_some_and(|error| error.contains("material.json")));
|
||||
fs::remove_dir_all(directory).expect("remove temporary fixture directory");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn theme_colors_accept_rgb_and_rgba_hex() {
|
||||
assert_eq!(
|
||||
parse_color("#41C6CF").expect("valid RGB"),
|
||||
egui::Color32::from_rgb(65, 198, 207)
|
||||
);
|
||||
assert_eq!(
|
||||
parse_color("E25E5E80").expect("valid RGBA"),
|
||||
egui::Color32::from_rgba_unmultiplied(226, 94, 94, 128)
|
||||
);
|
||||
assert!(parse_color("#not-a-color").is_err());
|
||||
}
|
||||
}
|
||||
Reference in new issue
Block a user