mirror of
https://github.com/storytold/materialcraft.git
synced 2026-11-19 14:01:02 +01:00
Adapt selected UI improvements to refactored main
Add panel maximize/restore, template tiles with atomic rectangular graph creation, and tabs for existing preferences. Keep main's graph, explorer, library and embedded editor implementations intact, and scope template textures to each app. Validated with Rust 1.96.0: engine and UI release suites, 14 offscreen UI tests and visual inspection, workspace Clippy, layers, wasm, native build and live maximize/restore checks.
This commit is contained in:
1 parent
0bfbbf1887
commit
5c69e51123
22 files changed
+1176
-512
No files matched your search
@@ -16,7 +16,7 @@ pub(crate) fn specs() -> Vec<CommandSpec> {
|
||||
"Graph...",
|
||||
["File", "New"],
|
||||
Some("Ctrl+N"),
|
||||
"{name?, kind? (material|function), template? (see graph.templates), size? (px, power of two)} adds a new graph to the package and opens it",
|
||||
"{name?, kind? (material|function), template? (see graph.templates), size? (default 1024), width?, height?} adds and opens a graph; material dimensions override size per axis, rounded down to powers of two in 16..8192 px",
|
||||
always,
|
||||
new_graph
|
||||
),
|
||||
@@ -69,7 +69,8 @@ fn new_graph(session: &mut Session, parameters: &J) -> Result<J> {
|
||||
TEMPLATES.iter().find(|entry| entry.0 == template_id).map_or("Graph", |entry| entry.1)
|
||||
};
|
||||
let size = u64p(parameters, "size").unwrap_or(1024).clamp(16, 8192);
|
||||
let log2 = 63 - size.leading_zeros();
|
||||
let width_log2 = graph_dimension(parameters, "width", size)?;
|
||||
let height_log2 = graph_dimension(parameters, "height", size)?;
|
||||
let base = strp(parameters, "name").map(str::to_string).unwrap_or_else(|| label.replace(' ', "_"));
|
||||
|
||||
session.edit("New graph", |session| {
|
||||
@@ -79,7 +80,9 @@ fn new_graph(session: &mut Session, parameters: &J) -> Result<J> {
|
||||
graph.function = Some(materialcraft_core::FunctionGraph::default());
|
||||
graph
|
||||
} else {
|
||||
template(template_id, &name, log2)?
|
||||
let mut graph = template(template_id, &name, width_log2)?;
|
||||
graph.size = [width_log2, height_log2];
|
||||
graph
|
||||
};
|
||||
session.pkg.graphs.push(graph);
|
||||
session.graph = session.pkg.graphs.len() - 1;
|
||||
@@ -91,6 +94,14 @@ fn new_graph(session: &mut Session, parameters: &J) -> Result<J> {
|
||||
})
|
||||
}
|
||||
|
||||
fn graph_dimension(parameters: &J, axis: &str, default_pixels: u64) -> Result<u32> {
|
||||
let pixels = match parameters.get(axis) {
|
||||
Some(value) => value.as_u64().ok_or_else(|| bad("file.new", format!("`{axis}` must be a nonnegative integer in pixels")))?,
|
||||
None => default_pixels,
|
||||
};
|
||||
Ok(63 - pixels.clamp(16, 8192).leading_zeros())
|
||||
}
|
||||
|
||||
fn new_package(s: &mut Session, p: &J) -> Result<J> {
|
||||
let mut pkg = Package::new(strp(p, "name").unwrap_or("Untitled package"));
|
||||
pkg.graphs.push(template("pbr", "New_graph", 10)?);
|
||||
|
||||
@@ -0,0 +1,48 @@
|
||||
use materialcraft_engine::{execute, new_session};
|
||||
use serde_json::json;
|
||||
|
||||
#[test]
|
||||
fn rectangular_templates_are_created_and_undone_as_one_edit() {
|
||||
for template in ["empty", "pbr", "atomics"] {
|
||||
let mut session = new_session();
|
||||
let original = session.pkg.clone();
|
||||
let original_graph = session.graph;
|
||||
execute(&mut session, "file.new", &json!({"template": template, "name": "Wide", "width": 512, "height": 128})).unwrap();
|
||||
assert_eq!(session.graph().unwrap().size_px(), [512, 128]);
|
||||
assert_eq!(session.graph().unwrap().name, "Wide");
|
||||
assert_eq!(session.pkg.graphs.len(), original.graphs.len() + 1);
|
||||
execute(&mut session, "edit.undo", &json!({})).unwrap();
|
||||
assert_eq!(session.pkg, original);
|
||||
assert_eq!(session.graph, original_graph);
|
||||
assert!(!session.modified);
|
||||
execute(&mut session, "edit.redo", &json!({})).unwrap();
|
||||
assert_eq!(session.graph().unwrap().size_px(), [512, 128]);
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn dimension_overrides_keep_square_defaults_and_bound_each_axis() {
|
||||
for (parameters, expected) in [
|
||||
(json!({"size": 256}), [256, 256]),
|
||||
(json!({"size": 256, "height": 64}), [256, 64]),
|
||||
(json!({"size": 256, "width": 64}), [64, 256]),
|
||||
(json!({"width": 1000, "height": 127}), [512, 64]),
|
||||
(json!({"width": 0, "height": u64::MAX}), [16, 8192]),
|
||||
] {
|
||||
let mut session = new_session();
|
||||
execute(&mut session, "file.new", ¶meters).unwrap();
|
||||
assert_eq!(session.graph().unwrap().size_px(), expected, "{parameters}");
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn invalid_dimensions_do_not_create_a_partial_graph_or_undo_entry() {
|
||||
for parameters in [json!({"width": -1}), json!({"height": "128"}), json!({"width": 32.5}), json!({"height": null})] {
|
||||
let mut session = new_session();
|
||||
let original = session.pkg.clone();
|
||||
assert!(execute(&mut session, "file.new", ¶meters).is_err(), "{parameters}");
|
||||
assert_eq!(session.pkg, original);
|
||||
assert!(!session.modified);
|
||||
assert!(execute(&mut session, "edit.undo", &json!({})).is_err());
|
||||
}
|
||||
}
|
||||
@@ -291,6 +291,7 @@ fn handle_inner(app: &mut MaterialCraftApp, ctx: &egui::Context, method: &str, p
|
||||
let (view, nodes, ports) = (app.graph.view, &app.graph.rects, &app.graph.ports);
|
||||
ok(json!({
|
||||
"state": app.ui,
|
||||
"maximizedPanel": app.ui.dock.maximized(),
|
||||
"graphView": rect(view),
|
||||
"selection": app.session.selection,
|
||||
"inspectedNode": app.graph.inspected_node,
|
||||
@@ -319,6 +320,19 @@ fn handle_inner(app: &mut MaterialCraftApp, ctx: &egui::Context, method: &str, p
|
||||
"toasts": app.toasts.iter().map(|t| json!({"text": t.text, "error": t.error})).collect::<Vec<_>>(),
|
||||
}))
|
||||
}
|
||||
"ui.panel.maximize" => {
|
||||
let Some(panel) = p.get("panel").cloned().and_then(|value| serde_json::from_value::<crate::docking::Panel>(value).ok()) else {
|
||||
return err("`panel` must name a workspace panel, such as Graph or View2d");
|
||||
};
|
||||
|
||||
match app.ui.dock.maximize(panel) {
|
||||
Ok(()) => {
|
||||
ctx.request_repaint();
|
||||
ok(Value::Null)
|
||||
}
|
||||
Err(error) => err(error),
|
||||
}
|
||||
}
|
||||
"ui.menu.list" => ok(crate::menus::list(app)),
|
||||
"ui.menu.invoke" => {
|
||||
let Some(id) = p.get("id").and_then(Value::as_str) else { return err("`id` is required") };
|
||||
|
||||
+52
-338
@@ -1,307 +1,74 @@
|
||||
//! The dock host: every panel (explorer, library, graph, 3D view, 2D view, properties, console,
|
||||
//! history) is a tab that can be docked, tabbed, resized, floated and closed. craft-ui's shared
|
||||
//! docking (`craft_ui::docking`) draws the frames, tab strips, floating windows and drop previews
|
||||
//! and owns the gestures; this module names the panels, builds the default arrangement, applies
|
||||
//! the dock's changes and hosts the panel bodies.
|
||||
//!
|
||||
//! The graph is the central canvas: it stays docked, never takes tabs and is the only panel that
|
||||
//! cannot close or float. The layout persists with `UiState` as a craft-ui `Workspace`; a layout
|
||||
//! that does not load or validate becomes the default.
|
||||
//! Panel hosting, workspace validation and transient maximization
|
||||
|
||||
use craft_ui::docking::{Action, DockArea, DockContent, DockStyle, Layout, Location, Node, PanelLimits, PanelState, Permissions, Placement};
|
||||
use craft_ui::layout::{SplitAxis, SplitSize};
|
||||
use egui::{Id, Margin, RichText, Ui, vec2};
|
||||
use serde::{Deserialize, Serialize};
|
||||
use serde_json::Value;
|
||||
mod dock;
|
||||
mod maximization;
|
||||
mod panel;
|
||||
mod panel_content;
|
||||
mod workspace;
|
||||
|
||||
use crate::MaterialCraftApp;
|
||||
use crate::i18n::tr;
|
||||
use crate::theme::Tokens;
|
||||
pub use dock::Dock;
|
||||
pub use panel::{Panel, VIEWS, view_panel};
|
||||
pub use workspace::{Workspace, default_workspace, permissions, validate};
|
||||
|
||||
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash, Serialize, Deserialize)]
|
||||
pub enum Panel {
|
||||
Graph,
|
||||
Explorer,
|
||||
Library,
|
||||
View3d,
|
||||
View2d,
|
||||
Properties,
|
||||
Console,
|
||||
History,
|
||||
}
|
||||
use craft_ui::docking::{DockArea, DockStyle};
|
||||
use egui::{Id, Ui};
|
||||
|
||||
/// Windows menu items and the panels they show or hide.
|
||||
pub const VIEWS: [(&str, Panel); 7] = [
|
||||
("ui.view.explorer", Panel::Explorer),
|
||||
("ui.view.properties", Panel::Properties),
|
||||
("ui.view.console", Panel::Console),
|
||||
("ui.view.3d", Panel::View3d),
|
||||
("ui.view.2d", Panel::View2d),
|
||||
("ui.view.library", Panel::Library),
|
||||
("ui.view.history", Panel::History),
|
||||
];
|
||||
|
||||
/// The panel a Windows menu item toggles.
|
||||
pub fn view_panel(id: &str) -> Option<Panel> {
|
||||
VIEWS.iter().find(|(v, _)| *v == id).map(|(_, p)| *p)
|
||||
}
|
||||
|
||||
impl Panel {
|
||||
pub const ALL: [Panel; 8] =
|
||||
[Panel::Graph, Panel::Explorer, Panel::Library, Panel::View3d, Panel::View2d, Panel::Properties, Panel::Console, Panel::History];
|
||||
|
||||
pub fn name(self) -> &'static str {
|
||||
match self {
|
||||
Panel::Graph => "Graph",
|
||||
Panel::Explorer => "Explorer",
|
||||
Panel::Library => "Library",
|
||||
Panel::View3d => "3D View",
|
||||
Panel::View2d => "2D View",
|
||||
Panel::Properties => "Properties",
|
||||
Panel::Console => "Console",
|
||||
Panel::History => "History",
|
||||
}
|
||||
}
|
||||
|
||||
/// Where the panel floats when it has never been laid out: `[x, y, width, height]`, cascaded.
|
||||
fn float_rect(self) -> Option<[f32; 4]> {
|
||||
let slot = match self {
|
||||
Panel::Console => 0.0,
|
||||
Panel::History => 1.0,
|
||||
_ => return None,
|
||||
};
|
||||
Some([900.0, 120.0 + 50.0 * slot, 420.0, 320.0])
|
||||
}
|
||||
}
|
||||
|
||||
/// The saved panel arrangement: craft-ui's workspace over MaterialCraft's panels.
|
||||
pub type Workspace = craft_ui::docking::Workspace<Panel>;
|
||||
|
||||
/// The graph never moves, floats, closes or takes tabs; panels dock beside it.
|
||||
pub fn permissions(panel: &Panel) -> Permissions {
|
||||
if *panel == Panel::Graph { Permissions { accepts_splits: true, ..Permissions::PROTECTED } } else { Permissions::default() }
|
||||
}
|
||||
|
||||
fn tabs(panels: &[Panel]) -> Node<Panel> {
|
||||
Node::Tabs { panels: panels.to_vec(), active: 0 }
|
||||
}
|
||||
|
||||
fn split(axis: SplitAxis, ratio: f32, first: Node<Panel>, second: Node<Panel>) -> Node<Panel> {
|
||||
Node::Split { axis, size: SplitSize::Ratio(ratio), first: Box::new(first), second: Box::new(second) }
|
||||
}
|
||||
|
||||
/// The default: explorer over library on the left; the graph over the 3D and 2D views in the
|
||||
/// middle; properties on the right. Console and history are closed and open floating.
|
||||
pub fn default_workspace() -> Workspace {
|
||||
use Panel::*;
|
||||
let left = split(SplitAxis::Vertical, 0.36, tabs(&[Explorer]), tabs(&[Library]));
|
||||
let views = split(SplitAxis::Horizontal, 0.5, tabs(&[View3d]), tabs(&[View2d]));
|
||||
let center = split(SplitAxis::Vertical, 0.52, tabs(&[Graph]), views);
|
||||
let root = split(SplitAxis::Horizontal, 0.15, left, split(SplitAxis::Horizontal, 0.8, center, tabs(&[Properties])));
|
||||
let mut workspace = Workspace::new(Layout { root: Some(root), floating: Vec::new() });
|
||||
for panel in Panel::ALL {
|
||||
if let Some(rect) = panel.float_rect() {
|
||||
let location = Location {
|
||||
floating: Some(rect),
|
||||
anchor: None,
|
||||
placement: Placement::Tab { before: None },
|
||||
size: None,
|
||||
stack: None,
|
||||
sibling: Vec::new(),
|
||||
group: None,
|
||||
};
|
||||
workspace.hidden.push((panel, location));
|
||||
}
|
||||
}
|
||||
workspace
|
||||
}
|
||||
|
||||
/// craft-ui's checks plus the graph's: a saved or hand-edited file cannot hide, float, group
|
||||
/// or collapse it.
|
||||
pub fn validate(workspace: &Workspace) -> Result<(), String> {
|
||||
workspace.validate().map_err(|error| error.to_string())?;
|
||||
let layout = &workspace.layout;
|
||||
if layout.floating.iter().any(|window| window.contains(&Panel::Graph)) {
|
||||
return Err("The graph cannot float".into());
|
||||
}
|
||||
if workspace.hidden.iter().any(|(panel, _)| *panel == Panel::Graph) {
|
||||
return Err("The graph cannot be hidden".into());
|
||||
}
|
||||
let mut found = false;
|
||||
let mut nodes: Vec<&Node<Panel>> = layout.root.iter().collect();
|
||||
while let Some(node) = nodes.pop() {
|
||||
match node {
|
||||
Node::Split { first, second, .. } => {
|
||||
nodes.push(first);
|
||||
nodes.push(second);
|
||||
}
|
||||
Node::Tabs { panels, .. } if panels.contains(&Panel::Graph) => {
|
||||
if panels.len() != 1 {
|
||||
return Err("The graph cannot share a tab group".into());
|
||||
}
|
||||
found = true;
|
||||
}
|
||||
Node::Stack { entries } if entries.iter().any(|entry| entry.panel == Panel::Graph) => {
|
||||
return Err("The graph cannot be collapsed".into());
|
||||
}
|
||||
Node::Dock { columns, .. } if columns.iter().flat_map(|column| &column.groups).any(|group| group.panels.contains(&Panel::Graph)) => {
|
||||
return Err("The graph cannot be in a dock".into());
|
||||
}
|
||||
_ => {}
|
||||
}
|
||||
}
|
||||
if found { Ok(()) } else { Err("The panel layout must contain the graph".into()) }
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------------------------------------
|
||||
// The live dock
|
||||
|
||||
/// The dock layout (part of `UiState`; serialized as a craft-ui `Workspace`).
|
||||
#[derive(Clone, Debug)]
|
||||
pub struct Dock {
|
||||
workspace: Workspace,
|
||||
/// A panel to bring in front of the other floating windows on the next frame.
|
||||
raise: Option<Panel>,
|
||||
}
|
||||
|
||||
impl Default for Dock {
|
||||
fn default() -> Self {
|
||||
Dock { workspace: default_workspace(), raise: None }
|
||||
}
|
||||
}
|
||||
|
||||
impl PartialEq for Dock {
|
||||
fn eq(&self, other: &Self) -> bool {
|
||||
self.workspace == other.workspace
|
||||
}
|
||||
}
|
||||
|
||||
impl Serialize for Dock {
|
||||
fn serialize<S: serde::Serializer>(&self, s: S) -> Result<S::Ok, S::Error> {
|
||||
self.workspace.serialize(s)
|
||||
}
|
||||
}
|
||||
|
||||
impl<'de> Deserialize<'de> for Dock {
|
||||
/// Never fails: a layout that cannot be read or fails the graph's rules is the default.
|
||||
fn deserialize<D: serde::Deserializer<'de>>(d: D) -> Result<Self, D::Error> {
|
||||
Ok(Dock::from_value(Value::deserialize(d)?))
|
||||
}
|
||||
}
|
||||
|
||||
impl Dock {
|
||||
/// The dock for a saved layout; the default when it is not a valid workspace.
|
||||
pub fn from_value(value: Value) -> Dock {
|
||||
let default = default_workspace();
|
||||
let loaded = serde_json::from_value::<Workspace>(value).ok();
|
||||
let Some(mut workspace) = loaded.filter(|w| validate(w).is_ok()) else { return Dock::default() };
|
||||
workspace.reconcile(|_| true, permissions, &default);
|
||||
if validate(&workspace).is_err() {
|
||||
return Dock::default();
|
||||
}
|
||||
Dock { workspace, raise: None }
|
||||
}
|
||||
|
||||
pub fn workspace(&self) -> &Workspace {
|
||||
&self.workspace
|
||||
}
|
||||
|
||||
pub fn is_open(&self, p: Panel) -> bool {
|
||||
self.workspace.layout.contains(&p)
|
||||
}
|
||||
|
||||
/// Open and the front tab of its group.
|
||||
pub fn is_visible(&self, p: Panel) -> bool {
|
||||
self.workspace.layout.panel_state(&p) == PanelState::Front
|
||||
}
|
||||
|
||||
/// Hide a visible panel, otherwise bring it up.
|
||||
pub fn toggle(&mut self, p: Panel) {
|
||||
if self.is_visible(p) { self.close(p) } else { self.focus(p) }
|
||||
}
|
||||
|
||||
pub fn close(&mut self, p: Panel) {
|
||||
if let Err(error) = self.workspace.set_visible(p, false, None, permissions) {
|
||||
log::warn!("panel {p:?} was not closed: {error}");
|
||||
}
|
||||
}
|
||||
|
||||
/// Open `p` (where it was when closed, else where it lives by default) and bring it to the
|
||||
/// front.
|
||||
pub fn focus(&mut self, p: Panel) {
|
||||
let mut next = self.workspace.clone();
|
||||
match next.set_visible(p, true, None, permissions) {
|
||||
Ok(()) if validate(&next).is_ok() => {
|
||||
self.workspace = next;
|
||||
self.raise = Some(p);
|
||||
}
|
||||
Ok(()) => log::warn!("panel {p:?} was not opened: it would break the graph's rules"),
|
||||
Err(error) => log::warn!("panel {p:?} was not opened: {error}"),
|
||||
}
|
||||
}
|
||||
|
||||
/// One change from the dock area's gestures. A change that is rejected leaves the layout as
|
||||
/// it was.
|
||||
fn apply(&mut self, action: Action<Panel>) {
|
||||
let mut next = self.workspace.clone();
|
||||
match next.apply(action, permissions) {
|
||||
Ok(_) if validate(&next).is_ok() => self.workspace = next,
|
||||
Ok(_) => log::warn!("a panel move would break the graph's rules"),
|
||||
Err(error) => log::warn!("a panel move was not applied: {error}"),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------------------------------------
|
||||
// Drawing
|
||||
use crate::{MaterialCraftApp, theme::Tokens};
|
||||
use panel_content::PanelContent;
|
||||
|
||||
fn area_id() -> Id {
|
||||
Id::unique("materialcraft-docking")
|
||||
}
|
||||
|
||||
/// The dock look: every panel group is a card on the window's frame colour, its tab strip
|
||||
/// without hard lines, the shown tab a pill, uppercase captions.
|
||||
fn style(ui: &Ui, t: &Tokens) -> DockStyle {
|
||||
let mut s = DockStyle::from_ui(ui);
|
||||
s.gap = 6.0;
|
||||
// Smallest panel extent a divider drag leaves.
|
||||
s.min_pane = 60.0;
|
||||
s.background = t.panel;
|
||||
s.tab_background = t.panel;
|
||||
s.active_background = t.button;
|
||||
s.text = t.text_strong;
|
||||
s.inactive_text = t.text_dim;
|
||||
s.border = egui::Stroke::NONE;
|
||||
s.accent = t.accent;
|
||||
s.floating_background = t.panel;
|
||||
s.floating_stroke = egui::Stroke::new(1.0, t.button_border);
|
||||
s.font = egui::FontId::proportional(10.5);
|
||||
s.min_tab_width = 54.0;
|
||||
s.tab_height = 30.0;
|
||||
// Panels arrange in a split tree around the graph; floating title bars only move windows.
|
||||
s.new_dock_zones = false;
|
||||
s.title_bar_docks = false;
|
||||
s
|
||||
/// Shared appearance for docked and floating panels
|
||||
fn style(ui: &Ui, tokens: &Tokens) -> DockStyle {
|
||||
let mut style = DockStyle::from_ui(ui);
|
||||
style.gap = 6.0;
|
||||
// Smallest panel extent a divider drag leaves
|
||||
style.min_pane = 60.0;
|
||||
style.background = tokens.panel;
|
||||
style.tab_background = tokens.panel;
|
||||
style.active_background = tokens.button;
|
||||
style.text = tokens.text_strong;
|
||||
style.inactive_text = tokens.text_dim;
|
||||
style.border = egui::Stroke::NONE;
|
||||
style.accent = tokens.accent;
|
||||
style.floating_background = tokens.panel;
|
||||
style.floating_stroke = egui::Stroke::new(1.0, tokens.button_border);
|
||||
style.font = egui::FontId::proportional(10.5);
|
||||
style.min_tab_width = 54.0;
|
||||
style.tab_height = 30.0;
|
||||
// Floating title bars move windows without creating new docks
|
||||
style.new_dock_zones = false;
|
||||
style.title_bar_docks = false;
|
||||
style
|
||||
}
|
||||
|
||||
/// Draw the dock (graph and panels) into `ui`.
|
||||
/// Draw the saved workspace or its maximized panel
|
||||
pub fn show(app: &mut MaterialCraftApp, ui: &mut Ui) {
|
||||
let ctx = ui.ctx().clone();
|
||||
let tk = Tokens::get(&ctx);
|
||||
let style = style(ui, &tk);
|
||||
let context = ui.ctx().clone();
|
||||
if app.ui.dock.maximized().is_some() && maximization::consume_shortcut(&context) {
|
||||
app.ui.dock.restore();
|
||||
}
|
||||
if let Some(panel) = app.ui.dock.maximized() {
|
||||
maximization::show(app, ui, panel);
|
||||
return;
|
||||
}
|
||||
|
||||
let tokens = Tokens::get(&context);
|
||||
let style = style(ui, &tokens);
|
||||
let layout = app.ui.dock.workspace.layout.clone();
|
||||
let mut area = DockArea::new(area_id()).input_blocked(ctx.memory(|m| m.top_modal_layer()).is_some());
|
||||
let mut area = DockArea::new(area_id()).input_blocked(context.memory(|m| m.top_modal_layer()).is_some());
|
||||
if let Some(panel) = app.ui.dock.raise.take() {
|
||||
area = area.raise_panel(panel);
|
||||
}
|
||||
let output = area.show_content(ui, &layout, &style, &mut Panels { app });
|
||||
let output = area.show_content(ui, &layout, &style, &mut PanelContent { app });
|
||||
if let Some(error) = &output.error {
|
||||
log::warn!("docking: {error}");
|
||||
}
|
||||
// A body that changed the layout (a panel opened from its own menu) wins over this frame's
|
||||
// gestures, which were made against the old one.
|
||||
if app.ui.dock.workspace.layout != layout {
|
||||
craft_ui::docking::cancel_drag::<Panel>(&ctx, area_id());
|
||||
// Panel actions take priority over gestures against the previous layout
|
||||
if app.ui.dock.workspace.layout != layout || app.ui.dock.maximized().is_some() {
|
||||
craft_ui::docking::cancel_drag::<Panel>(&context, area_id());
|
||||
return;
|
||||
}
|
||||
for action in output.actions {
|
||||
@@ -309,59 +76,6 @@ pub fn show(app: &mut MaterialCraftApp, ui: &mut Ui) {
|
||||
}
|
||||
}
|
||||
|
||||
/// The panels' contents, names and limits for the dock area.
|
||||
struct Panels<'a> {
|
||||
app: &'a mut MaterialCraftApp,
|
||||
}
|
||||
|
||||
impl DockContent<Panel> for Panels<'_> {
|
||||
fn body(&mut self, ui: &mut Ui, panel: &Panel) {
|
||||
let app = &mut *self.app;
|
||||
match panel {
|
||||
Panel::Graph => crate::graph::show(app, ui),
|
||||
Panel::View3d => crate::view3d::show(app, ui),
|
||||
Panel::View2d => crate::view2d::show(app, ui),
|
||||
_ => {
|
||||
egui::Frame::new().inner_margin(Margin::symmetric(6, 4)).show(ui, |ui| match panel {
|
||||
Panel::Explorer => crate::explorer::show(app, ui),
|
||||
Panel::Library => crate::library::show(app, ui),
|
||||
Panel::Properties => crate::properties::show(app, ui),
|
||||
Panel::Console => crate::windows::console(app, ui),
|
||||
Panel::History => crate::windows::history(app, ui),
|
||||
_ => {}
|
||||
});
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fn logical_label(&self, panel: &Panel) -> String {
|
||||
match panel {
|
||||
Panel::Properties => crate::properties::title(self.app),
|
||||
Panel::Graph => self.app.session.graph().map(|g| format!("{} - {}", g.name, tr("Graph"))).unwrap_or_else(|_| tr("Graph").into()),
|
||||
Panel::View3d => format!("{} - {}", crate::view3d::scene_label(self.app), tr("3D View")),
|
||||
Panel::View2d => crate::view2d::title(self.app),
|
||||
p => tr(p.name()).to_string(),
|
||||
}
|
||||
}
|
||||
|
||||
fn label(&mut self, _ui: &Ui, _panel: &Panel, logical: &str, font: &egui::FontId, color: egui::Color32) -> egui::WidgetText {
|
||||
RichText::new(logical.to_uppercase()).font(font.clone()).strong().color(color).into()
|
||||
}
|
||||
|
||||
fn permissions(&self, panel: &Panel) -> Permissions {
|
||||
permissions(panel)
|
||||
}
|
||||
|
||||
fn limits(&self, panel: &Panel) -> PanelLimits {
|
||||
let min = if *panel == Panel::Graph { vec2(240.0, 160.0) } else { vec2(120.0, 60.0) };
|
||||
PanelLimits { min, ..PanelLimits::default() }
|
||||
}
|
||||
|
||||
fn floating_size(&self, _panel: &Panel) -> Option<egui::Vec2> {
|
||||
Some(vec2(420.0, 320.0))
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
@@ -0,0 +1,122 @@
|
||||
use craft_ui::docking::{Action, PanelState};
|
||||
use serde::{Deserialize, Serialize};
|
||||
use serde_json::Value;
|
||||
|
||||
use super::{Panel, Workspace, default_workspace, permissions, validate};
|
||||
|
||||
/// Saved workspace and transient panel presentation
|
||||
#[derive(Clone, Debug)]
|
||||
pub struct Dock {
|
||||
pub(super) workspace: Workspace,
|
||||
pub(super) raise: Option<Panel>,
|
||||
maximized: Option<Panel>,
|
||||
}
|
||||
|
||||
impl Default for Dock {
|
||||
fn default() -> Self {
|
||||
Self { workspace: default_workspace(), raise: None, maximized: None }
|
||||
}
|
||||
}
|
||||
|
||||
impl PartialEq for Dock {
|
||||
fn eq(&self, other: &Self) -> bool {
|
||||
self.workspace == other.workspace
|
||||
}
|
||||
}
|
||||
|
||||
impl Serialize for Dock {
|
||||
fn serialize<S: serde::Serializer>(&self, serializer: S) -> Result<S::Ok, S::Error> {
|
||||
self.workspace.serialize(serializer)
|
||||
}
|
||||
}
|
||||
|
||||
impl<'de> Deserialize<'de> for Dock {
|
||||
fn deserialize<D: serde::Deserializer<'de>>(deserializer: D) -> Result<Self, D::Error> {
|
||||
Ok(Self::from_value(Value::deserialize(deserializer)?))
|
||||
}
|
||||
}
|
||||
|
||||
impl Dock {
|
||||
/// Invalid layouts fall back to the default workspace
|
||||
pub fn from_value(value: Value) -> Self {
|
||||
let default = default_workspace();
|
||||
let loaded = serde_json::from_value::<Workspace>(value).ok();
|
||||
let Some(mut workspace) = loaded.filter(|workspace| validate(workspace).is_ok()) else {
|
||||
return Self::default();
|
||||
};
|
||||
|
||||
workspace.reconcile(|_| true, permissions, &default);
|
||||
if validate(&workspace).is_err() {
|
||||
return Self::default();
|
||||
}
|
||||
Self { workspace, raise: None, maximized: None }
|
||||
}
|
||||
|
||||
pub fn workspace(&self) -> &Workspace {
|
||||
&self.workspace
|
||||
}
|
||||
|
||||
pub fn maximized(&self) -> Option<Panel> {
|
||||
self.maximized
|
||||
}
|
||||
|
||||
/// Maximization never alters the saved layout or opens hidden panels
|
||||
pub fn maximize(&mut self, panel: Panel) -> Result<(), String> {
|
||||
if self.workspace.layout.panel_state(&panel) != PanelState::Front {
|
||||
return Err(format!("{} must be an open, active panel before maximizing", panel.name()));
|
||||
}
|
||||
self.maximized = Some(panel);
|
||||
Ok(())
|
||||
}
|
||||
|
||||
pub fn restore(&mut self) {
|
||||
self.maximized = None;
|
||||
}
|
||||
|
||||
pub fn is_open(&self, panel: Panel) -> bool {
|
||||
self.workspace.layout.contains(&panel)
|
||||
}
|
||||
|
||||
pub fn is_visible(&self, panel: Panel) -> bool {
|
||||
self.maximized.map_or_else(|| self.workspace.layout.panel_state(&panel) == PanelState::Front, |maximized| maximized == panel)
|
||||
}
|
||||
|
||||
/// Hide a visible panel or bring it into view
|
||||
pub fn toggle(&mut self, panel: Panel) {
|
||||
if self.is_visible(panel) { self.close(panel) } else { self.focus(panel) }
|
||||
}
|
||||
|
||||
pub fn close(&mut self, panel: Panel) {
|
||||
match self.workspace.set_visible(panel, false, None, permissions) {
|
||||
Ok(()) if self.maximized == Some(panel) => self.restore(),
|
||||
Ok(()) => {}
|
||||
Err(error) => log::warn!("panel {panel:?} was not closed: {error}"),
|
||||
}
|
||||
}
|
||||
|
||||
/// Reveal the requested panel in its existing location
|
||||
pub fn focus(&mut self, panel: Panel) {
|
||||
let mut next = self.workspace.clone();
|
||||
match next.set_visible(panel, true, None, permissions) {
|
||||
Ok(()) if validate(&next).is_ok() => {
|
||||
self.workspace = next;
|
||||
self.raise = Some(panel);
|
||||
if self.maximized != Some(panel) {
|
||||
self.restore();
|
||||
}
|
||||
}
|
||||
Ok(()) => log::warn!("panel {panel:?} was not opened: it would break the graph's rules"),
|
||||
Err(error) => log::warn!("panel {panel:?} was not opened: {error}"),
|
||||
}
|
||||
}
|
||||
|
||||
/// Rejected gestures leave the layout intact
|
||||
pub(super) fn apply(&mut self, action: Action<Panel>) {
|
||||
let mut next = self.workspace.clone();
|
||||
match next.apply(action, permissions) {
|
||||
Ok(_) if validate(&next).is_ok() => self.workspace = next,
|
||||
Ok(_) => log::warn!("a panel move would break the graph's rules"),
|
||||
Err(error) => log::warn!("a panel move was not applied: {error}"),
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,39 @@
|
||||
use craft_ui::docking::DockContent;
|
||||
use egui::{Context, Key, Modifiers, RichText, Ui};
|
||||
|
||||
use super::{Panel, panel_content::PanelContent};
|
||||
use crate::{MaterialCraftApp, i18n::tr, theme::Tokens};
|
||||
|
||||
pub(super) fn consume_shortcut(context: &Context) -> bool {
|
||||
if context.egui_wants_keyboard_input()
|
||||
|| egui::Popup::is_any_open(context)
|
||||
|| context.memory(|memory| memory.top_modal_layer()).is_some()
|
||||
|| context.input(|input| input.pointer.any_down())
|
||||
{
|
||||
return false;
|
||||
}
|
||||
context.input_mut(|input| input.consume_key(Modifiers::SHIFT, Key::Space))
|
||||
}
|
||||
|
||||
pub(super) fn show(app: &mut MaterialCraftApp, ui: &mut Ui, panel: Panel) {
|
||||
let tokens = Tokens::get(ui.ctx());
|
||||
let title = PanelContent { app }.logical_label(&panel);
|
||||
egui::Frame::NONE.fill(tokens.panel).show(ui, |ui| {
|
||||
ui.set_min_size(ui.available_size());
|
||||
ui.horizontal(|ui| {
|
||||
ui.label(RichText::new(title.to_uppercase()).size(10.5).strong().color(tokens.text_strong));
|
||||
ui.with_layout(egui::Layout::right_to_left(egui::Align::Center), |ui| {
|
||||
if ui.small_button(tr("Restore panel layout")).on_hover_text("Shift+Space").clicked() {
|
||||
crate::menus::invoke(app, ui.ctx(), "ui.unmaximize");
|
||||
}
|
||||
});
|
||||
});
|
||||
let rectangle = ui.available_rect_before_wrap();
|
||||
// Match the dock host's scope so widget state survives maximizing and restoring
|
||||
let mut body = ui.new_child(
|
||||
egui::UiBuilder::new().scope_id(super::area_id().with(("body", &panel))).max_rect(rectangle).layout(egui::Layout::top_down(egui::Align::Min)),
|
||||
);
|
||||
body.set_clip_rect(rectangle.intersect(ui.clip_rect()));
|
||||
PanelContent { app }.body(&mut body, &panel);
|
||||
});
|
||||
}
|
||||
@@ -0,0 +1,57 @@
|
||||
use serde::{Deserialize, Serialize};
|
||||
|
||||
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash, Serialize, Deserialize)]
|
||||
pub enum Panel {
|
||||
Graph,
|
||||
Explorer,
|
||||
Library,
|
||||
View3d,
|
||||
View2d,
|
||||
Properties,
|
||||
Console,
|
||||
History,
|
||||
}
|
||||
|
||||
/// Windows menu items and the panels they show or hide
|
||||
pub const VIEWS: [(&str, Panel); 7] = [
|
||||
("ui.view.explorer", Panel::Explorer),
|
||||
("ui.view.properties", Panel::Properties),
|
||||
("ui.view.console", Panel::Console),
|
||||
("ui.view.3d", Panel::View3d),
|
||||
("ui.view.2d", Panel::View2d),
|
||||
("ui.view.library", Panel::Library),
|
||||
("ui.view.history", Panel::History),
|
||||
];
|
||||
|
||||
/// The panel a Windows menu item toggles
|
||||
pub fn view_panel(id: &str) -> Option<Panel> {
|
||||
VIEWS.iter().find(|(v, _)| *v == id).map(|(_, p)| *p)
|
||||
}
|
||||
|
||||
impl Panel {
|
||||
pub const ALL: [Panel; 8] =
|
||||
[Panel::Graph, Panel::Explorer, Panel::Library, Panel::View3d, Panel::View2d, Panel::Properties, Panel::Console, Panel::History];
|
||||
|
||||
pub fn name(self) -> &'static str {
|
||||
match self {
|
||||
Panel::Graph => "Graph",
|
||||
Panel::Explorer => "Explorer",
|
||||
Panel::Library => "Library",
|
||||
Panel::View3d => "3D View",
|
||||
Panel::View2d => "2D View",
|
||||
Panel::Properties => "Properties",
|
||||
Panel::Console => "Console",
|
||||
Panel::History => "History",
|
||||
}
|
||||
}
|
||||
|
||||
/// Initial floating rectangle in points: `[x, y, width, height]`
|
||||
pub(super) fn float_rect(self) -> Option<[f32; 4]> {
|
||||
let slot = match self {
|
||||
Panel::Console => 0.0,
|
||||
Panel::History => 1.0,
|
||||
_ => return None,
|
||||
};
|
||||
Some([900.0, 120.0 + 50.0 * slot, 420.0, 320.0])
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,65 @@
|
||||
use craft_ui::docking::{DockContent, PanelLimits, Permissions};
|
||||
use egui::{Margin, RichText, Ui, vec2};
|
||||
|
||||
use super::{Panel, permissions};
|
||||
use crate::{MaterialCraftApp, i18n::tr};
|
||||
|
||||
/// Panel bodies, titles and sizing constraints
|
||||
pub(super) struct PanelContent<'a> {
|
||||
pub(super) app: &'a mut MaterialCraftApp,
|
||||
}
|
||||
|
||||
impl DockContent<Panel> for PanelContent<'_> {
|
||||
fn body(&mut self, ui: &mut Ui, panel: &Panel) {
|
||||
let app = &mut *self.app;
|
||||
if app.ui.dock.maximized().is_none() && ui.rect_contains_pointer(ui.max_rect()) && super::maximization::consume_shortcut(ui.ctx()) {
|
||||
if let Err(error) = app.ui.dock.maximize(*panel) {
|
||||
log::warn!("panel was not maximized: {error}");
|
||||
}
|
||||
ui.ctx().request_repaint();
|
||||
}
|
||||
|
||||
match panel {
|
||||
Panel::Graph => crate::graph::show(app, ui),
|
||||
Panel::View3d => crate::view3d::show(app, ui),
|
||||
Panel::View2d => crate::view2d::show(app, ui),
|
||||
_ => {
|
||||
egui::Frame::new().inner_margin(Margin::symmetric(6, 4)).show(ui, |ui| match panel {
|
||||
Panel::Explorer => crate::explorer::show(app, ui),
|
||||
Panel::Library => crate::library::show(app, ui),
|
||||
Panel::Properties => crate::properties::show(app, ui),
|
||||
Panel::Console => crate::windows::console(app, ui),
|
||||
Panel::History => crate::windows::history(app, ui),
|
||||
_ => {}
|
||||
});
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fn logical_label(&self, panel: &Panel) -> String {
|
||||
match panel {
|
||||
Panel::Properties => crate::properties::title(self.app),
|
||||
Panel::Graph => self.app.session.graph().map(|g| format!("{} - {}", g.name, tr("Graph"))).unwrap_or_else(|_| tr("Graph").into()),
|
||||
Panel::View3d => format!("{} - {}", crate::view3d::scene_label(self.app), tr("3D View")),
|
||||
Panel::View2d => crate::view2d::title(self.app),
|
||||
p => tr(p.name()).to_string(),
|
||||
}
|
||||
}
|
||||
|
||||
fn label(&mut self, _ui: &Ui, _panel: &Panel, logical: &str, font: &egui::FontId, color: egui::Color32) -> egui::WidgetText {
|
||||
RichText::new(logical.to_uppercase()).font(font.clone()).strong().color(color).into()
|
||||
}
|
||||
|
||||
fn permissions(&self, panel: &Panel) -> Permissions {
|
||||
permissions(panel)
|
||||
}
|
||||
|
||||
fn limits(&self, panel: &Panel) -> PanelLimits {
|
||||
let min = if *panel == Panel::Graph { vec2(240.0, 160.0) } else { vec2(120.0, 60.0) };
|
||||
PanelLimits { min, ..PanelLimits::default() }
|
||||
}
|
||||
|
||||
fn floating_size(&self, _panel: &Panel) -> Option<egui::Vec2> {
|
||||
Some(vec2(420.0, 320.0))
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,81 @@
|
||||
use craft_ui::docking::{Layout, Location, Node, Permissions, Placement};
|
||||
use craft_ui::layout::{SplitAxis, SplitSize};
|
||||
|
||||
use super::Panel;
|
||||
|
||||
/// The saved panel arrangement
|
||||
pub type Workspace = craft_ui::docking::Workspace<Panel>;
|
||||
|
||||
/// The graph stays docked and separate from other tabs
|
||||
pub fn permissions(panel: &Panel) -> Permissions {
|
||||
if *panel == Panel::Graph { Permissions { accepts_splits: true, ..Permissions::PROTECTED } } else { Permissions::default() }
|
||||
}
|
||||
|
||||
fn tabs(panels: &[Panel]) -> Node<Panel> {
|
||||
Node::Tabs { panels: panels.to_vec(), active: 0 }
|
||||
}
|
||||
|
||||
fn split(axis: SplitAxis, ratio: f32, first: Node<Panel>, second: Node<Panel>) -> Node<Panel> {
|
||||
Node::Split { axis, size: SplitSize::Ratio(ratio), first: Box::new(first), second: Box::new(second) }
|
||||
}
|
||||
|
||||
/// Default workspace with console and history initially hidden
|
||||
pub fn default_workspace() -> Workspace {
|
||||
use Panel::*;
|
||||
let left = split(SplitAxis::Vertical, 0.36, tabs(&[Explorer]), tabs(&[Library]));
|
||||
let views = split(SplitAxis::Horizontal, 0.5, tabs(&[View3d]), tabs(&[View2d]));
|
||||
let center = split(SplitAxis::Vertical, 0.52, tabs(&[Graph]), views);
|
||||
let root = split(SplitAxis::Horizontal, 0.15, left, split(SplitAxis::Horizontal, 0.8, center, tabs(&[Properties])));
|
||||
let mut workspace = Workspace::new(Layout { root: Some(root), floating: Vec::new() });
|
||||
for panel in Panel::ALL {
|
||||
if let Some(rect) = panel.float_rect() {
|
||||
let location = Location {
|
||||
floating: Some(rect),
|
||||
anchor: None,
|
||||
placement: Placement::Tab { before: None },
|
||||
size: None,
|
||||
stack: None,
|
||||
sibling: Vec::new(),
|
||||
group: None,
|
||||
};
|
||||
workspace.hidden.push((panel, location));
|
||||
}
|
||||
}
|
||||
workspace
|
||||
}
|
||||
|
||||
/// Validate the workspace and protect the central graph panel
|
||||
pub fn validate(workspace: &Workspace) -> Result<(), String> {
|
||||
workspace.validate().map_err(|error| error.to_string())?;
|
||||
let layout = &workspace.layout;
|
||||
if layout.floating.iter().any(|window| window.contains(&Panel::Graph)) {
|
||||
return Err("The graph cannot float".into());
|
||||
}
|
||||
if workspace.hidden.iter().any(|(panel, _)| *panel == Panel::Graph) {
|
||||
return Err("The graph cannot be hidden".into());
|
||||
}
|
||||
let mut found = false;
|
||||
let mut nodes: Vec<&Node<Panel>> = layout.root.iter().collect();
|
||||
while let Some(node) = nodes.pop() {
|
||||
match node {
|
||||
Node::Split { first, second, .. } => {
|
||||
nodes.push(first);
|
||||
nodes.push(second);
|
||||
}
|
||||
Node::Tabs { panels, .. } if panels.contains(&Panel::Graph) => {
|
||||
if panels.len() != 1 {
|
||||
return Err("The graph cannot share a tab group".into());
|
||||
}
|
||||
found = true;
|
||||
}
|
||||
Node::Stack { entries } if entries.iter().any(|entry| entry.panel == Panel::Graph) => {
|
||||
return Err("The graph cannot be collapsed".into());
|
||||
}
|
||||
Node::Dock { columns, .. } if columns.iter().flat_map(|column| &column.groups).any(|group| group.panels.contains(&Panel::Graph)) => {
|
||||
return Err("The graph cannot be in a dock".into());
|
||||
}
|
||||
_ => {}
|
||||
}
|
||||
}
|
||||
if found { Ok(()) } else { Err("The panel layout must contain the graph".into()) }
|
||||
}
|
||||
@@ -16,6 +16,8 @@ pub mod library;
|
||||
mod material_preview_menu;
|
||||
mod menu_item;
|
||||
pub mod menus;
|
||||
mod new_graph_dialog;
|
||||
pub mod preferences;
|
||||
mod preview_resolution;
|
||||
#[path = "property/mod.rs"]
|
||||
pub mod properties;
|
||||
|
||||
@@ -15,6 +15,7 @@ pub struct MaterialCraftApp {
|
||||
pub cooker: cook::Cooker,
|
||||
/// Node output thumbnails and library previews
|
||||
pub thumbs: thumbs::Thumbs,
|
||||
pub(crate) template_previews: windows::TemplatePreviews,
|
||||
/// The graph editor's gesture state
|
||||
pub graph: graph::GraphView,
|
||||
pub view3d: view3d::View3dState,
|
||||
@@ -68,6 +69,7 @@ impl MaterialCraftApp {
|
||||
toasts: Vec::new(),
|
||||
cooker: cook::Cooker::default(),
|
||||
thumbs: thumbs::Thumbs::default(),
|
||||
template_previews: windows::TemplatePreviews::default(),
|
||||
graph: graph::GraphView::default(),
|
||||
view3d: view3d::View3dState::default(),
|
||||
view2d: view2d::View2dState::default(),
|
||||
|
||||
@@ -79,6 +79,7 @@ pub const CATALOG: &[MenuItem] = &[
|
||||
it("Windows", "Library", "ui.view.library", None),
|
||||
it("Windows", "History", "ui.view.history", None),
|
||||
sep("Windows"),
|
||||
it("Windows", "Restore panel layout", "ui.unmaximize", Some("Shift+Space")),
|
||||
it("Windows", "Reset layout", "ui.resetLayout", None),
|
||||
it("Help", "Home screen...", "ui.home", None),
|
||||
it("Help", "Documentation...", "ui.help.docs", None),
|
||||
@@ -110,7 +111,7 @@ pub fn enabled(app: &MaterialCraftApp, id: &str) -> bool {
|
||||
}
|
||||
|
||||
if is_ui(id) {
|
||||
return true;
|
||||
return id != "ui.unmaximize" || app.ui.dock.maximized().is_some();
|
||||
}
|
||||
materialcraft_engine::find(id).is_some_and(|c| (c.enabled)(&app.session).is_ok())
|
||||
}
|
||||
@@ -148,9 +149,10 @@ pub fn invoke(app: &mut MaterialCraftApp, ctx: &egui::Context, id: &str) {
|
||||
"ui.export" => app.ui.windows.export = true,
|
||||
"ui.quit" => ctx.send_viewport_cmd(egui::ViewportCommand::Close),
|
||||
"ui.preferences" => app.ui.windows.preferences = true,
|
||||
"ui.view.graph" => {}
|
||||
"ui.view.graph" => app.ui.dock.focus(crate::docking::Panel::Graph),
|
||||
"ui.unmaximize" => app.ui.dock.restore(),
|
||||
"ui.resetLayout" => app.ui.dock = crate::docking::Dock::default(),
|
||||
// These replace the open package: ask first when it has unsaved changes.
|
||||
// Replacing the open package needs confirmation for unsaved changes
|
||||
"ui.closeAll" | "file.newPackage" => crate::unsaved::guard(app, crate::unsaved::Guarded::Menu { id: id.to_string() }),
|
||||
"ui.reloadResources" | "ui.clearCache" => {
|
||||
if let Ok(mut c) = app.session.cache.lock() {
|
||||
@@ -287,7 +289,9 @@ pub fn shortcuts(app: &mut MaterialCraftApp, ctx: &egui::Context) {
|
||||
}
|
||||
}
|
||||
|
||||
let mut table: Vec<(&'static str, KeyboardShortcut)> = CATALOG.iter().filter_map(|i| Some((i.id, parse_shortcut(i.shortcut?)?))).collect();
|
||||
// The dock handles Shift+Space with the current panel's hit test
|
||||
let mut table: Vec<(&'static str, KeyboardShortcut)> =
|
||||
CATALOG.iter().filter(|item| item.id != "ui.unmaximize").filter_map(|item| Some((item.id, parse_shortcut(item.shortcut?)?))).collect();
|
||||
for c in materialcraft_engine::command_specs() {
|
||||
if table.iter().any(|(id, _)| *id == c.id) {
|
||||
continue;
|
||||
|
||||
@@ -0,0 +1,136 @@
|
||||
use egui::{Color32, RichText, Ui, vec2};
|
||||
use egui_phosphor::regular as icon;
|
||||
use materialcraft_engine::{core::GraphKind, samples::TEMPLATES};
|
||||
use serde_json::json;
|
||||
|
||||
use crate::{MaterialCraftApp, i18n::tr, theme::Tokens};
|
||||
|
||||
pub(crate) fn show(app: &mut MaterialCraftApp, context: &egui::Context) {
|
||||
let mut open = true;
|
||||
let mut create = false;
|
||||
crate::windows::modal(context, "new-graph", tr("New graph"), &mut open, vec2(660.0, 330.0), |ui| {
|
||||
ui.horizontal(|ui| {
|
||||
ui.selectable_value(&mut app.ui.new_graph_kind, GraphKind::Material, tr("Graph"));
|
||||
ui.selectable_value(&mut app.ui.new_graph_kind, GraphKind::Function, tr("Function Graph"));
|
||||
});
|
||||
ui.add_space(10.0);
|
||||
ui.horizontal_top(|ui| {
|
||||
if app.ui.new_graph_kind == GraphKind::Material {
|
||||
ui.vertical(|ui| {
|
||||
ui.set_width(320.0);
|
||||
ui.label(RichText::new(tr("Templates")).strong());
|
||||
ui.horizontal(|ui| {
|
||||
for (template, label) in TEMPLATES {
|
||||
template_tile(app, ui, template, label);
|
||||
}
|
||||
});
|
||||
ui.add_space(8.0);
|
||||
ui.label(tr(template_description(&app.ui.new_graph_template)));
|
||||
});
|
||||
ui.separator();
|
||||
}
|
||||
ui.vertical(|ui| {
|
||||
ui.set_width(280.0);
|
||||
ui.label(RichText::new(tr("Graph name")).strong());
|
||||
let name = ui.text_edit_singleline(&mut app.ui.new_graph_name);
|
||||
crate::widgets::name(&name, egui::Role::TextInput, "Graph name");
|
||||
if app.ui.new_graph_kind == GraphKind::Material {
|
||||
ui.add_space(10.0);
|
||||
dimensions(app, ui);
|
||||
}
|
||||
ui.add_space(12.0);
|
||||
ui.label(format!("{}: {}", tr("Package"), app.session.pkg.name));
|
||||
ui.add_space(16.0);
|
||||
ui.horizontal(|ui| {
|
||||
create = ui.add(crate::widgets::primary_button(ui, tr("Create"))).clicked();
|
||||
if ui.button(tr("Cancel")).clicked() {
|
||||
app.ui.windows.new_graph = false;
|
||||
}
|
||||
});
|
||||
});
|
||||
});
|
||||
});
|
||||
|
||||
if create {
|
||||
let mut parameters = json!({
|
||||
"kind": app.ui.new_graph_kind,
|
||||
"template": app.ui.new_graph_template,
|
||||
"name": app.ui.new_graph_name,
|
||||
"size": app.ui.new_graph_size,
|
||||
});
|
||||
if app.ui.new_graph_kind == GraphKind::Material {
|
||||
let height = if app.ui.new_graph_link { app.ui.new_graph_size } else { app.ui.new_graph_height };
|
||||
parameters["height"] = json!(height);
|
||||
}
|
||||
if app.run("file.new", parameters).is_some() {
|
||||
app.ui.frame_all = true;
|
||||
open = false;
|
||||
}
|
||||
}
|
||||
if !open {
|
||||
app.ui.windows.new_graph = false;
|
||||
}
|
||||
}
|
||||
|
||||
fn dimensions(app: &mut MaterialCraftApp, ui: &mut Ui) {
|
||||
if app.ui.new_graph_link {
|
||||
app.ui.new_graph_height = app.ui.new_graph_size;
|
||||
}
|
||||
ui.horizontal(|ui| {
|
||||
size_picker(ui, "Width", &mut app.ui.new_graph_size);
|
||||
let linked = app.ui.new_graph_link;
|
||||
if crate::widgets::icon_button(ui, if linked { icon::LINK } else { icon::LINK_BREAK }, tr("Link width and height"), linked, 22.0).clicked() {
|
||||
app.ui.new_graph_link = !linked;
|
||||
}
|
||||
if app.ui.new_graph_link {
|
||||
app.ui.new_graph_height = app.ui.new_graph_size;
|
||||
}
|
||||
ui.add_enabled_ui(!app.ui.new_graph_link, |ui| size_picker(ui, "Height", &mut app.ui.new_graph_height));
|
||||
});
|
||||
}
|
||||
|
||||
fn size_picker(ui: &mut Ui, label: &str, pixels: &mut u32) {
|
||||
ui.vertical(|ui| {
|
||||
ui.label(tr(label));
|
||||
let response = egui::ComboBox::from_id_salt(label).width(100.0).selected_text(format!("{pixels} px")).show_ui(ui, |ui| {
|
||||
for size in [16, 32, 64, 128, 256, 512, 1024, 2048, 4096, 8192] {
|
||||
ui.selectable_value(pixels, size, format!("{size} px"));
|
||||
}
|
||||
});
|
||||
crate::widgets::name(&response.response, egui::Role::ComboBox, label);
|
||||
});
|
||||
}
|
||||
|
||||
fn template_description(template: &str) -> &'static str {
|
||||
match template {
|
||||
"empty" => "Start with an empty graph and add nodes from the library.",
|
||||
"pbr" => "Uniform inputs connected to six material outputs: base color, normal, roughness, metallic, height and ambient occlusion.",
|
||||
"atomics" => "An original sample combining a value input, function, pixel processor, pattern graph and blur.",
|
||||
_ => "Choose a graph template.",
|
||||
}
|
||||
}
|
||||
|
||||
fn template_tile(app: &mut MaterialCraftApp, ui: &mut Ui, template: &str, label: &str) {
|
||||
let tokens = Tokens::get(ui.ctx());
|
||||
let selected = app.ui.new_graph_template == template;
|
||||
let (rectangle, response) = ui.allocate_exact_size(vec2(100.0, 124.0), egui::Sense::click());
|
||||
crate::widgets::name(&response, egui::Role::ListItem, label);
|
||||
if selected || response.hovered() {
|
||||
ui.painter().rect_filled(rectangle, 6.0, if selected { tokens.row_selected } else { tokens.row_hover });
|
||||
}
|
||||
if selected {
|
||||
ui.painter().rect_stroke(rectangle, 6.0, egui::Stroke::new(1.5, tokens.accent), egui::StrokeKind::Inside);
|
||||
}
|
||||
let image = egui::Rect::from_min_size(rectangle.min + vec2(10.0, 6.0), vec2(80.0, 80.0));
|
||||
if let Some(texture) = crate::windows::template_preview(app, ui.ctx(), template) {
|
||||
ui.painter().image(texture, image, egui::Rect::from_min_max(egui::Pos2::ZERO, egui::pos2(1.0, 1.0)), Color32::WHITE);
|
||||
} else {
|
||||
ui.painter().circle_filled(image.center(), 36.0, tokens.row);
|
||||
ui.painter().text(image.center(), egui::Align2::CENTER_CENTER, icon::TREE_STRUCTURE, egui::FontId::proportional(28.0), tokens.text_dim);
|
||||
}
|
||||
let caption = ui.painter().layout(tr(label).to_string(), egui::FontId::proportional(11.0), tokens.text, 96.0);
|
||||
ui.painter().galley(egui::pos2(rectangle.center().x - caption.size().x * 0.5, image.bottom() + 6.0), caption, tokens.text);
|
||||
if response.clicked() {
|
||||
app.ui.new_graph_template = template.into();
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,79 @@
|
||||
mod preference_tab;
|
||||
pub use preference_tab::PreferenceTab;
|
||||
|
||||
use egui::{Ui, vec2};
|
||||
|
||||
use crate::{
|
||||
MaterialCraftApp,
|
||||
i18n::tr,
|
||||
state::Prefs,
|
||||
theme::{Accent, Brightness},
|
||||
};
|
||||
|
||||
pub(crate) fn show(app: &mut MaterialCraftApp, context: &egui::Context) {
|
||||
let mut open = true;
|
||||
crate::windows::modal(context, "prefs", tr("Preferences"), &mut open, vec2(560.0, 360.0), |ui| {
|
||||
ui.horizontal_top(|ui| {
|
||||
ui.vertical(|ui| {
|
||||
ui.set_width(110.0);
|
||||
for tab in PreferenceTab::ALL {
|
||||
let response = ui.selectable_value(&mut app.ui.preferences_tab, tab, tr(tab.label()));
|
||||
crate::widgets::name(&response, egui::Role::Tab, tab.label());
|
||||
}
|
||||
});
|
||||
ui.separator();
|
||||
ui.vertical(|ui| {
|
||||
ui.set_width(410.0);
|
||||
match app.ui.preferences_tab {
|
||||
PreferenceTab::General => general(&mut app.ui.prefs, ui),
|
||||
PreferenceTab::Graph => graph(&mut app.ui.prefs, ui),
|
||||
PreferenceTab::View3d => view3d(&mut app.ui.prefs, ui),
|
||||
}
|
||||
});
|
||||
});
|
||||
});
|
||||
if !open {
|
||||
app.ui.windows.preferences = false;
|
||||
}
|
||||
}
|
||||
|
||||
fn general(preferences: &mut Prefs, ui: &mut Ui) {
|
||||
let current_language = crate::i18n::current();
|
||||
crate::widgets::combo(ui, tr("Language"), current_language.name, |ui| {
|
||||
for language in &crate::i18n::LANGUAGES {
|
||||
if ui.selectable_label(preferences.language == language.code, language.name).clicked() {
|
||||
preferences.language = language.code.to_owned();
|
||||
crate::i18n::set_language(&preferences.language);
|
||||
}
|
||||
}
|
||||
});
|
||||
crate::widgets::combo(ui, tr("Brightness"), tr(preferences.brightness.label()), |ui| {
|
||||
for brightness in Brightness::ALL {
|
||||
ui.selectable_value(&mut preferences.brightness, brightness, tr(brightness.label()));
|
||||
}
|
||||
});
|
||||
crate::widgets::combo(ui, tr("Accent color"), tr(preferences.accent.label()), |ui| {
|
||||
for accent in Accent::ALL {
|
||||
ui.selectable_value(&mut preferences.accent, accent, tr(accent.label()));
|
||||
}
|
||||
});
|
||||
crate::widgets::slider(ui, tr("Interface scale"), &mut preferences.ui_scale, 0.75..=2.0, 2);
|
||||
let mut autosave_minutes = preferences.autosave_minutes as f32;
|
||||
if crate::widgets::slider(ui, tr("Autosave every (minutes, 0 = off)"), &mut autosave_minutes, 0.0..=60.0, 0).changed() {
|
||||
preferences.autosave_minutes = autosave_minutes.round() as u32;
|
||||
}
|
||||
ui.checkbox(&mut preferences.show_home, tr("Show at startup"));
|
||||
}
|
||||
|
||||
fn graph(preferences: &mut Prefs, ui: &mut Ui) {
|
||||
crate::widgets::combo(ui, tr("Preview size while editing"), crate::preview_resolution::label(preferences.preview_size), |ui| {
|
||||
crate::preview_resolution::choices(ui, &mut preferences.preview_size);
|
||||
});
|
||||
ui.checkbox(&mut preferences.thumbnails, tr("Show node thumbnails"));
|
||||
ui.checkbox(&mut preferences.snap_to_grid, tr("Snap to grid"));
|
||||
}
|
||||
|
||||
fn view3d(preferences: &mut Prefs, ui: &mut Ui) {
|
||||
crate::widgets::slider(ui, tr("3D pan limit (mesh radii)"), &mut preferences.camera.pan_limit, 0.0..=20.0, 1);
|
||||
crate::widgets::slider(ui, tr("3D pan speed"), &mut preferences.camera.pan_speed, 0.1..=4.0, 2);
|
||||
}
|
||||
@@ -0,0 +1,19 @@
|
||||
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
|
||||
pub enum PreferenceTab {
|
||||
#[default]
|
||||
General,
|
||||
Graph,
|
||||
View3d,
|
||||
}
|
||||
|
||||
impl PreferenceTab {
|
||||
pub const ALL: [Self; 3] = [Self::General, Self::Graph, Self::View3d];
|
||||
|
||||
pub fn label(self) -> &'static str {
|
||||
match self {
|
||||
Self::General => "General",
|
||||
Self::Graph => "Graph",
|
||||
Self::View3d => "3D View",
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -21,6 +21,10 @@ pub struct UiState {
|
||||
pub new_graph_template: String,
|
||||
pub new_graph_name: String,
|
||||
pub new_graph_size: u32,
|
||||
pub new_graph_height: u32,
|
||||
pub new_graph_link: bool,
|
||||
#[serde(skip)]
|
||||
pub preferences_tab: crate::preferences::PreferenceTab,
|
||||
/// Export dialog fields
|
||||
pub export_dir: String,
|
||||
pub export_format: String,
|
||||
@@ -48,6 +52,9 @@ impl Default for UiState {
|
||||
new_graph_template: "pbr".into(),
|
||||
new_graph_name: "New_graph".into(),
|
||||
new_graph_size: 1024,
|
||||
new_graph_height: 1024,
|
||||
new_graph_link: true,
|
||||
preferences_tab: crate::preferences::PreferenceTab::default(),
|
||||
export_dir: String::new(),
|
||||
export_format: "png".into(),
|
||||
export_depth: 0,
|
||||
|
||||
+10
-163
@@ -1,9 +1,6 @@
|
||||
//! Dialogs (new graph, export outputs, preferences, shortcuts, about, home), the console and history panels, file actions behind the File menu, and the function editor
|
||||
|
||||
use std::collections::HashMap;
|
||||
use std::sync::mpsc::Receiver;
|
||||
|
||||
use egui::{Color32, RichText, TextureHandle, Ui, vec2};
|
||||
use egui::{Color32, RichText, Ui, vec2};
|
||||
use egui_phosphor::regular as icon;
|
||||
use materialcraft_engine::core::FunctionGraph;
|
||||
use materialcraft_engine::core::NodeId;
|
||||
@@ -12,79 +9,25 @@ use serde_json::{Value, json};
|
||||
|
||||
use crate::MaterialCraftApp;
|
||||
use crate::i18n::tr;
|
||||
use crate::theme::{Accent, Brightness, Tokens};
|
||||
use crate::theme::Tokens;
|
||||
|
||||
/// Template previews for the New graph dialog (rendered in the background on first open)
|
||||
#[derive(Default)]
|
||||
pub struct TemplatePreviews {
|
||||
tex: HashMap<String, TextureHandle>,
|
||||
rx: Option<Receiver<crate::thumbs::Previews>>,
|
||||
started: bool,
|
||||
}
|
||||
mod template_previews;
|
||||
pub(crate) use template_previews::TemplatePreviews;
|
||||
|
||||
const PREVIEW: u32 = 96;
|
||||
|
||||
fn render_templates() -> crate::thumbs::Previews {
|
||||
let light = materialcraft_render::Lighting::new("studio");
|
||||
let scene = materialcraft_render::Scene::builtin("sphere");
|
||||
let settings = materialcraft_render::Settings { distance: 2.7, supersample: 2, ..Default::default() };
|
||||
materialcraft_engine::samples::TEMPLATES
|
||||
.iter()
|
||||
.filter_map(|(id, _)| {
|
||||
let mut s = materialcraft_engine::Session::new(materialcraft_engine::core::Package::new("t"));
|
||||
s.pkg.graphs.push(materialcraft_engine::samples::template(id, "t", 8).ok()?);
|
||||
s.preview_size = Some(256);
|
||||
s.cook();
|
||||
let maps = materialcraft_render::Maps::from_usages(s.material_maps());
|
||||
Some((id.to_string(), materialcraft_render::render(&scene, &maps, &light, &settings, PREVIEW, PREVIEW)))
|
||||
})
|
||||
.collect()
|
||||
}
|
||||
|
||||
impl TemplatePreviews {
|
||||
fn get(&mut self, ctx: &egui::Context, id: &str) -> Option<egui::TextureId> {
|
||||
if !self.started {
|
||||
self.started = true;
|
||||
let (tx, rx) = std::sync::mpsc::channel();
|
||||
#[cfg(not(target_arch = "wasm32"))]
|
||||
{
|
||||
let c = ctx.clone();
|
||||
let _ = std::thread::Builder::new().name("materialcraft-templates".into()).spawn(move || {
|
||||
let _ = tx.send(render_templates());
|
||||
c.request_repaint();
|
||||
});
|
||||
}
|
||||
#[cfg(target_arch = "wasm32")]
|
||||
let _ = tx.send(render_templates());
|
||||
self.rx = Some(rx);
|
||||
}
|
||||
if let Some(rx) = &self.rx
|
||||
&& let Ok(list) = rx.try_recv()
|
||||
{
|
||||
for (k, px) in list {
|
||||
let img = egui::ColorImage::from_rgba_unmultiplied([PREVIEW as usize, PREVIEW as usize], &px);
|
||||
self.tex.insert(k.clone(), ctx.load_texture(format!("tpl-{k}"), img, egui::TextureOptions::LINEAR));
|
||||
}
|
||||
self.rx = None;
|
||||
}
|
||||
self.tex.get(id).map(TextureHandle::id)
|
||||
}
|
||||
}
|
||||
|
||||
thread_local! {
|
||||
static TEMPLATES: std::cell::RefCell<TemplatePreviews> = std::cell::RefCell::new(TemplatePreviews::default());
|
||||
pub(crate) fn template_preview(app: &mut MaterialCraftApp, context: &egui::Context, template: &str) -> Option<egui::TextureId> {
|
||||
app.template_previews.get(context, template)
|
||||
}
|
||||
|
||||
pub fn show(app: &mut MaterialCraftApp, ctx: &egui::Context) {
|
||||
app.thumbs.tick(ctx);
|
||||
if app.ui.windows.new_graph {
|
||||
new_graph(app, ctx);
|
||||
crate::new_graph_dialog::show(app, ctx);
|
||||
}
|
||||
if app.ui.windows.export {
|
||||
export(app, ctx);
|
||||
}
|
||||
if app.ui.windows.preferences {
|
||||
preferences(app, ctx);
|
||||
crate::preferences::show(app, ctx);
|
||||
}
|
||||
if app.ui.windows.about {
|
||||
about(app, ctx);
|
||||
@@ -98,7 +41,7 @@ pub fn show(app: &mut MaterialCraftApp, ctx: &egui::Context) {
|
||||
crate::unsaved::show(app, ctx);
|
||||
}
|
||||
|
||||
fn modal(ctx: &egui::Context, id: &str, title: &str, open: &mut bool, size: egui::Vec2, body: impl FnOnce(&mut Ui)) {
|
||||
pub(crate) fn modal(ctx: &egui::Context, id: &str, title: &str, open: &mut bool, size: egui::Vec2, body: impl FnOnce(&mut Ui)) {
|
||||
egui::Window::new(title)
|
||||
.id(egui::Id::unique(id))
|
||||
.open(open)
|
||||
@@ -110,62 +53,6 @@ fn modal(ctx: &egui::Context, id: &str, title: &str, open: &mut bool, size: egui
|
||||
.show(ctx, body);
|
||||
}
|
||||
|
||||
fn new_graph(app: &mut MaterialCraftApp, ctx: &egui::Context) {
|
||||
use materialcraft_engine::core::GraphKind;
|
||||
|
||||
let mut open = true;
|
||||
let mut create = false;
|
||||
modal(ctx, "new-graph", tr("New graph"), &mut open, vec2(440.0, 290.0), |ui| {
|
||||
ui.horizontal(|ui| {
|
||||
ui.selectable_value(&mut app.ui.new_graph_kind, GraphKind::Material, tr("Graph"));
|
||||
ui.selectable_value(&mut app.ui.new_graph_kind, GraphKind::Function, tr("Function Graph"));
|
||||
});
|
||||
ui.add_space(12.0);
|
||||
ui.label(tr("Graph name"));
|
||||
let name = ui.text_edit_singleline(&mut app.ui.new_graph_name);
|
||||
crate::widgets::name(&name, egui::Role::TextInput, "Graph name");
|
||||
|
||||
if app.ui.new_graph_kind == GraphKind::Material {
|
||||
ui.add_space(8.0);
|
||||
crate::widgets::combo(ui, tr("Template"), app.ui.new_graph_template.clone(), |ui| {
|
||||
for (id, label) in materialcraft_engine::samples::TEMPLATES {
|
||||
ui.selectable_value(&mut app.ui.new_graph_template, id.to_string(), tr(label));
|
||||
}
|
||||
});
|
||||
let size = egui::ComboBox::from_label(tr("Size")).selected_text(format!("{} px", app.ui.new_graph_size)).show_ui(ui, |ui| {
|
||||
for size in [256u32, 512, 1024, 2048, 4096] {
|
||||
ui.selectable_value(&mut app.ui.new_graph_size, size, format!("{size} px"));
|
||||
}
|
||||
});
|
||||
crate::widgets::name(&size.response, egui::Role::ComboBox, "Size");
|
||||
}
|
||||
|
||||
ui.add_space(12.0);
|
||||
ui.label(format!("{}: {}", tr("Package"), app.session.pkg.name));
|
||||
ui.add_space(16.0);
|
||||
ui.horizontal(|ui| {
|
||||
if ui.add(crate::widgets::primary_button(ui, tr("Create"))).clicked() {
|
||||
create = true;
|
||||
}
|
||||
if ui.button(tr("Cancel")).clicked() {
|
||||
app.ui.windows.new_graph = false;
|
||||
}
|
||||
});
|
||||
});
|
||||
|
||||
if create {
|
||||
let parameters =
|
||||
json!({"kind": app.ui.new_graph_kind, "template": app.ui.new_graph_template, "name": app.ui.new_graph_name, "size": app.ui.new_graph_size});
|
||||
if app.run("file.new", parameters).is_some() {
|
||||
app.ui.frame_all = true;
|
||||
open = false;
|
||||
}
|
||||
}
|
||||
if !open {
|
||||
app.ui.windows.new_graph = false;
|
||||
}
|
||||
}
|
||||
|
||||
fn export(app: &mut MaterialCraftApp, ctx: &egui::Context) {
|
||||
let mut open = true;
|
||||
let mut go = false;
|
||||
@@ -255,46 +142,6 @@ fn export(app: &mut MaterialCraftApp, ctx: &egui::Context) {
|
||||
}
|
||||
}
|
||||
|
||||
fn preferences(app: &mut MaterialCraftApp, ctx: &egui::Context) {
|
||||
let mut open = true;
|
||||
modal(ctx, "prefs", tr("Preferences"), &mut open, vec2(380.0, 340.0), |ui| {
|
||||
let p = &mut app.ui.prefs;
|
||||
let current_lang = crate::i18n::current();
|
||||
crate::widgets::combo(ui, tr("Language"), current_lang.name, |ui| {
|
||||
for l in &crate::i18n::LANGUAGES {
|
||||
if ui.selectable_label(p.language == l.code, l.name).clicked() {
|
||||
p.language = l.code.to_owned();
|
||||
crate::i18n::set_language(&p.language);
|
||||
}
|
||||
}
|
||||
});
|
||||
crate::widgets::combo(ui, tr("Brightness"), tr(p.brightness.label()), |ui| {
|
||||
for b in Brightness::ALL {
|
||||
ui.selectable_value(&mut p.brightness, b, tr(b.label()));
|
||||
}
|
||||
});
|
||||
crate::widgets::combo(ui, tr("Accent color"), tr(p.accent.label()), |ui| {
|
||||
for a in Accent::ALL {
|
||||
ui.selectable_value(&mut p.accent, a, tr(a.label()));
|
||||
}
|
||||
});
|
||||
crate::widgets::slider(ui, tr("Interface scale"), &mut p.ui_scale, 0.75..=2.0, 2);
|
||||
let mut auto = p.autosave_minutes as f32;
|
||||
if crate::widgets::slider(ui, tr("Autosave every (minutes, 0 = off)"), &mut auto, 0.0..=60.0, 0).changed() {
|
||||
p.autosave_minutes = auto.round() as u32;
|
||||
}
|
||||
crate::widgets::combo(ui, tr("Preview size while editing"), crate::preview_resolution::label(p.preview_size), |ui| {
|
||||
crate::preview_resolution::choices(ui, &mut p.preview_size);
|
||||
});
|
||||
ui.checkbox(&mut p.thumbnails, tr("Show node thumbnails"));
|
||||
crate::widgets::slider(ui, tr("3D pan limit (mesh radii)"), &mut p.camera.pan_limit, 0.0..=20.0, 1);
|
||||
crate::widgets::slider(ui, tr("3D pan speed"), &mut p.camera.pan_speed, 0.1..=4.0, 2);
|
||||
});
|
||||
if !open {
|
||||
app.ui.windows.preferences = false;
|
||||
}
|
||||
}
|
||||
|
||||
fn about(app: &mut MaterialCraftApp, ctx: &egui::Context) {
|
||||
let mut open = true;
|
||||
modal(ctx, "about", tr("About MaterialCraft"), &mut open, vec2(400.0, 260.0), |ui| {
|
||||
@@ -393,7 +240,7 @@ fn home(app: &mut MaterialCraftApp, ctx: &egui::Context) {
|
||||
ui.painter().rect_filled(r, 6.0, tk.row_hover);
|
||||
}
|
||||
let img = egui::Rect::from_min_size(r.min + vec2(6.0, 4.0), vec2(80.0, 80.0));
|
||||
match TEMPLATES.with(|t| t.borrow_mut().get(ui.ctx(), id)) {
|
||||
match template_preview(app, ui.ctx(), id) {
|
||||
Some(t) => {
|
||||
ui.painter().image(t, img, egui::Rect::from_min_max(egui::Pos2::ZERO, egui::pos2(1.0, 1.0)), Color32::WHITE);
|
||||
}
|
||||
|
||||
@@ -0,0 +1,61 @@
|
||||
use std::{collections::HashMap, sync::mpsc::Receiver};
|
||||
|
||||
use egui::TextureHandle;
|
||||
|
||||
/// Procedural template thumbnails owned by one app and its texture manager
|
||||
#[derive(Default)]
|
||||
pub struct TemplatePreviews {
|
||||
textures: HashMap<String, TextureHandle>,
|
||||
receiver: Option<Receiver<crate::thumbs::Previews>>,
|
||||
started: bool,
|
||||
}
|
||||
|
||||
const PREVIEW_PIXELS: u32 = 96;
|
||||
|
||||
fn render_templates() -> crate::thumbs::Previews {
|
||||
let lighting = materialcraft_render::Lighting::new("studio");
|
||||
let scene = materialcraft_render::Scene::builtin("sphere");
|
||||
let settings = materialcraft_render::Settings { distance: 2.7, supersample: 2, ..Default::default() };
|
||||
materialcraft_engine::samples::TEMPLATES
|
||||
.iter()
|
||||
.filter_map(|(identifier, _)| {
|
||||
let mut package = materialcraft_engine::core::Package::new("Template preview");
|
||||
package.graphs.push(materialcraft_engine::samples::template(identifier, "Template preview", 8).ok()?);
|
||||
let mut session = materialcraft_engine::Session::new(package);
|
||||
session.preview_size = Some(256);
|
||||
session.cook();
|
||||
let maps = materialcraft_render::Maps::from_usages(session.material_maps());
|
||||
Some((identifier.to_string(), materialcraft_render::render(&scene, &maps, &lighting, &settings, PREVIEW_PIXELS, PREVIEW_PIXELS)))
|
||||
})
|
||||
.collect()
|
||||
}
|
||||
|
||||
impl TemplatePreviews {
|
||||
pub(super) fn get(&mut self, context: &egui::Context, identifier: &str) -> Option<egui::TextureId> {
|
||||
if !self.started {
|
||||
self.started = true;
|
||||
let (sender, receiver) = std::sync::mpsc::channel();
|
||||
#[cfg(not(target_arch = "wasm32"))]
|
||||
{
|
||||
let context = context.clone();
|
||||
let _ = std::thread::Builder::new().name("materialcraft-templates".into()).spawn(move || {
|
||||
let _ = sender.send(render_templates());
|
||||
context.request_repaint();
|
||||
});
|
||||
}
|
||||
#[cfg(target_arch = "wasm32")]
|
||||
let _ = sender.send(render_templates());
|
||||
self.receiver = Some(receiver);
|
||||
}
|
||||
if let Some(receiver) = &self.receiver
|
||||
&& let Ok(previews) = receiver.try_recv()
|
||||
{
|
||||
for (identifier, pixels) in previews {
|
||||
let image = egui::ColorImage::from_rgba_unmultiplied([PREVIEW_PIXELS as usize, PREVIEW_PIXELS as usize], &pixels);
|
||||
self.textures.insert(identifier.clone(), context.load_texture(format!("tpl-{identifier}"), image, egui::TextureOptions::LINEAR));
|
||||
}
|
||||
self.receiver = None;
|
||||
}
|
||||
self.textures.get(identifier).map(TextureHandle::id)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,100 @@
|
||||
use egui::vec2;
|
||||
use egui_kittest::{
|
||||
Harness,
|
||||
kittest::{By, Queryable},
|
||||
};
|
||||
use materialcraft_ui_egui::{MaterialCraftApp, UiState};
|
||||
use serde_json::json;
|
||||
|
||||
fn harness(preferences: bool) -> Harness<'static, MaterialCraftApp> {
|
||||
let mut app = MaterialCraftApp::headless(materialcraft_engine::new_session(), UiState::default());
|
||||
app.ui.prefs.preview_size = 64;
|
||||
app.ui.windows.preferences = preferences;
|
||||
app.ui.windows.new_graph = !preferences;
|
||||
let mut harness = Harness::builder().with_size(vec2(1600.0, 960.0)).build_ui_state(
|
||||
|ui, app: &mut MaterialCraftApp| {
|
||||
app.step(&ui.ctx().clone());
|
||||
app.draw(ui);
|
||||
},
|
||||
app,
|
||||
);
|
||||
harness.run_steps(8);
|
||||
harness
|
||||
}
|
||||
|
||||
fn choose_size(harness: &mut Harness<'static, MaterialCraftApp>, axis: &str, size: &str) {
|
||||
harness.get(By::new().role(egui::accesskit::Role::ComboBox).label(axis)).click();
|
||||
harness.run_steps(2);
|
||||
harness.get_by_label(size).click();
|
||||
harness.run_steps(2);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn template_selection_preserves_the_name_and_rectangular_creation_is_one_undo() {
|
||||
let mut harness = harness(false);
|
||||
let original = harness.state().session.pkg.clone();
|
||||
harness.state_mut().ui.new_graph_name = "My material".into();
|
||||
harness.get(By::new().role(egui::accesskit::Role::ListItem).label("Atomic sample")).click();
|
||||
harness.run_steps(3);
|
||||
assert_eq!(harness.state().ui.new_graph_name, "My material");
|
||||
choose_size(&mut harness, "Width", "512 px");
|
||||
harness.get(By::new().role(egui::accesskit::Role::Button).label("Link width and height")).click();
|
||||
harness.run_steps(2);
|
||||
choose_size(&mut harness, "Height", "128 px");
|
||||
harness.get_by_label("Create").click();
|
||||
harness.run_steps(3);
|
||||
assert!(!harness.state().ui.windows.new_graph);
|
||||
assert_eq!(harness.state().session.graph().unwrap().size_px(), [512, 128]);
|
||||
assert_eq!(harness.state().session.graph().unwrap().name, "My material");
|
||||
assert!(harness.state().session.graph().unwrap().nodes.iter().any(|node| node.def == "fx_map"));
|
||||
harness.state_mut().run("edit.undo", json!({})).unwrap();
|
||||
assert_eq!(harness.state().session.pkg, original);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn relinking_dimensions_creates_a_square_and_function_creation_keeps_main_behavior() {
|
||||
let mut harness = harness(false);
|
||||
choose_size(&mut harness, "Width", "256 px");
|
||||
harness.get_by_label("Link width and height").click();
|
||||
harness.run_steps(2);
|
||||
choose_size(&mut harness, "Height", "64 px");
|
||||
harness.get_by_label("Link width and height").click();
|
||||
harness.run_steps(2);
|
||||
harness.get_by_label("Create").click();
|
||||
harness.run_steps(3);
|
||||
assert_eq!(harness.state().session.graph().unwrap().size_px(), [256, 256]);
|
||||
|
||||
harness.state_mut().ui.windows.new_graph = true;
|
||||
harness.run_steps(3);
|
||||
harness.get(By::new().role(egui::accesskit::Role::Button).label("Function Graph")).click();
|
||||
harness.run_steps(3);
|
||||
assert!(harness.query_all(By::new().role(egui::accesskit::Role::ComboBox).label("Width")).next().is_none());
|
||||
harness.get_by_label("Create").click();
|
||||
harness.run_steps(3);
|
||||
assert!(harness.state().session.graph().unwrap().function.is_some());
|
||||
assert!(harness.state().function_editor.is_some());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn preferences_tabs_edit_supported_settings_without_changing_the_document() {
|
||||
let mut harness = harness(true);
|
||||
let original = harness.state().session.pkg.clone();
|
||||
assert!(harness.query_all(By::new().role(egui::accesskit::Role::Slider).label("Interface scale")).next().is_some());
|
||||
harness.get(By::new().role(egui::accesskit::Role::Tab).label("Graph")).click();
|
||||
harness.run_steps(3);
|
||||
let thumbnails = harness.state().ui.prefs.thumbnails;
|
||||
harness.get(By::new().role(egui::accesskit::Role::CheckBox).label("Show node thumbnails")).click();
|
||||
harness.run_steps(2);
|
||||
assert_eq!(harness.state().ui.prefs.thumbnails, !thumbnails);
|
||||
harness.get(By::new().role(egui::accesskit::Role::Tab).label("3D View")).click();
|
||||
harness.run_steps(3);
|
||||
assert!(harness.query_all(By::new().role(egui::accesskit::Role::Slider).label("3D pan speed")).next().is_some());
|
||||
harness.get(By::new().role(egui::accesskit::Role::Tab).label("General")).click();
|
||||
harness.run_steps(3);
|
||||
harness.get(By::new().role(egui::accesskit::Role::ComboBox).label("Language")).click();
|
||||
harness.run_steps(2);
|
||||
assert!(harness.query_all(By::new().label("العربية")).next().is_some());
|
||||
assert_eq!(harness.state().session.pkg, original);
|
||||
let saved: UiState = serde_json::from_value(serde_json::to_value(&harness.state().ui).unwrap()).unwrap();
|
||||
assert_eq!(saved.prefs.thumbnails, !thumbnails);
|
||||
}
|
||||
@@ -0,0 +1,172 @@
|
||||
use egui::{Event, Key, Modifiers, vec2};
|
||||
use egui_kittest::{
|
||||
Harness,
|
||||
kittest::{By, Queryable},
|
||||
};
|
||||
use materialcraft_ui_egui::{MaterialCraftApp, UiState, control, docking::Panel, menus};
|
||||
use serde_json::{Value, json};
|
||||
|
||||
fn app() -> MaterialCraftApp {
|
||||
let mut app = MaterialCraftApp::headless(materialcraft_engine::new_session(), UiState::default());
|
||||
app.ui.prefs.preview_size = 64;
|
||||
app
|
||||
}
|
||||
|
||||
fn maximized(app: &mut MaterialCraftApp, context: &egui::Context) -> Value {
|
||||
control::handle(app, context, "ui.inspect", &json!({}))["result"]["maximizedPanel"].clone()
|
||||
}
|
||||
|
||||
fn maximize(app: &mut MaterialCraftApp, context: &egui::Context, panel: Panel) {
|
||||
let response = control::handle(app, context, "ui.panel.maximize", &json!({"panel": panel}));
|
||||
assert_eq!(response["ok"], true, "{response}");
|
||||
assert_eq!(maximized(app, context), json!(panel));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn maximize_restores_each_panel_without_changing_the_workspace_or_document() {
|
||||
let mut app = app();
|
||||
let context = egui::Context::default();
|
||||
app.ui.dock.focus(Panel::Console);
|
||||
app.ui.dock.focus(Panel::History);
|
||||
let workspace = serde_json::to_value(&app.ui.dock).unwrap();
|
||||
let package = app.session.pkg.clone();
|
||||
let modified = app.session.modified;
|
||||
|
||||
for panel in Panel::ALL {
|
||||
maximize(&mut app, &context, panel);
|
||||
assert!(menus::enabled(&app, "ui.unmaximize"));
|
||||
assert!(app.ui.dock.is_visible(panel));
|
||||
assert_eq!(serde_json::to_value(&app.ui.dock).unwrap(), workspace);
|
||||
let saved: UiState = serde_json::from_value(serde_json::to_value(&app.ui).unwrap()).unwrap();
|
||||
let mut reopened = MaterialCraftApp::headless(materialcraft_engine::new_session(), saved);
|
||||
assert_eq!(maximized(&mut reopened, &context), Value::Null);
|
||||
let response = control::handle(&mut app, &context, "ui.menu.invoke", &json!({"id": "ui.unmaximize"}));
|
||||
assert_eq!(response["ok"], true);
|
||||
assert_eq!(maximized(&mut app, &context), Value::Null);
|
||||
assert!(!menus::enabled(&app, "ui.unmaximize"));
|
||||
assert_eq!(serde_json::to_value(&app.ui.dock).unwrap(), workspace);
|
||||
assert_eq!(app.session.pkg, package);
|
||||
assert_eq!(app.session.modified, modified);
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn invalid_or_hidden_panels_leave_the_maximized_panel_and_workspace_alone() {
|
||||
let mut app = app();
|
||||
let context = egui::Context::default();
|
||||
maximize(&mut app, &context, Panel::View2d);
|
||||
let workspace = app.ui.dock.workspace().clone();
|
||||
|
||||
for parameters in [json!({}), json!({"panel": "missing"}), json!({"panel": null}), json!({"panel": "Console"})] {
|
||||
let response = control::handle(&mut app, &context, "ui.panel.maximize", ¶meters);
|
||||
assert_eq!(response["ok"], false, "{response}");
|
||||
assert_eq!(maximized(&mut app, &context), json!("View2d"));
|
||||
assert_eq!(app.ui.dock.workspace(), &workspace);
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn opening_another_panel_or_closing_the_maximized_panel_restores_the_workspace() {
|
||||
let mut app = app();
|
||||
let context = egui::Context::default();
|
||||
maximize(&mut app, &context, Panel::View2d);
|
||||
menus::invoke(&mut app, &context, "ui.view.properties");
|
||||
assert_eq!(maximized(&mut app, &context), Value::Null);
|
||||
assert!(app.ui.dock.is_visible(Panel::Properties));
|
||||
|
||||
maximize(&mut app, &context, Panel::View2d);
|
||||
app.ui.dock.close(Panel::View2d);
|
||||
assert_eq!(maximized(&mut app, &context), Value::Null);
|
||||
assert!(!app.ui.dock.is_open(Panel::View2d));
|
||||
|
||||
maximize(&mut app, &context, Panel::Graph);
|
||||
app.ui.dock.close(Panel::Graph);
|
||||
assert!(app.ui.dock.is_open(Panel::Graph));
|
||||
assert_eq!(maximized(&mut app, &context), json!("Graph"));
|
||||
menus::invoke(&mut app, &context, "ui.resetLayout");
|
||||
assert_eq!(maximized(&mut app, &context), Value::Null);
|
||||
assert_eq!(app.ui.dock, materialcraft_ui_egui::docking::Dock::default());
|
||||
}
|
||||
|
||||
fn harness() -> Harness<'static, MaterialCraftApp> {
|
||||
let mut harness = Harness::builder().with_size(vec2(1600.0, 960.0)).build_ui_state(
|
||||
|ui, app: &mut MaterialCraftApp| {
|
||||
app.step(&ui.ctx().clone());
|
||||
app.draw(ui);
|
||||
},
|
||||
app(),
|
||||
);
|
||||
harness.run_steps(8);
|
||||
harness
|
||||
}
|
||||
|
||||
fn press_shift_space(harness: &mut Harness<'static, MaterialCraftApp>) {
|
||||
harness.event(Event::ModifiersChanged(Modifiers::SHIFT));
|
||||
harness.event(Event::Key { key: Key::Space, physical_key: None, pressed: true, repeat: false, modifiers: Modifiers::SHIFT });
|
||||
harness.step();
|
||||
harness.event(Event::Key { key: Key::Space, physical_key: None, pressed: false, repeat: false, modifiers: Modifiers::SHIFT });
|
||||
harness.step();
|
||||
harness.event(Event::ModifiersChanged(Modifiers::NONE));
|
||||
harness.run_steps(3);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn shortcut_uses_the_current_pointer_and_restore_button_keeps_panel_geometry() {
|
||||
let mut harness = harness();
|
||||
let context = harness.ctx.clone();
|
||||
let graph = harness.state().graph.view;
|
||||
let workspace = harness.state().ui.dock.workspace().clone();
|
||||
harness.event(Event::PointerMoved(graph.center()));
|
||||
press_shift_space(&mut harness);
|
||||
assert_eq!(maximized(harness.state_mut(), &context), json!("Graph"));
|
||||
assert!(harness.state().graph.view.width() > graph.width());
|
||||
harness.get(By::new().role(egui::accesskit::Role::Button).label("Restore panel layout")).click();
|
||||
harness.run_steps(4);
|
||||
assert_eq!(maximized(harness.state_mut(), &context), Value::Null);
|
||||
assert_eq!(harness.state().graph.view, graph);
|
||||
assert_eq!(harness.state().ui.dock.workspace(), &workspace);
|
||||
|
||||
harness.event(Event::PointerMoved(graph.center()));
|
||||
harness.step();
|
||||
harness.event(Event::PointerMoved(egui::pos2(1599.0, 1.0)));
|
||||
press_shift_space(&mut harness);
|
||||
assert_eq!(maximized(harness.state_mut(), &context), Value::Null);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn shortcut_leaves_text_input_and_popups_in_control() {
|
||||
let mut harness = harness();
|
||||
let context = harness.ctx.clone();
|
||||
harness.state_mut().ui.windows.new_graph = true;
|
||||
harness.run_steps(5);
|
||||
harness
|
||||
.get(By::new().role(egui::accesskit::Role::Window).label("New graph"))
|
||||
.get(By::new().role(egui::accesskit::Role::TextInput).label("Graph name"))
|
||||
.click();
|
||||
harness.run_steps(2);
|
||||
let graph = harness.state().graph.view;
|
||||
harness.event(Event::PointerMoved(graph.center()));
|
||||
press_shift_space(&mut harness);
|
||||
assert_eq!(maximized(harness.state_mut(), &context), Value::Null);
|
||||
|
||||
harness.state_mut().ui.windows.new_graph = false;
|
||||
harness.run_steps(3);
|
||||
maximize(harness.state_mut(), &context, Panel::Graph);
|
||||
harness.state_mut().ui.windows.new_graph = true;
|
||||
harness.run_steps(5);
|
||||
harness
|
||||
.get(By::new().role(egui::accesskit::Role::Window).label("New graph"))
|
||||
.get(By::new().role(egui::accesskit::Role::TextInput).label("Graph name"))
|
||||
.click();
|
||||
harness.run_steps(2);
|
||||
press_shift_space(&mut harness);
|
||||
assert_eq!(maximized(harness.state_mut(), &context), json!("Graph"));
|
||||
|
||||
harness.get_by_label("Cancel").click();
|
||||
harness.run_steps(3);
|
||||
harness.get_by_label("Windows").click();
|
||||
harness.run_steps(3);
|
||||
assert!(egui::Popup::is_any_open(&context));
|
||||
press_shift_space(&mut harness);
|
||||
assert_eq!(maximized(harness.state_mut(), &context), json!("Graph"));
|
||||
}
|
||||
@@ -69,9 +69,7 @@ fn empty_startup_can_create_a_template() {
|
||||
}
|
||||
harness.get_by_label("New graph...").click();
|
||||
settle(&mut harness, 4);
|
||||
harness.get(By::new().role(egui::accesskit::Role::ComboBox).label("Template")).click();
|
||||
settle(&mut harness, 2);
|
||||
harness.get_by_label("Atomic sample").click();
|
||||
harness.get(By::new().role(egui::accesskit::Role::ListItem).label("Atomic sample")).click();
|
||||
settle(&mut harness, 4);
|
||||
harness.get_by_label("Create").click();
|
||||
settle(&mut harness, 40);
|
||||
@@ -893,3 +891,84 @@ fn explorer_inputs_and_graph_drop_share_labels_and_material_assignment() {
|
||||
assert!(frame.chunks_exact(4).filter(|pixel| u16::from(pixel[0]) > u16::from(pixel[1]) + 30).count() > 100);
|
||||
save(&mut harness, &directory, "graph-dropped-on-material");
|
||||
}
|
||||
|
||||
#[test]
|
||||
#[ignore = "requires an offscreen GPU; run explicitly with --ignored"]
|
||||
fn maximized_panels_restore_main_workspace_and_inline_editors() {
|
||||
use materialcraft_ui_egui::{control, docking::Panel, menus};
|
||||
|
||||
let mut app = MaterialCraftApp::headless(materialcraft_engine::sample_session(), UiState::default());
|
||||
app.ui.prefs.preview_size = 64;
|
||||
let mut harness = harness(app, 1600.0, 960.0);
|
||||
settle(&mut harness, 30);
|
||||
let directory = std::path::PathBuf::from(std::env::var_os("MC_SNAPSHOT_DIR").unwrap());
|
||||
std::fs::create_dir_all(&directory).unwrap();
|
||||
save(&mut harness, &directory, "transplant-workspace-before");
|
||||
let workspace = harness.state().ui.dock.workspace().clone();
|
||||
let package = harness.state().session.pkg.clone();
|
||||
let context = harness.ctx.clone();
|
||||
|
||||
for panel in [Panel::View2d, Panel::View3d, Panel::Graph, Panel::Explorer] {
|
||||
let response = control::handle(harness.state_mut(), &context, "ui.panel.maximize", &json!({"panel": panel}));
|
||||
assert_eq!(response["ok"], true, "{response}");
|
||||
settle(&mut harness, 15);
|
||||
save(&mut harness, &directory, &format!("transplant-maximized-{panel:?}"));
|
||||
harness.get(By::new().role(egui::accesskit::Role::Button).label("Restore panel layout")).click();
|
||||
settle(&mut harness, 5);
|
||||
assert_eq!(harness.state().ui.dock.maximized(), None);
|
||||
assert_eq!(harness.state().ui.dock.workspace(), &workspace);
|
||||
assert_eq!(harness.state().session.pkg, package);
|
||||
}
|
||||
save(&mut harness, &directory, "transplant-workspace-restored");
|
||||
|
||||
harness.state_mut().run("graph.node.add", json!({"def": "pixel_processor"})).unwrap();
|
||||
menus::invoke(harness.state_mut(), &context, "graph.node.edit");
|
||||
settle(&mut harness, 4);
|
||||
assert!(harness.state().function_editor.is_some());
|
||||
let package = harness.state().session.pkg.clone();
|
||||
control::handle(harness.state_mut(), &context, "ui.panel.maximize", &json!({"panel": "Graph"}));
|
||||
settle(&mut harness, 5);
|
||||
assert_eq!(harness.query_all(By::new().role(egui::accesskit::Role::Canvas).label("Function Graph")).count(), 1);
|
||||
save(&mut harness, &directory, "transplant-maximized-inline-function");
|
||||
harness.get(By::new().role(egui::accesskit::Role::Button).label("Return to parent graph")).click();
|
||||
settle(&mut harness, 4);
|
||||
assert!(harness.state().function_editor.is_none());
|
||||
assert_eq!(harness.state().ui.dock.maximized(), Some(Panel::Graph));
|
||||
assert_eq!(harness.state().session.pkg, package);
|
||||
menus::invoke(harness.state_mut(), &context, "ui.unmaximize");
|
||||
settle(&mut harness, 4);
|
||||
assert_eq!(harness.state().ui.dock.workspace(), &workspace);
|
||||
}
|
||||
|
||||
#[test]
|
||||
#[ignore = "requires an offscreen GPU; run explicitly with --ignored"]
|
||||
fn transplanted_dialogs_render_with_main_settings_and_templates() {
|
||||
let directory = std::path::PathBuf::from(std::env::var_os("MC_SNAPSHOT_DIR").unwrap());
|
||||
std::fs::create_dir_all(&directory).unwrap();
|
||||
for instance in 0..2 {
|
||||
let mut app = MaterialCraftApp::headless(materialcraft_engine::new_session(), UiState::default());
|
||||
app.ui.prefs.preview_size = 64;
|
||||
app.ui.windows.new_graph = true;
|
||||
let mut harness = harness(app, 1600.0, 960.0);
|
||||
settle(&mut harness, 30);
|
||||
save(&mut harness, &directory, &format!("transplant-new-graph-{instance}"));
|
||||
let rendered = harness.render().unwrap();
|
||||
for label in ["Empty", "Material outputs", "Atomic sample"] {
|
||||
let tile = harness.get(By::new().role(egui::accesskit::Role::ListItem).label(label)).rect();
|
||||
let pixel = rendered.get_pixel(tile.center().x as u32, (tile.top() + 46.0) as u32);
|
||||
assert!(pixel[0] > 140 && pixel[1] > 140 && pixel[2] > 140, "missing {label} preview in app instance {instance}: {pixel:?}");
|
||||
}
|
||||
let original = harness.state().session.pkg.clone();
|
||||
harness.get_by_label("Cancel").click();
|
||||
settle(&mut harness, 3);
|
||||
assert_eq!(harness.state().session.pkg, original);
|
||||
harness.state_mut().ui.windows.preferences = true;
|
||||
settle(&mut harness, 4);
|
||||
for label in ["General", "Graph", "3D View"] {
|
||||
harness.get(By::new().role(egui::accesskit::Role::Tab).label(label)).click();
|
||||
settle(&mut harness, 3);
|
||||
save(&mut harness, &directory, &format!("transplant-preferences-{instance}-{label}"));
|
||||
}
|
||||
assert_eq!(harness.state().session.pkg, original);
|
||||
}
|
||||
}
|
||||
@@ -39,6 +39,7 @@ Agents drive MaterialCraft three ways, all dispatching the same engine commands:
|
||||
| `render {view?, width?, height?, yaw?, pitch?, scene?, node?, port?, full?, tiling?, hq?, displacement?}` | headless | PNG (base64) of the 3D view or of one node; `hq` is the beauty render (displaced mesh, ray-traced AO, shadowed key light, 3×3 supersampling), `displacement` its depth in scene radii |
|
||||
| `ui.inspect` | app | UI state, the graph view rectangle, every node's screen rectangle, every port's identifier, display label and screen position, fps, toasts |
|
||||
| `ui.menu.list` / `ui.menu.invoke {id}` | app | the menu catalog; behave like a click |
|
||||
| `ui.panel.maximize {panel}` | app | maximize an open, active panel: `Graph`, `Explorer`, `Library`, `View3d`, `View2d`, `Properties`, `Console`, or `History`; restore with `ui.menu.invoke {"id":"ui.unmaximize"}` |
|
||||
| `ui.set {...}` | app | recursively merge fields into the UI state |
|
||||
| `ui.input {events}` | app | synthetic input, below |
|
||||
| `view.screenshot {view?: "3d"\|"2d"}` | app | PNG of the 3D or 2D view |
|
||||
@@ -65,11 +66,15 @@ window points (take them from `ui.inspect`'s `nodes` and `ports`).
|
||||
Types: `move`, `down`, `up`, `click`, `doubleClick`, `drag`, `scroll`, `key` (egui key names:
|
||||
`A`, `Enter`, `Space`, `Delete`, `F5`, …), `text`. Buttons: `left`, `right`, `middle`.
|
||||
|
||||
`ui.inspect.maximizedPanel` reports the temporary maximized panel, or `null`. Maximizing
|
||||
preserves the saved workspace. Shift+Space toggles maximization under the pointer; text inputs,
|
||||
popups, modal dialogs and pointer drags retain their input.
|
||||
|
||||
## Key commands
|
||||
|
||||
| Command | Params |
|
||||
|---|---|
|
||||
| `file.new` | `{template?, name?, size?}`; templates from `graph.templates` (`empty`, `pbr`, `bricks`, `stone_tiles`, `wood`, `rusty_metal`, `fabric`, `ground`) |
|
||||
| `file.new` | `{kind?, template?, name?, size?, width?, height?}`; material width/height override size per axis (default 1024 px), rounded down to powers of two in 16..8192; creation is one undo step. Templates from `graph.templates`: `empty`, `pbr`, `atomics` |
|
||||
| `graph.node.edit` | `{}` resolves the selected FX-Map, processor or local graph instance to `{kind, node, parameter?, graph?}`; use `ui.menu.invoke` to enter it in the graph panel |
|
||||
| `graph.pattern.set` | `{id, pattern}` replaces an FX-Map subgraph with cycle validation and undo |
|
||||
| `graph.node.add` | `{def, at?, params?, connectFrom?: {node, port?}, label?}` |
|
||||
|
||||
Reference in new issue
Block a user