mirror of
https://github.com/storytold/materialcraft.git
synced 2026-11-30 01:53:54 +01:00
feat(graph): select several wires and swap their sources with X
Shift+click adds a wire to the selection and Ctrl+click toggles it. With two
or more wires selected, X swaps where they come from: two wires trade
sources, more reverse them in target-node and input order, so selecting a
Blend node's foreground and background wires and pressing X swaps the two
layers. The wires stay selected, so X again swaps back. Delete and
Backspace remove every selected wire in one undo step, and the wire menu
gains Swap selected links and Delete selected links.
New commands graph.wire.swap and graph.wire.delete take
{wires: [{to, toPort}, ...]}; a swap that would make a cycle is refused and
changes nothing. Engine and UI tests (real clicks on a Blend node) cover
both; docs/wires-and-alpha.md documents the gestures, the ordering rule and
the commands.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
1 parent
8f4dd5b6c1
commit
29dee321d9
10 files changed
+321
-55
No files matched your search
@@ -173,7 +173,7 @@ SVG and Text, noises including tileable 3D ones, patterns, filters, the flood fi
|
||||
whole-material blending and weathering), function graphs with a visual editor and dynamic
|
||||
parameters, sub-graphs with exposed inputs and presets, the full editor (graph, library,
|
||||
properties, 2D view with histogram, 3D view with your own OBJ/glTF meshes, alpha transparency and an
|
||||
alpha channel view; wires you can select, delete and reroute with dots, see
|
||||
alpha channel view; wires you can select, delete, swap (X) and reroute with dots, see
|
||||
[docs/wires-and-alpha.md](docs/wires-and-alpha.md)), `.mcraft` packages,
|
||||
texture export, portable `.mcmat` materials that TextureCraft paints with (inputs stay editable
|
||||
there), the browser build with file I/O, the CLI, the control channel and the MCP server
|
||||
|
||||
@@ -1,24 +1,104 @@
|
||||
//! Wire commands: edit a single wire (connection) of the open graph, addressed by the input it
|
||||
//! feeds (`to`, `toPort`). Deleting a wire is `graph.disconnect`; this module splits a wire with
|
||||
//! a reroute dot so it can be repositioned.
|
||||
//! Wire commands: edit wires (connections) of the open graph, each addressed by the input it
|
||||
//! feeds (`to`, `toPort`): split a wire with a reroute dot so it can be repositioned, delete
|
||||
//! several wires at once, and swap (reverse) where a set of wires come from.
|
||||
|
||||
use serde_json::{Value as J, json};
|
||||
|
||||
use materialcraft_core::NodeId;
|
||||
use materialcraft_core::{Connection, NodeId};
|
||||
|
||||
use crate::commands::{CommandSpec, bad, has_graph, point, strp, u64p};
|
||||
use crate::{Result, Session, cmd};
|
||||
|
||||
pub(crate) fn specs() -> Vec<CommandSpec> {
|
||||
vec![cmd!(
|
||||
"graph.wire.insertDot",
|
||||
"Insert reroute dot",
|
||||
[],
|
||||
None,
|
||||
"{to, toPort, at? [x, y] (graph point, default: midway)} splits the wire feeding to.toPort with a Dot node there, selected",
|
||||
has_graph,
|
||||
insert_dot
|
||||
)]
|
||||
vec![
|
||||
cmd!(
|
||||
"graph.wire.insertDot",
|
||||
"Insert reroute dot",
|
||||
[],
|
||||
None,
|
||||
"{to, toPort, at? [x, y] (graph point, default: midway)} splits the wire feeding to.toPort with a Dot node there, selected",
|
||||
has_graph,
|
||||
insert_dot
|
||||
),
|
||||
cmd!(
|
||||
"graph.wire.delete",
|
||||
"Delete links",
|
||||
[],
|
||||
None,
|
||||
"{wires: [{to, toPort}, ...]} deletes the wires feeding those inputs, in one undo step",
|
||||
has_graph,
|
||||
delete
|
||||
),
|
||||
cmd!(
|
||||
"graph.wire.swap",
|
||||
"Swap links",
|
||||
[],
|
||||
None,
|
||||
"{wires: [{to, toPort}, ...] (two or more)} reverses where the wires come from: sorted by target node and input order, the first wire's source goes to the last input and so on (two wires swap)",
|
||||
has_graph,
|
||||
swap
|
||||
),
|
||||
]
|
||||
}
|
||||
|
||||
/// Most wires one command takes (a graph has far fewer inputs in practice).
|
||||
const MAX_WIRES: usize = 4096;
|
||||
|
||||
/// The wires named by `wires: [{to, toPort}, ...]`, each existing and named once.
|
||||
fn wires_param(s: &Session, id: &str, p: &J) -> Result<Vec<Connection>> {
|
||||
let list = p.get("wires").and_then(J::as_array).ok_or_else(|| bad(id, "`wires` is a list of {to, toPort}"))?;
|
||||
if list.len() > MAX_WIRES {
|
||||
return Err(bad(id, format!("at most {MAX_WIRES} wires")));
|
||||
}
|
||||
let g = s.graph()?;
|
||||
let mut out: Vec<Connection> = Vec::with_capacity(list.len());
|
||||
for w in list {
|
||||
let to = w.get("to").and_then(J::as_u64).map(NodeId).ok_or_else(|| bad(id, "each wire needs `to`"))?;
|
||||
let port = w.get("toPort").and_then(J::as_str).ok_or_else(|| bad(id, "each wire needs `toPort`"))?;
|
||||
let c = g.input_of(to, port).ok_or_else(|| bad(id, format!("no wire feeds `{port}` of node {}", to.0)))?;
|
||||
if out.iter().any(|o| o.to == c.to && o.to_port == c.to_port) {
|
||||
return Err(bad(id, format!("the wire into `{port}` of node {} is listed twice", to.0)));
|
||||
}
|
||||
out.push(c.clone());
|
||||
}
|
||||
Ok(out)
|
||||
}
|
||||
|
||||
fn delete(s: &mut Session, p: &J) -> Result<J> {
|
||||
let wires = wires_param(s, "graph.wire.delete", p)?;
|
||||
if wires.is_empty() {
|
||||
return Err(bad("graph.wire.delete", "no wire given"));
|
||||
}
|
||||
s.edit("Delete links", |s| {
|
||||
let g = s.graph_mut()?;
|
||||
for c in &wires {
|
||||
g.disconnect(c.to, &c.to_port);
|
||||
}
|
||||
Ok(json!({"deleted": wires.len()}))
|
||||
})
|
||||
}
|
||||
|
||||
fn swap(s: &mut Session, p: &J) -> Result<J> {
|
||||
const ID: &str = "graph.wire.swap";
|
||||
let mut wires = wires_param(s, ID, p)?;
|
||||
if wires.len() < 2 {
|
||||
return Err(bad(ID, "select two or more wires to swap"));
|
||||
}
|
||||
// A stable order whatever order the wires were picked in: target node, then input order.
|
||||
let order = |s: &Session, c: &Connection| (c.to.0, s.input_ports(c.to).iter().position(|p| *p == c.to_port).unwrap_or(usize::MAX));
|
||||
wires.sort_by_key(|c| order(s, c));
|
||||
let sources: Vec<(NodeId, String)> = wires.iter().rev().map(|c| (c.from, c.from_port.clone())).collect();
|
||||
s.edit("Swap links", |s| {
|
||||
let g = s.graph_mut()?;
|
||||
// Unplug them all first, so no half-swapped state is mistaken for a cycle.
|
||||
for c in &wires {
|
||||
g.disconnect(c.to, &c.to_port);
|
||||
}
|
||||
for (c, (from, port)) in wires.iter().zip(&sources) {
|
||||
g.connect(*from, port, c.to, &c.to_port).map_err(|_| bad(ID, format!("swapping would feed node {} into itself (a cycle)", c.to.0)))?;
|
||||
}
|
||||
Ok(json!({"swapped": wires.len()}))
|
||||
})
|
||||
}
|
||||
|
||||
fn insert_dot(s: &mut Session, p: &J) -> Result<J> {
|
||||
|
||||
@@ -234,3 +234,54 @@ fn every_template_is_opaque_in_the_3d_view() {
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn selected_wires_swap_their_sources_and_delete_together() {
|
||||
use materialcraft_engine::core::NodeId;
|
||||
let mut s = sample_session();
|
||||
run(&mut s, "file.new", json!({"template": "empty"}));
|
||||
let a = run(&mut s, "graph.node.add", json!({"def": "clouds_1", "at": [0, 0]}))["id"].as_u64().unwrap();
|
||||
let b = run(&mut s, "graph.node.add", json!({"def": "perlin_noise", "at": [0, 200]}))["id"].as_u64().unwrap();
|
||||
let m = run(&mut s, "graph.node.add", json!({"def": "checker", "at": [0, 400]}))["id"].as_u64().unwrap();
|
||||
let blend = run(&mut s, "graph.node.add", json!({"def": "blend", "at": [300, 100]}))["id"].as_u64().unwrap();
|
||||
run(&mut s, "graph.connect", json!({"from": a, "to": blend, "toPort": "foreground"}));
|
||||
run(&mut s, "graph.connect", json!({"from": b, "to": blend, "toPort": "background"}));
|
||||
run(&mut s, "graph.connect", json!({"from": m, "to": blend, "toPort": "mask"}));
|
||||
let src = |s: &Session, port: &str| s.graph().unwrap().input_of(NodeId(blend), port).unwrap().from.0;
|
||||
let fg_bg = json!({"wires": [{"to": blend, "toPort": "background"}, {"to": blend, "toPort": "foreground"}]});
|
||||
// Two wires swap, whatever order they are listed in; the other input is left alone.
|
||||
run(&mut s, "graph.wire.swap", fg_bg.clone());
|
||||
assert_eq!((src(&s, "foreground"), src(&s, "background"), src(&s, "mask")), (b, a, m));
|
||||
run(&mut s, "graph.wire.swap", fg_bg.clone());
|
||||
assert_eq!((src(&s, "foreground"), src(&s, "background")), (a, b));
|
||||
// Three wires reverse in input order: foreground <-> mask, background stays.
|
||||
let all = json!({"wires": [{"to": blend, "toPort": "foreground"}, {"to": blend, "toPort": "background"}, {"to": blend, "toPort": "mask"}]});
|
||||
run(&mut s, "graph.wire.swap", all.clone());
|
||||
assert_eq!((src(&s, "foreground"), src(&s, "background"), src(&s, "mask")), (m, b, a));
|
||||
// One undo step each.
|
||||
run(&mut s, "edit.undo", json!({}));
|
||||
assert_eq!((src(&s, "foreground"), src(&s, "background"), src(&s, "mask")), (a, b, m));
|
||||
// Bad requests change nothing.
|
||||
for bad in [
|
||||
json!({}),
|
||||
json!({"wires": [{"to": blend, "toPort": "foreground"}]}),
|
||||
json!({"wires": [{"to": blend, "toPort": "foreground"}, {"to": blend, "toPort": "foreground"}]}),
|
||||
json!({"wires": [{"to": blend, "toPort": "foreground"}, {"to": a, "toPort": "input"}]}),
|
||||
] {
|
||||
assert!(execute(&mut s, "graph.wire.swap", &bad).is_err(), "{bad}");
|
||||
}
|
||||
assert_eq!(src(&s, "foreground"), a);
|
||||
// A swap that would make a cycle is refused and rolled back: blend -> levels, then swap the
|
||||
// wire into levels with the wire into blend's foreground.
|
||||
let lv = run(&mut s, "graph.node.add", json!({"def": "levels", "at": [600, 100]}))["id"].as_u64().unwrap();
|
||||
run(&mut s, "graph.connect", json!({"from": blend, "to": lv}));
|
||||
let cyc = json!({"wires": [{"to": blend, "toPort": "foreground"}, {"to": lv, "toPort": "input"}]});
|
||||
assert!(execute(&mut s, "graph.wire.swap", &cyc).is_err());
|
||||
assert_eq!(src(&s, "foreground"), a);
|
||||
assert_eq!(s.graph().unwrap().connections.len(), 4);
|
||||
// Deleting several wires is one step.
|
||||
run(&mut s, "graph.wire.delete", all);
|
||||
assert_eq!(s.graph().unwrap().connections.len(), 1);
|
||||
run(&mut s, "edit.undo", json!({}));
|
||||
assert_eq!(s.graph().unwrap().connections.len(), 4);
|
||||
}
|
||||
@@ -6,8 +6,9 @@
|
||||
//! it, drag the empty canvas to box-select (Ctrl adds), middle-drag or Alt+drag to pan, wheel to
|
||||
//! zoom, double-click a node to show it in the 2D view (a graph instance opens its graph), Space, Tab or
|
||||
//! double-click the canvas for the node search, right-click for menus, drop library items to add
|
||||
//! them. Click a wire to select it (Delete removes it), drag a wire to pull a reroute dot out of
|
||||
//! it, double-click a wire to drop a dot there, right-click a wire for its menu. Every edit is an
|
||||
//! them. Click a wire to select it (Shift or Ctrl+click adds more; Delete removes them, X swaps
|
||||
//! where they come from), drag a wire to pull a reroute dot out of it, double-click a wire to drop
|
||||
//! a dot there, right-click a wire for its menu. Every edit is an
|
||||
//! engine command; the gestures only draw previews until they commit.
|
||||
|
||||
use egui::{Align2, Color32, CornerRadius, FontId, Pos2, Rect, Sense, Stroke, StrokeKind, Ui, Vec2, pos2, vec2};
|
||||
@@ -104,8 +105,8 @@ pub struct GraphView {
|
||||
menu_at: Pos2,
|
||||
/// The graph the camera last framed.
|
||||
framed_graph: Option<usize>,
|
||||
/// The selected wire (Delete removes it).
|
||||
pub selected_wire: Option<WireRef>,
|
||||
/// The selected wires, in the order they were picked (Delete removes them, X swaps them).
|
||||
pub selected_wires: Vec<WireRef>,
|
||||
/// The wire the context menu is for (right-clicked on a wire).
|
||||
menu_wire: Option<WireRef>,
|
||||
/// Wires on screen last frame: the wire and its bezier control points.
|
||||
@@ -124,7 +125,7 @@ impl Default for GraphView {
|
||||
view: Rect::NOTHING,
|
||||
menu_at: Pos2::ZERO,
|
||||
framed_graph: None,
|
||||
selected_wire: None,
|
||||
selected_wires: Vec::new(),
|
||||
menu_wire: None,
|
||||
wires: Vec::new(),
|
||||
}
|
||||
@@ -407,7 +408,7 @@ fn canvas(app: &mut MaterialCraftApp, ui: &mut Ui) {
|
||||
if app.ui.frame_all || app.graph.framed_graph != Some(app.session.graph) {
|
||||
app.ui.frame_all = false;
|
||||
app.graph.framed_graph = Some(app.session.graph);
|
||||
app.graph.selected_wire = None;
|
||||
app.graph.selected_wires.clear();
|
||||
frame(app, rect, false);
|
||||
}
|
||||
let painter = ui.painter_at(rect);
|
||||
@@ -557,7 +558,7 @@ fn canvas(app: &mut MaterialCraftApp, ui: &mut Ui) {
|
||||
for (w, ctrl) in &wires {
|
||||
let Some(c) = g.input_of(w.0, &w.1) else { continue };
|
||||
let hot = selection.contains(&c.from) || selection.contains(&c.to);
|
||||
let picked = app.graph.selected_wire.as_ref() == Some(w);
|
||||
let picked = app.graph.selected_wires.contains(w);
|
||||
let hovered = wire_hover.as_ref() == Some(w);
|
||||
let base = (2.0 * cam.zoom).clamp(1.0, 3.0);
|
||||
let stroke = if picked {
|
||||
@@ -796,10 +797,13 @@ fn handle_input(
|
||||
if middle_down || (primary_pressed && mods.alt) {
|
||||
app.graph.drag = Some(Drag::Pan);
|
||||
} else if primary_pressed {
|
||||
// Any press other than on a wire drops the wire selection.
|
||||
app.graph.selected_wire = None;
|
||||
let on_card = nodes.iter().any(|(_, r)| r.rect.contains(p)) || comments.iter().any(|(_, r)| r.contains(p));
|
||||
if let Some(w) = wire_hover.as_ref().filter(|_| port_hover.is_none() && !on_card) {
|
||||
let wire = wire_hover.as_ref().filter(|_| port_hover.is_none() && !on_card);
|
||||
// Any press other than on a wire drops the wire selection.
|
||||
if wire.is_none() {
|
||||
app.graph.selected_wires.clear();
|
||||
}
|
||||
if let Some(w) = wire {
|
||||
app.graph.drag = Some(Drag::WirePress { wire: w.clone(), start: p });
|
||||
} else if let Some(h) = &port_hover {
|
||||
if h.output {
|
||||
@@ -870,7 +874,17 @@ fn handle_input(
|
||||
Drag::Pan => {}
|
||||
Drag::WirePress { wire, .. } => {
|
||||
app.session.selection.clear();
|
||||
app.graph.selected_wire = Some(wire);
|
||||
let sel = &mut app.graph.selected_wires;
|
||||
if mods.ctrl && sel.contains(&wire) {
|
||||
// Ctrl+click toggles a wire out of the selection.
|
||||
sel.retain(|w| *w != wire);
|
||||
} else if mods.ctrl || mods.shift {
|
||||
if !sel.contains(&wire) {
|
||||
sel.push(wire);
|
||||
}
|
||||
} else {
|
||||
*sel = vec![wire];
|
||||
}
|
||||
}
|
||||
Drag::Nodes { delta } => {
|
||||
if delta.length() > 0.5 {
|
||||
@@ -985,7 +999,7 @@ fn handle_input(
|
||||
Some(w) => {
|
||||
let at = cam.to_graph(p);
|
||||
app.run("graph.wire.insertDot", json!({"to": w.0.0, "toPort": w.1, "at": [at.x, at.y]}));
|
||||
app.graph.selected_wire = None;
|
||||
app.graph.selected_wires.clear();
|
||||
}
|
||||
None => open_search(app, cam.to_graph(p), None),
|
||||
}
|
||||
@@ -995,9 +1009,12 @@ fn handle_input(
|
||||
{
|
||||
app.graph.menu_at = cam.to_graph(p);
|
||||
app.graph.menu_wire = wire_hover.clone().filter(|_| !on_node);
|
||||
if let Some(w) = &app.graph.menu_wire {
|
||||
// Right-clicking a selected wire keeps the selection (to swap or delete them all).
|
||||
if let Some(w) = &app.graph.menu_wire
|
||||
&& !app.graph.selected_wires.contains(w)
|
||||
{
|
||||
app.session.selection.clear();
|
||||
app.graph.selected_wire = Some(w.clone());
|
||||
app.graph.selected_wires = vec![w.clone()];
|
||||
}
|
||||
}
|
||||
let at = app.graph.menu_at;
|
||||
@@ -1175,22 +1192,51 @@ fn node_menu(app: &mut MaterialCraftApp, ui: &mut Ui, id: NodeId) {
|
||||
item(ui, "Create graph from selection", "graph.createFromSelection", json!({}));
|
||||
}
|
||||
|
||||
/// Delete the selected wire (the Delete and Backspace keys); `false` when none is selected.
|
||||
pub fn delete_selected_wire(app: &mut MaterialCraftApp) -> bool {
|
||||
let Some((to, port)) = app.graph.selected_wire.take() else { return false };
|
||||
app.run("graph.disconnect", json!({"to": to.0, "toPort": port}));
|
||||
/// `wires` as the `{wires: [{to, toPort}, ...]}` parameter of the wire commands.
|
||||
fn wires_json(wires: &[WireRef]) -> serde_json::Value {
|
||||
json!({"wires": wires.iter().map(|(to, port)| json!({"to": to.0, "toPort": port})).collect::<Vec<_>>()})
|
||||
}
|
||||
|
||||
/// Delete the selected wires in one undo step (the Delete and Backspace keys); `false` when none
|
||||
/// is selected.
|
||||
pub fn delete_selected_wires(app: &mut MaterialCraftApp) -> bool {
|
||||
let wires = std::mem::take(&mut app.graph.selected_wires);
|
||||
if wires.is_empty() {
|
||||
return false;
|
||||
}
|
||||
app.run("graph.wire.delete", wires_json(&wires));
|
||||
true
|
||||
}
|
||||
|
||||
/// Swap where the selected wires come from (the X key): two wires trade sources, more reverse
|
||||
/// them in input order. The wires stay selected, so X again swaps back. `false` when no wire is
|
||||
/// selected.
|
||||
pub fn swap_selected_wires(app: &mut MaterialCraftApp) -> bool {
|
||||
if app.graph.selected_wires.is_empty() {
|
||||
return false;
|
||||
}
|
||||
let params = wires_json(&app.graph.selected_wires);
|
||||
app.run("graph.wire.swap", params);
|
||||
true
|
||||
}
|
||||
|
||||
fn wire_menu(app: &mut MaterialCraftApp, ui: &mut Ui, (to, port): WireRef, at: Pos2) {
|
||||
let n = app.graph.selected_wires.len();
|
||||
if ui.button(format!("{} {}", icon::DOT_OUTLINE, tr("Insert reroute dot"))).clicked() {
|
||||
app.run("graph.wire.insertDot", json!({"to": to.0, "toPort": port, "at": [at.x, at.y]}));
|
||||
app.graph.selected_wire = None;
|
||||
app.graph.selected_wires.clear();
|
||||
ui.close();
|
||||
}
|
||||
if ui.button(format!("{} {}", icon::TRASH, tr("Delete link"))).clicked() {
|
||||
app.graph.selected_wire = Some((to, port));
|
||||
delete_selected_wire(app);
|
||||
if n >= 2 && ui.button(format!("{} {} (X)", icon::ARROWS_LEFT_RIGHT, tr("Swap selected links"))).clicked() {
|
||||
swap_selected_wires(app);
|
||||
ui.close();
|
||||
}
|
||||
let label = if n >= 2 { tr("Delete selected links") } else { tr("Delete link") };
|
||||
if ui.button(format!("{} {label}", icon::TRASH)).clicked() {
|
||||
if n < 2 {
|
||||
app.graph.selected_wires = vec![(to, port)];
|
||||
}
|
||||
delete_selected_wires(app);
|
||||
ui.close();
|
||||
}
|
||||
}
|
||||
@@ -1289,6 +1335,55 @@ mod tests {
|
||||
assert!(app.graph.search.is_some());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn clicked_wires_swap_with_x_and_delete_together() {
|
||||
let mut app = MaterialCraftApp::headless(materialcraft_engine::sample_session(), crate::UiState::default());
|
||||
app.run("file.new", json!({"template": "empty"}));
|
||||
let id = |v: Option<serde_json::Value>| v.and_then(|v| v["id"].as_u64()).unwrap();
|
||||
let a = id(app.run("graph.node.add", json!({"def": "clouds_1", "at": [0, -150]})));
|
||||
let b = id(app.run("graph.node.add", json!({"def": "checker", "at": [0, 150]})));
|
||||
let blend = id(app.run("graph.node.add", json!({"def": "blend", "at": [450, 0]})));
|
||||
app.run("graph.connect", json!({"from": a, "to": blend, "toPort": "foreground"}));
|
||||
app.run("graph.connect", json!({"from": b, "to": blend, "toPort": "background"}));
|
||||
let ctx = egui::Context::default();
|
||||
let mut frame = |app: &mut MaterialCraftApp, mut events: Vec<egui::Event>, modifiers: egui::Modifiers| {
|
||||
events.insert(0, egui::Event::ModifiersChanged(modifiers));
|
||||
let input = egui::RawInput { events, ..Default::default() };
|
||||
ctx.run_ui(input, |ui| {
|
||||
app.step(&ui.ctx().clone());
|
||||
app.draw(ui);
|
||||
})
|
||||
.textures_delta
|
||||
.clear();
|
||||
};
|
||||
for _ in 0..3 {
|
||||
frame(&mut app, Vec::new(), egui::Modifiers::NONE);
|
||||
}
|
||||
let mid =
|
||||
|app: &MaterialCraftApp, port: &str| app.graph.wires.iter().find(|(w, _)| w.0.0 == blend && w.1 == port).map(|(_, c)| bezier_at(c, 0.5)).unwrap();
|
||||
let click =
|
||||
|app: &mut MaterialCraftApp, frame: &mut dyn FnMut(&mut MaterialCraftApp, Vec<egui::Event>, egui::Modifiers), port: &str, m: egui::Modifiers| {
|
||||
let p = mid(app, port);
|
||||
let button = |pressed| egui::Event::PointerButton { pos: p, button: egui::PointerButton::Primary, pressed, modifiers: m };
|
||||
frame(app, vec![egui::Event::PointerMoved(p)], m);
|
||||
frame(app, vec![button(true)], m);
|
||||
frame(app, vec![button(false)], m);
|
||||
};
|
||||
click(&mut app, &mut frame, "foreground", egui::Modifiers::NONE);
|
||||
click(&mut app, &mut frame, "background", egui::Modifiers::SHIFT);
|
||||
assert_eq!(app.graph.selected_wires.len(), 2, "{:?}", app.graph.selected_wires);
|
||||
let key = |k| egui::Event::Key { key: k, physical_key: None, pressed: true, repeat: false, modifiers: egui::Modifiers::NONE };
|
||||
let src = |app: &MaterialCraftApp, port: &str| app.session.graph().unwrap().input_of(NodeId(blend), port).unwrap().from.0;
|
||||
frame(&mut app, vec![key(egui::Key::X)], egui::Modifiers::NONE);
|
||||
assert_eq!((src(&app, "foreground"), src(&app, "background")), (b, a));
|
||||
// Still selected: X again swaps back.
|
||||
frame(&mut app, vec![key(egui::Key::X)], egui::Modifiers::NONE);
|
||||
assert_eq!((src(&app, "foreground"), src(&app, "background")), (a, b));
|
||||
frame(&mut app, vec![key(egui::Key::Delete)], egui::Modifiers::NONE);
|
||||
assert!(app.session.graph().unwrap().connections.is_empty());
|
||||
assert!(app.graph.selected_wires.is_empty());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn node_search_shortcuts_respect_hover_and_keyboard_focus() {
|
||||
for key in [egui::Key::Space, egui::Key::Tab] {
|
||||
|
||||
@@ -252,11 +252,13 @@ pub fn shortcuts(app: &mut MaterialCraftApp, ctx: &egui::Context) {
|
||||
if !ctx.input(|i| i.events.iter().any(|e| matches!(e, egui::Event::Key { pressed: true, .. }))) {
|
||||
return;
|
||||
}
|
||||
// A selected wire takes Delete and Backspace before the node commands do.
|
||||
if app.graph.selected_wire.is_some()
|
||||
&& ctx.input_mut(|i| i.consume_key(egui::Modifiers::NONE, egui::Key::Delete) | i.consume_key(egui::Modifiers::NONE, egui::Key::Backspace))
|
||||
{
|
||||
crate::graph_view::delete_selected_wire(app);
|
||||
// Selected wires take Delete and Backspace before the node commands do, and X swaps them.
|
||||
if !app.graph.selected_wires.is_empty() {
|
||||
if ctx.input_mut(|i| i.consume_key(egui::Modifiers::NONE, egui::Key::Delete) | i.consume_key(egui::Modifiers::NONE, egui::Key::Backspace)) {
|
||||
crate::graph_view::delete_selected_wires(app);
|
||||
} else if ctx.input_mut(|i| i.consume_key(egui::Modifiers::NONE, egui::Key::X)) {
|
||||
crate::graph_view::swap_selected_wires(app);
|
||||
}
|
||||
}
|
||||
let mut table: Vec<(&'static str, KeyboardShortcut)> = CATALOG.iter().filter_map(|i| Some((i.id, parse_shortcut(i.shortcut?)?))).collect();
|
||||
for c in materialcraft_engine::command_specs() {
|
||||
|
||||
@@ -73,7 +73,7 @@ fn snapshots() {
|
||||
.unwrap();
|
||||
h.state_mut().run("graph.wire.insertDot", json!({"to": out, "toPort": "input", "at": [210, -330]}));
|
||||
let wire = h.state().session.graph().unwrap().connections.iter().find(|c| c.to.0 != out).map(|c| (c.to, c.to_port.clone()));
|
||||
h.state_mut().graph.selected_wire = wire;
|
||||
h.state_mut().graph.selected_wires = wire.into_iter().collect();
|
||||
h.state_mut().run("view.3d", json!({"scene": "sphere"}));
|
||||
h.state_mut().ui.frame_all = true;
|
||||
settle(&mut h, 60);
|
||||
|
||||
@@ -63,7 +63,7 @@ drag) into one undo step. See [control-protocol.md](control-protocol.md).
|
||||
through `ui.inspect` / `ui.set`). The dock (craft-ui) hosts eight panels around the protected graph
|
||||
panel. The graph editor lays nodes out in graph space, draws cards with thumbnails from the cook
|
||||
results (uploaded once per cache key), wires as cubic beziers between typed ports (hit-tested
|
||||
against the curve, so a wire can be selected, deleted or split with a reroute dot), and turns
|
||||
against the curve, so wires can be selected, deleted, swapped or split with a reroute dot), and turns
|
||||
gestures into commands only when they complete. See [wires-and-alpha.md](wires-and-alpha.md). The 3D view renders with `materialcraft-render`
|
||||
on the CPU: half resolution while the camera moves, 2×2 supersampled when it rests.
|
||||
|
||||
|
||||
@@ -63,6 +63,7 @@ Types: `move`, `down`, `up`, `click`, `doubleClick`, `drag`, `scroll`, `key` (eg
|
||||
| `graph.node.add` | `{def, at?, params?, connectFrom?: {node, port?}, label?}` |
|
||||
| `graph.connect` / `graph.disconnect` | `{from, fromPort?, to, toPort?}` / `{to, toPort}` |
|
||||
| `graph.wire.insertDot` | `{to, toPort, at?}`: split the wire feeding `to.toPort` with a reroute Dot node at `at` (graph point, default midway), selected |
|
||||
| `graph.wire.swap` / `graph.wire.delete` | `{wires: [{to, toPort}, ...]}`: swap (two) or reverse (more, in input order) where the wires come from / delete them, one undo step each |
|
||||
| `graph.node.param` | `{id?, param, value}`: numbers, `[x, y]`, `"#rrggbb"`, enum index, curve `[[x, y], …]`, gradient `[[pos, color], …]`, or a typed value `{"t": "function", "v": {...}}` |
|
||||
| `graph.node.base` | `{id?, sizeMode?, size?, format?, seed?, tiling?}` |
|
||||
| `graph.exposed.add` / `graph.exposed.set` | `{id, label?, default?, bind?: {node, param}}` / `{id, value}` |
|
||||
|
||||
@@ -8,7 +8,7 @@ automation + tests), weighted by how much of the day each area carries. **Remain
|
||||
|
||||
| Area | Weight | Done | What works | Main gaps |
|
||||
|---|---:|---:|---|---|
|
||||
| Graph editing | 15 | 75% | Pan/zoom canvas with grid; node cards with headers by category, live thumbnails and size/format labels; typed ports; bezier wires; drag to wire, re-route and unplug; select a wire (click) and delete it (Delete, Backspace, wire menu); reroute dots pulled out of a wire (drag), dropped on it (double-click) or inserted from its menu; drop a wire on empty canvas to add a wired node; box/Ctrl/Shift selection; move; frames (move with contents, resize), comments (inline edit), navigation pins; node search (Space, double-click); library drag and drop; align and distribute; copy/cut/paste/duplicate (with or without links); delete and relink; disable; select upstream/downstream; create graph from selection; snapshot undo with merged slider drags | Dot-node chains editing, wire tension preferences, compact node display mode, multi-graph tabs, minimap |
|
||||
| Graph editing | 15 | 75% | Pan/zoom canvas with grid; node cards with headers by category, live thumbnails and size/format labels; typed ports; bezier wires; drag to wire, re-route and unplug; select wires (click, Shift/Ctrl+click), delete them (Delete, Backspace, wire menu) and swap their sources (X); reroute dots pulled out of a wire (drag), dropped on it (double-click) or inserted from its menu; drop a wire on empty canvas to add a wired node; box/Ctrl/Shift selection; move; frames (move with contents, resize), comments (inline edit), navigation pins; node search (Space, double-click); library drag and drop; align and distribute; copy/cut/paste/duplicate (with or without links); delete and relink; disable; select upstream/downstream; create graph from selection; snapshot undo with merged slider drags | Dot-node chains editing, wire tension preferences, compact node display mode, multi-graph tabs, minimap |
|
||||
| Atomic nodes | 12 | 95% | Bitmap, Blend (16 modes, masks, alpha), Blur, Channels Shuffle, Curve, Directional Blur, Directional Warp, Distance (with color propagation), Emboss, FX-Map (grid, quadtree and scatter modes with per-instance randomness), Gradient (Dynamic), Gradient Map, Grayscale Conversion, HSL, Levels, Normal, Pixel Processor, Value Processor, Sharpen, SVG (path data, fill rules, stroke), Text (own stroke font), Transformation 2D, Uniform Color, Warp, inputs, outputs, dots, graph instances | FX-Map driven by per-iteration functions, SVG arcs and SVG files, font choice for Text |
|
||||
| Node library | 20 | 45% | 227 nodes: noises (tileable 3D Perlin, simplex and Worley, cracks, stones, dirt, grunge maps and more), patterns (tile generator and sampler, bricks, hexagons, weave, shape splatter, paint strokes, scratches), filters (adjustments, blending, blurs, channels, effects, normal map tools, tiling, transforms), the flood fill family, whole-material and height blending, weathering (rust, moss, leaks, edge damage, edge wear, dust) | The rest of the reference library's ~400 graphs: more grunge and scan processing, mesh-based generators and bakers, spline tools, SDF functions |
|
||||
| Function graphs | 10 | 70% | A compiled, 4-wide evaluator with ~55 ops (constants, $pos/$size, exposed variables, samplers, vectors, swizzles, math, logic, comparison, noise, random, if/else); pixel and value processors; a visual function editor; dynamic parameters (a function on any numeric, color, bool or enum parameter, evaluated from the graph's inputs) | Loops, function graphs as reusable package items |
|
||||
|
||||
+48
-11
@@ -1,7 +1,7 @@
|
||||
# Editing wires and viewing alpha in the 3D view
|
||||
|
||||
This page documents two editor features: selecting, deleting and rerouting wires in the graph
|
||||
editor, and the alpha (transparency) support of the 3D view. Both are clean-room implementations;
|
||||
This page documents two editor features: selecting, deleting, swapping and rerouting wires in
|
||||
the graph editor, and the alpha (transparency) support of the 3D view. Both are clean-room implementations;
|
||||
every action is an engine command, so the CLI, the control channel and MCP can do the same as the
|
||||
mouse.
|
||||
|
||||
@@ -20,17 +20,38 @@ named by the input it feeds: the target node and its input port (`to`, `toPort`)
|
||||
| Gesture | What it does |
|
||||
|---|---|
|
||||
| Hover a wire | The wire turns white and the pointer becomes a hand: it can be clicked |
|
||||
| Click a wire | Selects it (drawn thicker, in the accent color); the node selection is cleared |
|
||||
| **Delete** or **Backspace** with a wire selected | Deletes the wire |
|
||||
| Click a wire | Selects it alone (drawn thicker, in the accent color); the node selection is cleared |
|
||||
| **Shift**+click a wire | Adds it to the wire selection |
|
||||
| **Ctrl**+click a wire | Adds it to the wire selection, or removes it when it is already selected |
|
||||
| **Delete** or **Backspace** with wires selected | Deletes every selected wire (one undo step) |
|
||||
| **X** with two or more wires selected | Swaps where the selected wires come from (see below); they stay selected, so **X** again swaps back |
|
||||
| Drag a wire | Pulls a reroute **Dot** out of the wire where it was pressed and moves it with the pointer, in one gesture |
|
||||
| Double-click a wire | Drops a reroute Dot at that point |
|
||||
| Right-click a wire | Opens the wire menu: **Insert reroute dot**, **Delete link** |
|
||||
| Right-click a wire | Opens the wire menu: **Insert reroute dot**, **Swap selected links (X)** (with two or more selected), **Delete link** / **Delete selected links**. Right-clicking a wire that is already selected keeps the selection |
|
||||
| Click anywhere else | Drops the wire selection |
|
||||
|
||||
A wire is hit within 5 points of its curve. Node cards, ports and comments sit on top of wires, so
|
||||
a press there acts on them, not on the wire underneath. Alt+drag and middle-drag still pan the
|
||||
canvas.
|
||||
|
||||
### Swapping wires
|
||||
|
||||
Select the wires going into a node and press **X** to swap their sources. On a **Blend** node, select
|
||||
the *Foreground* and *Background* wires and press **X**: what fed the foreground now feeds the
|
||||
background and the other way around, so the two layers trade places without rewiring by hand.
|
||||
|
||||
- **Two wires** trade sources.
|
||||
- **More than two** reverse their sources. The wires are ordered by target node, then by the order
|
||||
of the inputs on the node (top to bottom), and the first wire's source goes to the last input,
|
||||
the second's to the one before it, and so on. With *Foreground*, *Background* and *Opacity*
|
||||
selected on a Blend, the foreground and opacity sources trade places and the background keeps
|
||||
its own.
|
||||
- The order you click the wires in does not matter, so the result is predictable.
|
||||
- Wires into different nodes can be swapped too. A swap that would feed a node into itself (a
|
||||
cycle) is refused with a message, and nothing changes.
|
||||
- One wire alone cannot be swapped: the editor says to select two or more.
|
||||
- The swap is one undo step.
|
||||
|
||||
### Reroute dots
|
||||
|
||||
A Dot is the existing `dot` node: one input, one output, passing its input through unchanged. It
|
||||
@@ -44,7 +65,9 @@ restores the straight wire.
|
||||
| Command | Params | Result |
|
||||
|---|---|---|
|
||||
| `graph.wire.insertDot` | `{to, toPort, at?: [x, y]}` | Splits the wire feeding `to.toPort` with a Dot centered at `at` (graph space; default: midway between the two nodes). Returns `{"id": <dot id>}` and selects the dot. Errors when no wire feeds that input. |
|
||||
| `graph.disconnect` | `{to, toPort}` | Deletes the wire feeding `to.toPort` (what the Delete key and **Delete link** run). |
|
||||
| `graph.wire.swap` | `{wires: [{to, toPort}, ...]}` | Swaps (two wires) or reverses (more) the sources of the listed wires, as described above. Returns `{"swapped": n}`. Errors with fewer than two wires, a wire listed twice, a missing wire or a cycle; nothing changes then. |
|
||||
| `graph.wire.delete` | `{wires: [{to, toPort}, ...]}` | Deletes the listed wires in one undo step (what the Delete key and the menu run). Returns `{"deleted": n}`. |
|
||||
| `graph.disconnect` | `{to, toPort}` | Deletes the single wire feeding `to.toPort`. |
|
||||
|
||||
Over the control channel (see [control-protocol.md](control-protocol.md)), splitting the wire
|
||||
feeding node 12's `input` with a dot at (240, 80), then deleting the wire from the dot to node 12:
|
||||
@@ -54,6 +77,12 @@ feeding node 12's `input` with a dot at (240, 80), then deleting the wire from t
|
||||
{"id": 2, "method": "command.run", "params": {"id": "graph.disconnect", "params": {"to": 12, "toPort": "input"}}}
|
||||
```
|
||||
|
||||
Swapping the two layers of Blend node 7:
|
||||
|
||||
```json
|
||||
{"id": 3, "method": "command.run", "params": {"id": "graph.wire.swap", "params": {"wires": [{"to": 7, "toPort": "foreground"}, {"to": 7, "toPort": "background"}]}}}
|
||||
```
|
||||
|
||||
`session.inspect` lists every wire under `graph.connections` and the dot under `graph.nodes`
|
||||
(`"def": "dot"`). The wire selection itself is editor state, like hover, and is not part of the
|
||||
session.
|
||||
@@ -103,7 +132,7 @@ It shows the first surface only, so the channel reads clearly.
|
||||
| `alphaView` | `false` | Show the alpha channel instead of the lit material |
|
||||
|
||||
```json
|
||||
{"id": 3, "method": "command.run", "params": {"id": "view.3d", "params": {"alphaView": true}}}
|
||||
{"id": 4, "method": "command.run", "params": {"id": "view.3d", "params": {"alphaView": true}}}
|
||||
```
|
||||
|
||||
Headless renders (`materialcraft-cli render`, the `render` RPC) use the same settings.
|
||||
@@ -113,11 +142,14 @@ Headless renders (`materialcraft-cli render`, the `render` RPC) use the same set
|
||||
- `crates/render/src/preview.rs`: `alpha()` picks the alpha source; `shade()` returns color, alpha
|
||||
and hit distance; `trace()` composites the layers (`MAX_LAYERS = 8`, stops once less than 0.1%
|
||||
of the light gets through); `Settings::{transparency, alpha_view}`.
|
||||
- `crates/engine/src/wire_cmds.rs`: `graph.wire.insertDot`.
|
||||
- `crates/engine/src/wire_cmds.rs`: `graph.wire.insertDot`, `graph.wire.swap` (unplugs every
|
||||
listed wire first, then reconnects, so a half-swapped state is never mistaken for a cycle) and
|
||||
`graph.wire.delete`.
|
||||
- `crates/ui-egui/src/graph_view.rs`: wire hit testing (`bezier_points`, `bezier_at`,
|
||||
`bezier_distance`, `wire_at`), the `WirePress` gesture, the wire menu and
|
||||
`delete_selected_wire`; `crates/ui-egui/src/menus.rs` gives Delete and Backspace to a selected
|
||||
wire before the node commands.
|
||||
`bezier_distance`, `wire_at`), the `WirePress` gesture, the multi-wire selection
|
||||
(`GraphView::selected_wires`), the wire menu, `delete_selected_wires` and
|
||||
`swap_selected_wires`; `crates/ui-egui/src/menus.rs` gives Delete, Backspace and X to selected
|
||||
wires before the node commands and shortcuts.
|
||||
- `crates/ui-egui/src/view3d.rs`: the Display menu toggles and the bottom-bar button.
|
||||
|
||||
## Tests
|
||||
@@ -127,6 +159,11 @@ Headless renders (`materialcraft-cli render`, the `render` RPC) use the same set
|
||||
color alpha, the alpha view shows exact values.
|
||||
- `a_wire_splits_with_a_reroute_dot_and_deletes` (engine): insertion, wiring, selection, cooking
|
||||
through the dot, single-step undo, the error with no wire, deletion.
|
||||
- `selected_wires_swap_their_sources_and_delete_together` (engine): two-wire swap in any order,
|
||||
three-wire reverse, single-step undo, refused requests (one wire, duplicates, missing wires),
|
||||
a refused cycle that leaves the graph unchanged, deleting several wires in one step.
|
||||
- `graph_view::tests::clicked_wires_swap_with_x_and_delete_together`: real clicks on a Blend
|
||||
node's two wires (the second with Shift), X swaps, X again swaps back, Delete removes both.
|
||||
- `every_template_is_opaque_in_the_3d_view` (engine): no built-in template turns see-through.
|
||||
- `graph_view::tests::wires_are_hit_near_their_curve_only`: wire hit testing.
|
||||
- The `snapshots` UI test renders both screenshots on this page (`alpha-transparency`,
|
||||
|
||||
Reference in new issue
Block a user