mirror of
https://github.com/storytold/materialcraft.git
synced 2026-11-22 07:20:57 +01:00
Merge pull request #182 from storytold/181-fixing---ui-library-improvement
Listing all nodes from custom functions.sbs
This commit is contained in:
122 files changed
+4768
-645
No files matched your search
Binary file not shown.
|
Before Width: | Height: | Size: 3.2 KiB |
@@ -1 +0,0 @@
|
||||
<?xml version="1.0" encoding="UTF-8"?><package><identifier v="Unsaved Package"/><formatVersion v="1.1.0.202401"/><updaterVersion v="1.1.0.202401"/><fileUID v="{d761218c-6535-4012-a000-21216d08e74e}"/><versionUID v="0"/><dependencies><dependency><filename v="?himself"/><uid v="1584632780"/><type v="package"/><fileUID v="0"/><versionUID v="0"/></dependency><dependency><filename v="sbs://3d_perlin_noise.sbs"/><uid v="1437570156"/><type v="package"/><fileUID v="0"/><versionUID v="0"/></dependency><dependency><filename v="sbs://3d_simplex_noise.sbs"/><uid v="1311275138"/><type v="package"/><fileUID v="0"/><versionUID v="0"/></dependency><dependency><filename v="sbs://noise_voronoi.sbs"/><uid v="1440766644"/><type v="package"/><fileUID v="0"/><versionUID v="0"/></dependency><dependency><filename v="sbs://3d_worley_noise.sbs"/><uid v="1217378548"/><type v="package"/><fileUID v="0"/><versionUID v="0"/></dependency><dependency><filename v="sbs://noise_anisotropic_noise.sbs"/><uid v="1584639338"/><type v="package"/><fileUID v="0"/><versionUID v="0"/></dependency><dependency><filename v="sbs://blue_noise.sbs"/><uid v="1584639858"/><type v="package"/><fileUID v="0"/><versionUID v="0"/></dependency><dependency><filename v="sbs://noise_bnw_spots_1.sbs"/><uid v="1584639913"/><type v="package"/><fileUID v="0"/><versionUID v="0"/></dependency><dependency><filename v="sbs://noise_bnw_spots_2.sbs"/><uid v="1584640143"/><type v="package"/><fileUID v="0"/><versionUID v="0"/></dependency><dependency><filename v="sbs://noise_bnw_spots_3.sbs"/><uid v="1299276443"/><type v="package"/><fileUID v="0"/><versionUID v="0"/></dependency><dependency><filename v="sbs://noise_cells_1.sbs"/><uid v="1584642533"/><type v="package"/><fileUID v="0"/><versionUID v="0"/></dependency><dependency><filename v="sbs://noise_cells_2.sbs"/><uid v="1584642645"/><type v="package"/><fileUID v="0"/><versionUID v="0"/></dependency><dependency><filename v="sbs://noise_cells_3.sbs"/><uid v="1584643037"/><type v="package"/><fileUID v="0"/><versionUID v="0"/></dependency><dependency><filename v="sbs://noise_cells_4.sbs"/><uid v="1299276447"/><type v="package"/><fileUID v="0"/><versionUID v="0"/></dependency><dependency><filename v="sbs://noise_clouds_1.sbs"/><uid v="1584643174"/><type v="package"/><fileUID v="0"/><versionUID v="0"/></dependency><dependency><filename v="sbs://noise_clouds_2.sbs"/><uid v="1584643519"/><type v="package"/><fileUID v="0"/><versionUID v="0"/></dependency><dependency><filename v="sbs://noise_clouds_3.sbs"/><uid v="1584643869"/><type v="package"/><fileUID v="0"/><versionUID v="0"/></dependency><dependency><filename v="sbs://noise_creased.sbs"/><uid v="1584644203"/><type v="package"/><fileUID v="0"/><versionUID v="0"/></dependency><dependency><filename v="sbs://noise_crystal_1.sbs"/><uid v="1584644394"/><type v="package"/><fileUID v="0"/><versionUID v="0"/></dependency><dependency><filename v="sbs://noise_crystal_2.sbs"/><uid v="1584644622"/><type v="package"/><fileUID v="0"/><versionUID v="0"/></dependency><dependency><filename v="sbs://noise_directional_noise_1.sbs"/><uid v="1584645560"/><type v="package"/><fileUID v="0"/><versionUID v="0"/></dependency><dependency><filename v="sbs://noise_directional_noise_2.sbs"/><uid v="1584646017"/><type v="package"/><fileUID v="0"/><versionUID v="0"/></dependency><dependency><filename v="sbs://noise_directional_noise_3.sbs"/><uid v="1584646196"/><type v="package"/><fileUID v="0"/><versionUID v="0"/></dependency><dependency><filename v="sbs://noise_directional_noise_4.sbs"/><uid v="1584646656"/><type v="package"/><fileUID v="0"/><versionUID v="0"/></dependency><dependency><filename v="sbs://noise_directional_scratches.sbs"/><uid v="1584646818"/><type v="package"/><fileUID v="0"/><versionUID v="0"/></dependency><dependency><filename v="sbs://noise_dirt_1.sbs"/><uid v="1299276460"/><type v="package"/><fileUID v="0"/><versionUID v="0"/></dependency><dependency><filename v="sbs://noise_dirt_2.sbs"/><uid v="1584646981"/><type v="package"/><fileUID v="0"/><versionUID v="0"/></dependency><dependency><filename v="sbs://noise_dirt_3.sbs"/><uid v="1584647143"/><type v="package"/><fileUID v="0"/><versionUID v="0"/></dependency><dependency><filename v="sbs://noise_dirt_4.sbs"/><uid v="1584647426"/><type v="package"/><fileUID v="0"/><versionUID v="0"/></dependency><dependency><filename v="sbs://noise_dirt_5.sbs"/><uid v="1584647603"/><type v="package"/><fileUID v="0"/><versionUID v="0"/></dependency><dependency><filename v="sbs://noise_dirt_gradient.sbs"/><uid v="1584647753"/><type v="package"/><fileUID v="0"/><versionUID v="0"/></dependency><dependency><filename v="sbs://noise_fluid.sbs"/><uid v="1584648733"/><type v="package"/><fileUID v="0"/><versionUID v="0"/></dependency><dependency><filename v="sbs://noise_fractal_sum_1.sbs"/><uid v="1584648924"/><type v="package"/><fileUID v="0"/><versionUID v="0"/></dependency><dependency><filename v="sbs://noise_fractal_sum_2.sbs"/><uid v="1584650329"/><type v="packageLine truncated
|
||||
@@ -1 +1 @@
|
||||
<?xml version="1.0" encoding="UTF-8"?><package><identifier v="Functions"/><formatVersion v="1.1.0.202401"/><updaterVersion v="0.1.3"/><fileUID v="0"/><versionUID v="0"/><dependencies><dependency><filename v="?himself"/><uid v="1000000001"/><type v="package"/><fileUID v="0"/><versionUID v="0"/></dependency></dependencies><content><group><identifier v="Functions"/><uid v="1000000002"/><content><group><identifier v="Tonemappers"/><uid v="1000000003"/><content><function><identifier v="tonemap_Hejl"/><uid v="1000000039"/><attributes><category v="Functions/Tonemappers"/><description v="Evaluates the tonemap_Hejl function graph. Result type: Float3. Inputs: input."/><author v=""/><tags v=""/></attributes><paraminputs><paraminput><identifier v="input"/><uid v="1000000040"/><attributes><label v="input"/></attributes><type v="1024"/><defaultValue><constantValueFloat3 v="1 1 1"/></defaultValue><defaultWidget><name v="slider"/><options><option><name v="min"/><value v="0"/></option><option><name v="max"/><value v="1"/></option></options></defaultWidget></paraminput></paraminputs><type v="1024"/><paramValue><dynamicValue><rootnode v="1000000029"/><paramNodes><paramNode><uid v="1000000004"/><function v="max"/><type v="1024"/><GUILayout><gpos v="624 64 0"/></GUILayout><connections><connection><identifier v="a"/><connRef v="1000000018"/></connection><connection><identifier v="b"/><connRef v="1000000011"/></connection></connections></paramNode><paramNode><uid v="1000000005"/><function v="add"/><type v="1024"/><GUILayout><gpos v="1184 64 0"/></GUILayout><connections><connection><identifier v="a"/><connRef v="1000000028"/></connection><connection><identifier v="b"/><connRef v="1000000023"/></connection></connections></paramNode><paramNode><uid v="1000000006"/><function v="mulscalar"/><type v="1024"/><GUILayout><gpos v="904 64 0"/></GUILayout><connections><connection><identifier v="a"/><connRef v="1000000004"/></connection><connection><identifier v="scalar"/><connRef v="1000000012"/></connection></connections></paramNode><paramNode><uid v="1000000007"/><function v="const_float1"/><type v="256"/><GUILayout><gpos v="64 64 0"/></GUILayout><connections></connections><funcDatas><funcData><name v="const_float1"/><constantValue><constantValueFloat1 v="1.25"/></constantValue></funcData></funcDatas></paramNode><paramNode><uid v="1000000008"/><function v="swizzle3"/><type v="1024"/><GUILayout><gpos v="624 224 0"/></GUILayout><connections><connection><identifier v="vector"/><connRef v="1000000016"/></connection></connections><funcDatas><funcData><name v="swizzle3"/><constantValue><constantValueInt3 v="0 0 0"/></constantValue></funcData></funcDatas></paramNode><paramNode><uid v="1000000009"/><function v="swizzle3"/><type v="1024"/><GUILayout><gpos v="344 64 0"/></GUILayout><connections><connection><identifier v="vector"/><connRef v="1000000021"/></connection></connections><funcDatas><funcData><name v="swizzle3"/><constantValue><constantValueInt3 v="0 0 0"/></constantValue></funcData></funcDatas></paramNode><paramNode><uid v="1000000010"/><function v="mulscalar"/><type v="1024"/><GUILayout><gpos v="904 224 0"/></GUILayout><connections><connection><identifier v="a"/><connRef v="1000000019"/></connection><connection><identifier v="scalar"/><connRef v="1000000007"/></connection></connections></paramNode><paramNode><uid v="1000000011"/><function v="const_float3"/><type v="1024"/><GUILayout><gpos v="64 224 0"/></GUILayout><connections></connections><funcDatas><funcData><name v="const_float3"/><constantValue><constantValueFloat3 v="0 0 0"/></constantValue></funcData></funcDatas></paramNode><paramNode><uid v="1000000012"/><function v="const_float1"/><type v="256"/><GUILayout><gpos v="64 384 0"/></GUILayout><connections></connections><funcDatas><funcData><name v="const_float1"/><constantValue><constantValueFloat1 v="0.22"/></constantValue></funcData></funcDatas></paramNode><paramNode><uid v="1000000013"/><function v="mul"/><type v="256"/><GUILayout><gpos v="344 224 0"/></GUILayout><connections><connection><identifier v="a"/><connRef v="1000000037"/></connection><connection><identifier v="b"/><connRef v="1000000022"/></connection></connections></paramNode><paramNode><uid v="1000000014"/><function v="mul"/><type v="1024"/><GUILayout><gpos v="1464 64 0"/></GUILayout><connections><connection><identifier v="a"/><connRef v="1000000004"/></connection><connection><identifier v="b"/><connRef v="1000000005"/></connection></connections></paramNode><paramNode><uid v="1000000015"/><function v="mul"/><type v="256"/><GUILayout><gpos v="344 384 0"/></GUILayout><connections><connection><identifier v="a"/><connRef v="1000000037"/></connection><connection><identifier v="b"/><connRef v="1000000032"/></connection></connections></paramNode><paramNode><uid v="1000000016"/><function v="div"/><type v="256"/><GUILayout><gpos v="344 544 0"/></GUILayout><connections><connection><identifier v="a"/><connRef v="1000000032"/></connection><connection><identifier v="b"/><connRef vLine truncated
|
||||
<?xml version="1.0" encoding="UTF-8"?><package><identifier v="Functions"/><formatVersion v="1.1.0.202401"/><updaterVersion v="0.1.3"/><fileUID v="0"/><versionUID v="0"/><dependencies><dependency><filename v="?himself"/><uid v="1000000001"/><type v="package"/><fileUID v="0"/><versionUID v="0"/></dependency></dependencies><content><group><identifier v="Functions"/><uid v="1000000002"/><content><group><identifier v="Tonemappers"/><uid v="1000000003"/><content><function><identifier v="tonemap_Hejl"/><uid v="1000000039"/><attributes><category v=""/><description v="Evaluates the tonemap_Hejl function graph. Result type: Float3. Inputs: input."/><author v=""/><tags v="Color"/></attributes><paraminputs><paraminput><identifier v="input"/><uid v="1000000040"/><attributes><label v="input"/></attributes><type v="1024"/><defaultValue><constantValueFloat3 v="1 1 1"/></defaultValue><defaultWidget><name v="slider"/><options><option><name v="min"/><value v="0"/></option><option><name v="max"/><value v="1"/></option></options></defaultWidget></paraminput></paraminputs><type v="1024"/><paramValue><dynamicValue><rootnode v="1000000029"/><paramNodes><paramNode><uid v="1000000004"/><function v="max"/><type v="1024"/><GUILayout><gpos v="624 64 0"/></GUILayout><connections><connection><identifier v="a"/><connRef v="1000000018"/></connection><connection><identifier v="b"/><connRef v="1000000011"/></connection></connections></paramNode><paramNode><uid v="1000000005"/><function v="add"/><type v="1024"/><GUILayout><gpos v="1184 64 0"/></GUILayout><connections><connection><identifier v="a"/><connRef v="1000000028"/></connection><connection><identifier v="b"/><connRef v="1000000023"/></connection></connections></paramNode><paramNode><uid v="1000000006"/><function v="mulscalar"/><type v="1024"/><GUILayout><gpos v="904 64 0"/></GUILayout><connections><connection><identifier v="a"/><connRef v="1000000004"/></connection><connection><identifier v="scalar"/><connRef v="1000000012"/></connection></connections></paramNode><paramNode><uid v="1000000007"/><function v="const_float1"/><type v="256"/><GUILayout><gpos v="64 64 0"/></GUILayout><connections></connections><funcDatas><funcData><name v="const_float1"/><constantValue><constantValueFloat1 v="1.25"/></constantValue></funcData></funcDatas></paramNode><paramNode><uid v="1000000008"/><function v="swizzle3"/><type v="1024"/><GUILayout><gpos v="624 224 0"/></GUILayout><connections><connection><identifier v="vector"/><connRef v="1000000016"/></connection></connections><funcDatas><funcData><name v="swizzle3"/><constantValue><constantValueInt3 v="0 0 0"/></constantValue></funcData></funcDatas></paramNode><paramNode><uid v="1000000009"/><function v="swizzle3"/><type v="1024"/><GUILayout><gpos v="344 64 0"/></GUILayout><connections><connection><identifier v="vector"/><connRef v="1000000021"/></connection></connections><funcDatas><funcData><name v="swizzle3"/><constantValue><constantValueInt3 v="0 0 0"/></constantValue></funcData></funcDatas></paramNode><paramNode><uid v="1000000010"/><function v="mulscalar"/><type v="1024"/><GUILayout><gpos v="904 224 0"/></GUILayout><connections><connection><identifier v="a"/><connRef v="1000000019"/></connection><connection><identifier v="scalar"/><connRef v="1000000007"/></connection></connections></paramNode><paramNode><uid v="1000000011"/><function v="const_float3"/><type v="1024"/><GUILayout><gpos v="64 224 0"/></GUILayout><connections></connections><funcDatas><funcData><name v="const_float3"/><constantValue><constantValueFloat3 v="0 0 0"/></constantValue></funcData></funcDatas></paramNode><paramNode><uid v="1000000012"/><function v="const_float1"/><type v="256"/><GUILayout><gpos v="64 384 0"/></GUILayout><connections></connections><funcDatas><funcData><name v="const_float1"/><constantValue><constantValueFloat1 v="0.22"/></constantValue></funcData></funcDatas></paramNode><paramNode><uid v="1000000013"/><function v="mul"/><type v="256"/><GUILayout><gpos v="344 224 0"/></GUILayout><connections><connection><identifier v="a"/><connRef v="1000000037"/></connection><connection><identifier v="b"/><connRef v="1000000022"/></connection></connections></paramNode><paramNode><uid v="1000000014"/><function v="mul"/><type v="1024"/><GUILayout><gpos v="1464 64 0"/></GUILayout><connections><connection><identifier v="a"/><connRef v="1000000004"/></connection><connection><identifier v="b"/><connRef v="1000000005"/></connection></connections></paramNode><paramNode><uid v="1000000015"/><function v="mul"/><type v="256"/><GUILayout><gpos v="344 384 0"/></GUILayout><connections><connection><identifier v="a"/><connRef v="1000000037"/></connection><connection><identifier v="b"/><connRef v="1000000032"/></connection></connections></paramNode><paramNode><uid v="1000000016"/><function v="div"/><type v="256"/><GUILayout><gpos v="344 544 0"/></GUILayout><connections><connection><identifier v="a"/><connRef v="1000000032"/></connection><connection><identifier v="b"/><connRef v="1000000022"/><Line truncated
|
||||
@@ -0,0 +1,32 @@
|
||||
use crate::{Comment, Frame, Pin};
|
||||
use serde::{Deserialize, Serialize};
|
||||
|
||||
/// Editable helpers belonging to one embedded graph canvas.
|
||||
#[derive(Clone, Debug, Default, PartialEq, Serialize, Deserialize)]
|
||||
pub struct CanvasAnnotations {
|
||||
#[serde(default)]
|
||||
pub frames: Vec<Frame>,
|
||||
#[serde(default)]
|
||||
pub comments: Vec<Comment>,
|
||||
#[serde(default)]
|
||||
pub pins: Vec<Pin>,
|
||||
}
|
||||
|
||||
impl CanvasAnnotations {
|
||||
/// Whether the canvas has no frames, comments or pins.
|
||||
pub fn is_empty(&self) -> bool {
|
||||
self.frames.is_empty() && self.comments.is_empty() && self.pins.is_empty()
|
||||
}
|
||||
|
||||
/// The next annotation id, or none when all ids have been exhausted.
|
||||
pub fn next_id(&self) -> Option<u64> {
|
||||
self.frames
|
||||
.iter()
|
||||
.map(|frame| frame.id)
|
||||
.chain(self.comments.iter().map(|comment| comment.id))
|
||||
.chain(self.pins.iter().map(|pin| pin.id))
|
||||
.max()
|
||||
.unwrap_or(0)
|
||||
.checked_add(1)
|
||||
}
|
||||
}
|
||||
@@ -6,6 +6,8 @@ use crate::FunctionNode;
|
||||
|
||||
#[derive(Clone, Debug, Default, PartialEq, Serialize, Deserialize)]
|
||||
pub struct FunctionGraph {
|
||||
#[serde(default, skip_serializing_if = "crate::CanvasAnnotations::is_empty")]
|
||||
pub annotations: crate::CanvasAnnotations,
|
||||
pub nodes: Vec<FunctionNode>,
|
||||
#[serde(default)]
|
||||
pub output: Option<u32>,
|
||||
|
||||
@@ -3,6 +3,7 @@
|
||||
|
||||
mod attributes;
|
||||
mod base_parameters;
|
||||
mod canvas_annotations;
|
||||
mod color;
|
||||
mod comment;
|
||||
mod component_usage;
|
||||
@@ -33,6 +34,7 @@ mod pattern_graph;
|
||||
mod pattern_node;
|
||||
mod pattern_node_kind;
|
||||
mod pin;
|
||||
pub use canvas_annotations::CanvasAnnotations;
|
||||
mod preset;
|
||||
mod resource;
|
||||
mod resource_bytes;
|
||||
|
||||
@@ -5,6 +5,8 @@ use crate::{PatternNode, PatternNodeKind};
|
||||
|
||||
#[derive(Clone, Debug, Default, PartialEq, Serialize, Deserialize)]
|
||||
pub struct PatternGraph {
|
||||
#[serde(default, skip_serializing_if = "crate::CanvasAnnotations::is_empty")]
|
||||
pub annotations: crate::CanvasAnnotations,
|
||||
pub nodes: Vec<PatternNode>,
|
||||
pub root: Option<u32>,
|
||||
}
|
||||
@@ -12,6 +14,7 @@ pub struct PatternGraph {
|
||||
impl PatternGraph {
|
||||
pub fn with_root(kind: PatternNodeKind) -> Self {
|
||||
Self {
|
||||
annotations: Default::default(),
|
||||
root: Some(1),
|
||||
nodes: vec![PatternNode { id: 1, kind, children: vec![None; kind.child_count()], parameters: BTreeMap::new(), position: [0.0; 2] }],
|
||||
}
|
||||
|
||||
@@ -8,13 +8,15 @@ pub(crate) fn specs() -> Vec<CommandSpec> {
|
||||
"Select annotation",
|
||||
[],
|
||||
None,
|
||||
"{kind?: frame|comment, id?} clears node selection; omit kind to deselect",
|
||||
"{kind?: frame|comment|pin, id?} clears node selection; omit kind to deselect",
|
||||
has_graph,
|
||||
select
|
||||
)]
|
||||
}
|
||||
|
||||
fn select(session: &mut Session, parameters: &Value) -> Result<Value> {
|
||||
let target = crate::AnnotationTarget::resolve(session, parameters)?;
|
||||
let items = target.items(session)?;
|
||||
let selection = match strp(parameters, "kind") {
|
||||
None => None,
|
||||
Some(kind) => {
|
||||
@@ -22,9 +24,10 @@ fn select(session: &mut Session, parameters: &Value) -> Result<Value> {
|
||||
let selection = match kind {
|
||||
"frame" => AnnotationSelection::Frame(id),
|
||||
"comment" => AnnotationSelection::Comment(id),
|
||||
_ => return Err(bad("graph.annotation.select", "kind must be frame or comment")),
|
||||
"pin" => AnnotationSelection::Pin(id),
|
||||
_ => return Err(bad("graph.annotation.select", "kind must be frame, comment or pin")),
|
||||
};
|
||||
if !selection.exists(session.graph()?) {
|
||||
if !selection.exists(&items) {
|
||||
return Err(bad("graph.annotation.select", "annotation does not exist"));
|
||||
}
|
||||
|
||||
@@ -32,6 +35,7 @@ fn select(session: &mut Session, parameters: &Value) -> Result<Value> {
|
||||
}
|
||||
};
|
||||
|
||||
session.annotation_target = target;
|
||||
session.annotation_selection = selection;
|
||||
if selection.is_some() {
|
||||
session.selection.clear();
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
use materialcraft_core::Graph;
|
||||
use materialcraft_core::CanvasAnnotations;
|
||||
use serde::{Deserialize, Serialize};
|
||||
|
||||
#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize)]
|
||||
@@ -6,13 +6,15 @@ use serde::{Deserialize, Serialize};
|
||||
pub enum AnnotationSelection {
|
||||
Frame(u64),
|
||||
Comment(u64),
|
||||
Pin(u64),
|
||||
}
|
||||
|
||||
impl AnnotationSelection {
|
||||
pub fn exists(self, graph: &Graph) -> bool {
|
||||
pub fn exists(self, graph: &CanvasAnnotations) -> bool {
|
||||
match self {
|
||||
Self::Frame(id) => graph.frames.iter().any(|frame| frame.id == id),
|
||||
Self::Comment(id) => graph.comments.iter().any(|comment| comment.id == id),
|
||||
Self::Pin(id) => graph.pins.iter().any(|pin| pin.id == id),
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,150 @@
|
||||
use crate::{FrameContents, FunctionGraphTarget, Result, SelectionTarget, Session, commands::bad};
|
||||
use materialcraft_core::{CanvasAnnotations, Frame, NodeId, Value};
|
||||
use serde::{Deserialize, Serialize};
|
||||
use serde_json::{Value as Json, json};
|
||||
|
||||
/// Canvas that owns the selected frame, comment or navigation pin.
|
||||
#[derive(Clone, Debug, Default, PartialEq, Eq, Serialize, Deserialize)]
|
||||
#[serde(tag = "kind", rename_all = "camelCase")]
|
||||
pub enum AnnotationTarget {
|
||||
#[default]
|
||||
Graph,
|
||||
Function {
|
||||
target: FunctionGraphTarget,
|
||||
},
|
||||
Pattern {
|
||||
owner: NodeId,
|
||||
},
|
||||
}
|
||||
|
||||
impl AnnotationTarget {
|
||||
pub(crate) fn resolve(session: &Session, parameters: &Json) -> Result<Self> {
|
||||
Ok(match SelectionTarget::resolve(session, parameters)? {
|
||||
None | Some(SelectionTarget::Function(FunctionGraphTarget::Graph)) => Self::Graph,
|
||||
Some(SelectionTarget::Function(target)) => Self::Function { target },
|
||||
Some(SelectionTarget::Pattern(owner)) => Self::Pattern { owner },
|
||||
})
|
||||
}
|
||||
|
||||
/// Command parameters that address this canvas.
|
||||
pub fn parameters(&self) -> Json {
|
||||
match self {
|
||||
Self::Graph => json!({}),
|
||||
Self::Function { target } => json!({"function": target}),
|
||||
Self::Pattern { owner } => json!({"pattern": owner.0}),
|
||||
}
|
||||
}
|
||||
|
||||
/// Copy the annotations owned by this canvas.
|
||||
pub fn items(&self, session: &Session) -> Result<CanvasAnnotations> {
|
||||
Ok(match self {
|
||||
Self::Graph => {
|
||||
let graph = session.graph()?;
|
||||
CanvasAnnotations { frames: graph.frames.clone(), comments: graph.comments.clone(), pins: graph.pins.clone() }
|
||||
}
|
||||
Self::Function { target } => target.current(session)?.annotations.clone(),
|
||||
Self::Pattern { owner } => SelectionTarget::pattern(session, *owner)?.annotations.clone(),
|
||||
})
|
||||
}
|
||||
|
||||
pub(crate) fn replace(&self, session: &mut Session, items: CanvasAnnotations) -> Result<()> {
|
||||
match self {
|
||||
Self::Graph => {
|
||||
let graph = session.graph_mut()?;
|
||||
graph.next_id = graph.next_id.max(items.next_id().unwrap_or(u64::MAX));
|
||||
graph.frames = items.frames;
|
||||
graph.comments = items.comments;
|
||||
graph.pins = items.pins;
|
||||
}
|
||||
Self::Function { target } => {
|
||||
let mut function = target.current(session)?.clone();
|
||||
function.annotations = items;
|
||||
target.replace(session, function)?;
|
||||
}
|
||||
Self::Pattern { owner } => {
|
||||
let mut graph = SelectionTarget::pattern(session, *owner)?.clone();
|
||||
graph.annotations = items;
|
||||
session.graph_mut()?.node_mut(*owner)?.params.insert("pattern".into(), Value::PatternGraph(Box::new(graph)));
|
||||
}
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
pub(crate) fn next_id(&self, session: &Session, items: &CanvasAnnotations) -> Result<u64> {
|
||||
let next = items.next_id().ok_or_else(|| bad("graph annotation", "no available annotation id"))?;
|
||||
Ok(if *self == Self::Graph { next.max(session.graph()?.next_id) } else { next })
|
||||
}
|
||||
|
||||
/// Node positions in this canvas, using the shared node-id representation.
|
||||
pub fn positions(&self, session: &Session) -> Result<Vec<(NodeId, [f32; 2])>> {
|
||||
Ok(match self {
|
||||
Self::Graph => {
|
||||
let graph = session.graph()?;
|
||||
match &graph.function {
|
||||
Some(function) => function.nodes.iter().map(|node| (NodeId(u64::from(node.id)), node.pos)).collect(),
|
||||
None => graph.nodes.iter().map(|node| (node.id, node.pos)).collect(),
|
||||
}
|
||||
}
|
||||
Self::Function { target } => target.current(session)?.nodes.iter().map(|node| (NodeId(u64::from(node.id)), node.pos)).collect(),
|
||||
Self::Pattern { owner } => {
|
||||
SelectionTarget::pattern(session, *owner)?.nodes.iter().map(|node| (NodeId(u64::from(node.id)), node.position)).collect()
|
||||
}
|
||||
})
|
||||
}
|
||||
|
||||
/// Capture the nodes and annotations moved with a frame.
|
||||
pub fn capture_frame(&self, session: &Session, frame: &Frame) -> Result<FrameContents> {
|
||||
if *self == Self::Graph {
|
||||
return Ok(FrameContents::capture(session.graph()?, frame));
|
||||
}
|
||||
|
||||
let items = self.items(session)?;
|
||||
let nodes: Vec<_> = self.positions(session)?.into_iter().filter(|(_, position)| frame.contains_position(*position)).map(|(id, _)| id).collect();
|
||||
Ok(FrameContents {
|
||||
function_nodes: nodes.iter().filter_map(|id| u32::try_from(id.0).ok()).collect(),
|
||||
nodes,
|
||||
comments: items.comments.iter().filter(|comment| frame.contains_position(comment.pos)).map(|comment| comment.id).collect(),
|
||||
frames: items.frames.iter().filter(|candidate| candidate.id == frame.id || frame.contains_rect(candidate.rect)).map(|frame| frame.id).collect(),
|
||||
pins: items.pins.iter().filter(|pin| frame.contains_position(pin.pos)).map(|pin| pin.id).collect(),
|
||||
})
|
||||
}
|
||||
|
||||
pub(crate) fn move_contents(&self, session: &mut Session, contents: &FrameContents, offset: [f32; 2]) -> Result<()> {
|
||||
if *self == Self::Graph {
|
||||
contents.translate(session.graph_mut()?, offset);
|
||||
return Ok(());
|
||||
}
|
||||
|
||||
let translate = |position: [f32; 2]| crate::graph_grid::snap_position([position[0] + offset[0], position[1] + offset[1]], false);
|
||||
match self {
|
||||
Self::Function { target } => {
|
||||
let mut graph = target.current(session)?.clone();
|
||||
for node in graph.nodes.iter_mut().filter(|node| contents.function_nodes.contains(&node.id)) {
|
||||
node.pos = translate(node.pos);
|
||||
}
|
||||
target.replace(session, graph)?;
|
||||
}
|
||||
Self::Pattern { owner } => {
|
||||
let mut graph = SelectionTarget::pattern(session, *owner)?.clone();
|
||||
for node in graph.nodes.iter_mut().filter(|node| contents.nodes.contains(&NodeId(u64::from(node.id)))) {
|
||||
node.position = translate(node.position);
|
||||
}
|
||||
session.graph_mut()?.node_mut(*owner)?.params.insert("pattern".into(), Value::PatternGraph(Box::new(graph)));
|
||||
}
|
||||
Self::Graph => {}
|
||||
}
|
||||
let mut items = self.items(session)?;
|
||||
for comment in items.comments.iter_mut().filter(|comment| contents.comments.contains(&comment.id)) {
|
||||
comment.pos = translate(comment.pos);
|
||||
}
|
||||
for frame in items.frames.iter_mut().filter(|frame| contents.frames.contains(&frame.id)) {
|
||||
let position = translate([frame.rect[0], frame.rect[1]]);
|
||||
frame.rect[0] = position[0];
|
||||
frame.rect[1] = position[1];
|
||||
}
|
||||
for pin in items.pins.iter_mut().filter(|pin| contents.pins.contains(&pin.id)) {
|
||||
pin.pos = translate(pin.pos);
|
||||
}
|
||||
self.replace(session, items)
|
||||
}
|
||||
}
|
||||
@@ -60,6 +60,7 @@ pub fn command_specs() -> &'static [CommandSpec] {
|
||||
v.extend(crate::explorer_clipboard_commands::specs());
|
||||
v.extend(crate::graph_instance_commands::specs());
|
||||
v.extend(crate::function_library_commands::specs());
|
||||
v.extend(crate::node_library_commands::specs());
|
||||
v.extend(crate::node_info_commands::specs());
|
||||
v.extend(crate::atomic_sample_commands::specs());
|
||||
v.extend(crate::material_cmds::specs());
|
||||
@@ -76,6 +77,7 @@ pub fn command_specs() -> &'static [CommandSpec] {
|
||||
v.extend(crate::function_variable_commands::specs());
|
||||
v.extend(crate::evaluation_environment_commands::specs());
|
||||
v.extend(crate::comment_commands::specs());
|
||||
v.extend(crate::pin_commands::specs());
|
||||
v.extend(crate::node_cmds::specs());
|
||||
v.extend(crate::node_graph_commands::specs());
|
||||
v.extend(crate::pattern_graph_commands::specs());
|
||||
@@ -100,7 +102,7 @@ pub fn execute(s: &mut Session, id: &str, params: &J) -> Result<J> {
|
||||
}
|
||||
(spec.enabled)(s).map_err(|why| EngineError::Disabled { cmd: id.to_string(), why })?;
|
||||
let result = (spec.run)(s, params)?;
|
||||
if !s.selection.is_empty() || s.annotation_selection.is_some_and(|selection| !s.graph().is_ok_and(|graph| selection.exists(graph))) {
|
||||
if !s.selection.is_empty() || s.annotation_selection.is_some_and(|selection| !s.annotation_target.items(s).is_ok_and(|items| selection.exists(&items))) {
|
||||
s.annotation_selection = None;
|
||||
}
|
||||
|
||||
@@ -116,6 +118,8 @@ pub fn list(s: &Session, filter: Option<&str>) -> J {
|
||||
.filter(|c| f.as_ref().is_none_or(|f| c.id.to_ascii_lowercase().contains(f) || c.label.to_ascii_lowercase().contains(f)))
|
||||
.map(|c| json!({"id": c.id, "label": c.label, "menu": c.menu, "shortcut": c.shortcut, "params": if crate::selection_commands::supports(c.id) {
|
||||
format!("{}; optional function: FunctionGraphTarget or pattern: owner node id, graph: owning graph index; embedded targets use explicit ids; copy returns clip", c.params)
|
||||
} else if c.id.starts_with("graph.annotation.") || c.id.starts_with("graph.frame.") || c.id.starts_with("graph.comment.") {
|
||||
format!("{}; optional function: FunctionGraphTarget or pattern: owner node id", c.params)
|
||||
} else { c.params.to_string() }, "enabled": crate::selection_commands::enabled(s, c.id, &J::Null).unwrap_or_else(|| (c.enabled)(s).is_ok())}))
|
||||
.collect(),
|
||||
)
|
||||
|
||||
@@ -13,13 +13,16 @@ pub(crate) fn specs() -> Vec<CommandSpec> {
|
||||
}
|
||||
|
||||
fn comment_add(session: &mut Session, parameters: &J) -> Result<J> {
|
||||
let target = crate::AnnotationTarget::resolve(session, parameters)?;
|
||||
let at = point(parameters, "at").or_else(|| nodes_rect(session, &session.selection).map(|rect| [rect[0], rect[1] - 90.0])).unwrap_or([0.0, -120.0]);
|
||||
let text = strp(parameters, "text").unwrap_or("Comment").to_string();
|
||||
|
||||
session.edit("Add comment", |session| {
|
||||
let graph = session.graph_mut()?;
|
||||
let id = graph.alloc_id();
|
||||
graph.comments.push(Comment { id, text, pos: at, size: [180.0, 70.0] });
|
||||
let mut items = target.items(session)?;
|
||||
let id = target.next_id(session, &items)?;
|
||||
items.comments.push(Comment { id, text, pos: at, size: [180.0, 70.0] });
|
||||
target.replace(session, items)?;
|
||||
session.annotation_target = target;
|
||||
session.selection.clear();
|
||||
session.annotation_selection = Some(AnnotationSelection::Comment(id));
|
||||
Ok(json!({"id": id}))
|
||||
@@ -27,11 +30,12 @@ fn comment_add(session: &mut Session, parameters: &J) -> Result<J> {
|
||||
}
|
||||
|
||||
fn comment_edit(session: &mut Session, parameters: &J) -> Result<J> {
|
||||
let target = crate::AnnotationTarget::resolve(session, parameters)?;
|
||||
let id = u64p(parameters, "id").ok_or_else(|| bad("graph.comment.edit", "`id` is required"))?;
|
||||
|
||||
session.edit_merged(&format!("comment{id}"), "Edit comment", |session| {
|
||||
let comment =
|
||||
session.graph_mut()?.comments.iter_mut().find(|comment| comment.id == id).ok_or_else(|| bad("graph.comment.edit", format!("no comment {id}")))?;
|
||||
session.edit_merged(&format!("comment:{target:?}:{id}"), "Edit comment", |session| {
|
||||
let mut items = target.items(session)?;
|
||||
let comment = items.comments.iter_mut().find(|comment| comment.id == id).ok_or_else(|| bad("graph.comment.edit", format!("no comment {id}")))?;
|
||||
if let Some(text) = strp(parameters, "text") {
|
||||
comment.text = text.into();
|
||||
}
|
||||
@@ -42,16 +46,20 @@ fn comment_edit(session: &mut Session, parameters: &J) -> Result<J> {
|
||||
comment.size = [size[0].max(40.0), size[1].max(24.0)];
|
||||
}
|
||||
|
||||
target.replace(session, items)?;
|
||||
Ok(J::Null)
|
||||
})
|
||||
}
|
||||
|
||||
fn comment_delete(session: &mut Session, parameters: &J) -> Result<J> {
|
||||
let target = crate::AnnotationTarget::resolve(session, parameters)?;
|
||||
let id = u64p(parameters, "id").ok_or_else(|| bad("graph.comment.delete", "`id` is required"))?;
|
||||
|
||||
session.edit("Delete comment", |session| {
|
||||
session.graph_mut()?.comments.retain(|comment| comment.id != id);
|
||||
let mut items = target.items(session)?;
|
||||
items.comments.retain(|comment| comment.id != id);
|
||||
|
||||
target.replace(session, items)?;
|
||||
Ok(J::Null)
|
||||
})
|
||||
}
|
||||
@@ -172,13 +172,16 @@ fn has_deletable_selection(session: &Session) -> std::result::Result<(), String>
|
||||
|
||||
fn delete_annotation(session: &mut Session) -> Result<J> {
|
||||
let selection = session.annotation_selection;
|
||||
let target = session.annotation_target.clone();
|
||||
let mut items = target.items(session)?;
|
||||
match selection {
|
||||
Some(crate::AnnotationSelection::Frame(id)) => items.frames.retain(|frame| frame.id != id),
|
||||
Some(crate::AnnotationSelection::Comment(id)) => items.comments.retain(|comment| comment.id != id),
|
||||
Some(crate::AnnotationSelection::Pin(id)) => items.pins.retain(|pin| pin.id != id),
|
||||
None => {}
|
||||
}
|
||||
session.edit("Delete annotation", |session| {
|
||||
let graph = session.graph_mut()?;
|
||||
match selection {
|
||||
Some(crate::AnnotationSelection::Frame(id)) => graph.frames.retain(|frame| frame.id != id),
|
||||
Some(crate::AnnotationSelection::Comment(id)) => graph.comments.retain(|comment| comment.id != id),
|
||||
None => {}
|
||||
}
|
||||
target.replace(session, items)?;
|
||||
session.annotation_selection = None;
|
||||
Ok(json!({"deleted": 1}))
|
||||
})
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
use crate::commands::{CommandSpec, bad, boolp, has_graph, point, strp, u64p};
|
||||
use crate::graph_cmds::nodes_rect;
|
||||
use crate::{AnnotationSelection, FrameContents, Result, Session, cmd};
|
||||
use crate::{AnnotationSelection, Result, Session, cmd};
|
||||
use materialcraft_core::Frame;
|
||||
use serde_json::{Value as J, json};
|
||||
|
||||
@@ -32,6 +32,7 @@ fn color_of(parameters: &J) -> Option<[f32; 4]> {
|
||||
}
|
||||
|
||||
fn frame_add(session: &mut Session, parameters: &J) -> Result<J> {
|
||||
let target = crate::AnnotationTarget::resolve(session, parameters)?;
|
||||
let rect = match rect_of(parameters) {
|
||||
Some(rect) => rect,
|
||||
None => nodes_rect(session, &session.selection)
|
||||
@@ -45,9 +46,11 @@ fn frame_add(session: &mut Session, parameters: &J) -> Result<J> {
|
||||
let description = strp(parameters, "description").unwrap_or("").to_string();
|
||||
|
||||
session.edit("Add frame", |session| {
|
||||
let graph = session.graph_mut()?;
|
||||
let id = graph.alloc_id();
|
||||
graph.frames.push(Frame { id, title, title_visible, description, rect, color });
|
||||
let mut items = target.items(session)?;
|
||||
let id = target.next_id(session, &items)?;
|
||||
items.frames.push(Frame { id, title, title_visible, description, rect, color });
|
||||
target.replace(session, items)?;
|
||||
session.annotation_target = target;
|
||||
session.selection.clear();
|
||||
session.annotation_selection = Some(AnnotationSelection::Frame(id));
|
||||
Ok(json!({"id": id}))
|
||||
@@ -55,10 +58,12 @@ fn frame_add(session: &mut Session, parameters: &J) -> Result<J> {
|
||||
}
|
||||
|
||||
fn frame_edit(session: &mut Session, parameters: &J) -> Result<J> {
|
||||
let target = crate::AnnotationTarget::resolve(session, parameters)?;
|
||||
let id = u64p(parameters, "id").ok_or_else(|| bad("graph.frame.edit", "`id` is required"))?;
|
||||
|
||||
session.edit_merged(&format!("frame{id}"), "Edit frame", |session| {
|
||||
let frame = session.graph_mut()?.frames.iter_mut().find(|frame| frame.id == id).ok_or_else(|| bad("graph.frame.edit", format!("no frame {id}")))?;
|
||||
session.edit_merged(&format!("frame:{target:?}:{id}"), "Edit frame", |session| {
|
||||
let mut items = target.items(session)?;
|
||||
let frame = items.frames.iter_mut().find(|frame| frame.id == id).ok_or_else(|| bad("graph.frame.edit", format!("no frame {id}")))?;
|
||||
if let Some(text) = strp(parameters, "title") {
|
||||
frame.title = text.into();
|
||||
}
|
||||
@@ -75,35 +80,39 @@ fn frame_edit(session: &mut Session, parameters: &J) -> Result<J> {
|
||||
frame.color = color;
|
||||
}
|
||||
|
||||
target.replace(session, items)?;
|
||||
Ok(J::Null)
|
||||
})
|
||||
}
|
||||
|
||||
fn frame_delete(session: &mut Session, parameters: &J) -> Result<J> {
|
||||
let target = crate::AnnotationTarget::resolve(session, parameters)?;
|
||||
let id = u64p(parameters, "id").ok_or_else(|| bad("graph.frame.delete", "`id` is required"))?;
|
||||
|
||||
session.edit("Delete frame", |session| {
|
||||
let graph = session.graph_mut()?;
|
||||
let previous_count = graph.frames.len();
|
||||
graph.frames.retain(|frame| frame.id != id);
|
||||
if previous_count == graph.frames.len() {
|
||||
let mut items = target.items(session)?;
|
||||
let previous_count = items.frames.len();
|
||||
items.frames.retain(|frame| frame.id != id);
|
||||
if previous_count == items.frames.len() {
|
||||
return Err(bad("graph.frame.delete", format!("no frame {id}")));
|
||||
}
|
||||
|
||||
target.replace(session, items)?;
|
||||
Ok(J::Null)
|
||||
})
|
||||
}
|
||||
|
||||
fn frame_move(session: &mut Session, parameters: &J) -> Result<J> {
|
||||
let target = crate::AnnotationTarget::resolve(session, parameters)?;
|
||||
let id = u64p(parameters, "id").ok_or_else(|| bad("graph.frame.move", "`id` is required"))?;
|
||||
let offset = point(parameters, "by").ok_or_else(|| bad("graph.frame.move", "`by` is required"))?;
|
||||
let offset = crate::graph_grid::snap_position(offset, boolp(parameters, "snapToGrid").unwrap_or(false));
|
||||
let graph = session.graph()?;
|
||||
let frame = graph.frames.iter().find(|frame| frame.id == id).ok_or_else(|| bad("graph.frame.move", "frame does not exist"))?;
|
||||
let contents = FrameContents::capture(graph, frame);
|
||||
let items = target.items(session)?;
|
||||
let frame = items.frames.iter().find(|frame| frame.id == id).ok_or_else(|| bad("graph.frame.move", "frame does not exist"))?;
|
||||
let contents = target.capture_frame(session, frame)?;
|
||||
|
||||
session.edit("Move frame and contents", |session| {
|
||||
contents.translate(session.graph_mut()?, offset);
|
||||
target.move_contents(session, &contents, offset)?;
|
||||
|
||||
Ok(J::Null)
|
||||
})
|
||||
|
||||
@@ -27,10 +27,9 @@ impl FunctionGraphTarget {
|
||||
crate::function_variables::suggestions(self, session, id)
|
||||
}
|
||||
|
||||
pub fn available_operations(&self, session: &Session) -> impl Iterator<Item = &'static materialcraft_nodes::function::FunctionDefinition> + use<> {
|
||||
let value_processor = matches!(self, Self::Parameter { node, parameter }
|
||||
if parameter == "function" && session.graph().ok().and_then(|graph| graph.node(*node).ok()).is_some_and(|node| node.def == "value_processor"));
|
||||
materialcraft_nodes::function::FUNCTIONS.iter().filter(move |operation| !value_processor || !matches!(operation.id, "samplelum" | "samplecol"))
|
||||
/// All function targets accept the native catalog, including samplers for processor image inputs.
|
||||
pub fn available_operations(&self, _session: &Session) -> impl Iterator<Item = &'static materialcraft_nodes::function::FunctionDefinition> + use<> {
|
||||
materialcraft_nodes::function::FUNCTIONS.iter()
|
||||
}
|
||||
|
||||
pub fn current<'a>(&self, session: &'a Session) -> Result<&'a FunctionGraph> {
|
||||
|
||||
@@ -1,21 +1,2 @@
|
||||
use materialcraft_core::Package;
|
||||
use std::{collections::BTreeMap, sync::Arc};
|
||||
|
||||
/// The bundled function library every session loads (see `node_library`)
|
||||
pub(crate) const STANDARD_PACKAGE: &str = "sbs://functions.sbs";
|
||||
|
||||
pub(crate) struct FunctionLibrary {
|
||||
pub packages: BTreeMap<String, Arc<Package>>,
|
||||
pub warnings: Vec<String>,
|
||||
}
|
||||
|
||||
pub(crate) fn load() -> Result<FunctionLibrary, String> {
|
||||
let bytes = materialcraft_formats::sbs::library::read(STANDARD_PACKAGE)?;
|
||||
let mut read =
|
||||
materialcraft_formats::sbs::read_sbs(&bytes, STANDARD_PACKAGE, &crate::file_cmds::linked_files(STANDARD_PACKAGE)).map_err(|error| error.to_string())?;
|
||||
crate::linked_files::normalize_references(&mut read.pkg, STANDARD_PACKAGE);
|
||||
read.warnings.extend(crate::linked_files::load(&mut read.pkg));
|
||||
|
||||
let mut packages = std::mem::take(&mut read.pkg.dependencies);
|
||||
packages.insert(STANDARD_PACKAGE.into(), Arc::new(read.pkg));
|
||||
Ok(FunctionLibrary { packages, warnings: read.warnings })
|
||||
}
|
||||
@@ -2,9 +2,9 @@
|
||||
|
||||
use serde_json::{Value as J, json};
|
||||
|
||||
use materialcraft_core::{ExposedParameter, Graph, MAX_SIZE_LOG2, MIN_SIZE_LOG2, NodeId, OutputFormat, Pin, Value};
|
||||
use materialcraft_core::{ExposedParameter, Graph, MAX_SIZE_LOG2, MIN_SIZE_LOG2, NodeId, OutputFormat, Value};
|
||||
|
||||
use crate::commands::{CommandSpec, always, bad, boolp, f32p, has_graph, has_selection, i64p, ids_param, point, strp, u64p};
|
||||
use crate::commands::{CommandSpec, always, bad, boolp, f32p, has_graph, has_selection, i64p, ids_param, strp, u64p};
|
||||
use crate::{Result, Session, cmd};
|
||||
|
||||
pub(crate) fn specs() -> Vec<CommandSpec> {
|
||||
@@ -22,9 +22,15 @@ pub(crate) fn specs() -> Vec<CommandSpec> {
|
||||
})
|
||||
}),
|
||||
cmd!("graph.format", "Output format", [], None, "{format: u8|u16|f16|f32, graph?, document?}", always, format),
|
||||
cmd!("graph.cook", "Compute graph", [], None, "{full?: bool} cooks now; returns per-node timings and errors", has_graph, cook),
|
||||
cmd!("graph.pin.add", "Add Navigation pin", [], None, "{name?, at? [x, y]}", has_graph, pin_add),
|
||||
cmd!("graph.pin.delete", "Delete pin", [], None, "{id}", has_graph, pin_delete),
|
||||
cmd!(
|
||||
"graph.cook",
|
||||
"Compute graph",
|
||||
[],
|
||||
None,
|
||||
"{full?: bool, graph?: index (another graph of the package cooks at full size into the cache)} cooks now; returns per-node timings and errors",
|
||||
has_graph,
|
||||
cook
|
||||
),
|
||||
cmd!(
|
||||
"graph.exposed.add",
|
||||
"Expose parameter",
|
||||
@@ -153,8 +159,19 @@ fn format(s: &mut Session, p: &J) -> Result<J> {
|
||||
}
|
||||
|
||||
fn cook(s: &mut Session, p: &J) -> Result<J> {
|
||||
let cooked = if boolp(p, "full") == Some(true) { s.cook_full(s.graph) } else { s.cook().clone() };
|
||||
let g = s.graph()?;
|
||||
let index = match p.get("graph").filter(|graph| !graph.is_null()) {
|
||||
None => s.graph,
|
||||
Some(graph) => {
|
||||
let index = graph.as_u64().and_then(|index| usize::try_from(index).ok()).ok_or_else(|| bad("graph.cook", "`graph` is a graph index"))?;
|
||||
let graph = s.pkg.graph(index)?;
|
||||
if graph.function.is_some() {
|
||||
return Err(bad("graph.cook", "a Function Graph has no outputs to compute"));
|
||||
}
|
||||
index
|
||||
}
|
||||
};
|
||||
let cooked = if index != s.graph || boolp(p, "full") == Some(true) { s.cook_full(index) } else { s.cook().clone() };
|
||||
let g = s.pkg.graph(index)?;
|
||||
Ok(json!({
|
||||
"ms": cooked.ms,
|
||||
"nodes": cooked.nodes.iter().map(|(id, r)| {
|
||||
@@ -175,25 +192,6 @@ pub fn nodes_rect(s: &Session, ids: &[NodeId]) -> Option<[f32; 4]> {
|
||||
(r[0] < f32::MAX).then(|| [r[0], r[1], r[2] - r[0], r[3] - r[1]])
|
||||
}
|
||||
|
||||
fn pin_add(s: &mut Session, p: &J) -> Result<J> {
|
||||
let at = point(p, "at").unwrap_or([0.0, 0.0]);
|
||||
s.edit("Add pin", |s| {
|
||||
let g = s.graph_mut()?;
|
||||
let id = g.alloc_id();
|
||||
let name = strp(p, "name").map(str::to_string).unwrap_or_else(|| format!("Pin {}", g.pins.len() + 1));
|
||||
g.pins.push(Pin { id, name, pos: at });
|
||||
Ok(json!({"id": id}))
|
||||
})
|
||||
}
|
||||
|
||||
fn pin_delete(s: &mut Session, p: &J) -> Result<J> {
|
||||
let id = u64p(p, "id").ok_or_else(|| bad("graph.pin.delete", "`id` is required"))?;
|
||||
s.edit("Delete pin", |s| {
|
||||
s.graph_mut()?.pins.retain(|c| c.id != id);
|
||||
Ok(J::Null)
|
||||
})
|
||||
}
|
||||
|
||||
fn exposed_add(s: &mut Session, p: &J) -> Result<J> {
|
||||
// From a bound node parameter: its value, range and options become the input's
|
||||
let bind = p.get("bind").and_then(|b| Some((NodeId(b.get("node")?.as_u64()?), b.get("param")?.as_str()?.to_string())));
|
||||
|
||||
@@ -70,6 +70,7 @@ pub fn session(s: &Session, graph: Option<usize>) -> J {
|
||||
"openGraph": g.map(|_| s.graph),
|
||||
"graph": graph_json,
|
||||
"annotationSelection": s.annotation_selection,
|
||||
"annotationTarget": s.annotation_target,
|
||||
"selection": s.selection.iter().map(|i| i.0).collect::<Vec<_>>(),
|
||||
"view2d": s.view2d,
|
||||
"view3d": s.view3d,
|
||||
|
||||
@@ -1,6 +1,9 @@
|
||||
#![forbid(unsafe_code)]
|
||||
#![deny(clippy::unwrap_used, clippy::expect_used, clippy::panic, clippy::unimplemented, clippy::todo, clippy::unreachable)]
|
||||
|
||||
#[cfg(test)]
|
||||
extern crate self as materialcraft_engine;
|
||||
|
||||
mod document_path;
|
||||
mod evaluation_environment_commands;
|
||||
mod explorer_clipboard;
|
||||
@@ -11,6 +14,9 @@ mod folder_property_commands;
|
||||
pub use explorer_clipboard::ExplorerClipboard;
|
||||
mod function_library;
|
||||
mod function_library_commands;
|
||||
pub mod node_library;
|
||||
mod node_library_commands;
|
||||
pub use node_library::{LibraryCanvas, LibraryEntry, LibraryItem, NodeLibrary};
|
||||
mod function_variable;
|
||||
mod function_variable_commands;
|
||||
mod function_variables;
|
||||
@@ -99,12 +105,15 @@ pub use exported::Exported;
|
||||
|
||||
mod annotation_commands;
|
||||
mod annotation_selection;
|
||||
mod annotation_target;
|
||||
pub use annotation_target::AnnotationTarget;
|
||||
mod comment_commands;
|
||||
mod frame_commands;
|
||||
mod frame_contents;
|
||||
mod function_commands;
|
||||
mod node_graph_commands;
|
||||
mod pattern_graph_commands;
|
||||
mod pin_commands;
|
||||
mod snapshot;
|
||||
pub use annotation_selection::AnnotationSelection;
|
||||
pub use frame_contents::FrameContents;
|
||||
|
||||
@@ -97,8 +97,15 @@ impl Session {
|
||||
self.refresh_links_from(BTreeSet::new());
|
||||
}
|
||||
|
||||
/// Refresh linked interfaces and retain ownership of installed library snapshots.
|
||||
pub(crate) fn refresh_links_from(&mut self, mut changed: BTreeSet<String>) {
|
||||
// Replaced snapshots belong to the caller, even when their library alias is unchanged
|
||||
self.library_sources.retain(|path, owned| self.linked_sources.get(path).is_some_and(|source| Arc::ptr_eq(source, owned)));
|
||||
let open_paths: BTreeSet<_> = self.open_packages().into_iter().filter_map(|(_, _, path, _)| path.map(str::to_string)).collect();
|
||||
self.library_sources.retain(|path, _| !open_paths.contains(path));
|
||||
|
||||
let mut sources = self.linked_sources.clone();
|
||||
|
||||
// Interface types can propagate through several files; the workspace has at most 64 open packages
|
||||
for _ in 0..64 {
|
||||
for (_, package, path, _) in self.open_packages() {
|
||||
@@ -142,6 +149,13 @@ impl Session {
|
||||
}
|
||||
document.pkg.dependencies = sources.clone();
|
||||
}
|
||||
|
||||
// Interface refreshes replace Arcs without changing who owns the source
|
||||
for (path, owned) in &mut self.library_sources {
|
||||
if let Some(source) = sources.get(path) {
|
||||
*owned = source.clone();
|
||||
}
|
||||
}
|
||||
self.linked_sources = sources;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,458 @@
|
||||
//! The node library. Every SBS package in the library folder (`assets/sbs`, or the bundled copies)
|
||||
//! is loaded once per process and lends its graphs: function graphs go under Functions (sorted by
|
||||
//! their classification tags, with folder fallbacks), other graphs under their attribute category. Native nodes, function operations,
|
||||
//! FX-Map nodes and graph items fill the rest of the tree. A package whose titled frames are library
|
||||
//! categories ("Filters - Blurs") can also lay the library out: each node inside a frame becomes an
|
||||
//! entry in that category, listed as missing until a package provides it.
|
||||
|
||||
mod library_canvas;
|
||||
mod library_entry;
|
||||
mod library_item;
|
||||
mod library_placement;
|
||||
pub use library_canvas::LibraryCanvas;
|
||||
pub use library_entry::LibraryEntry;
|
||||
pub use library_item::LibraryItem;
|
||||
use library_placement::LibraryPlacement;
|
||||
|
||||
use materialcraft_core::{Package, PatternNodeKind};
|
||||
use materialcraft_formats::sbs::{LayoutItem, library};
|
||||
use std::collections::{BTreeMap, BTreeSet};
|
||||
use std::sync::{Arc, Mutex};
|
||||
|
||||
/// The library tree in display order: top-level categories and their sub-categories. The UI adds
|
||||
/// Favorites above it
|
||||
pub const CATEGORIES: &[(&str, &[&str])] = &[
|
||||
("Graph items", &[]),
|
||||
("Atomic nodes", &[]),
|
||||
("FxMap nodes", &[]),
|
||||
("Function nodes", &["Constant", "Vector", "Variables", "Samplers", "Cast", "Operator", "Logical", "Comparison", "Function", "Control"]),
|
||||
("Texture generators", &["Noises", "Patterns"]),
|
||||
("Filters", &["Adjustments", "Blending", "Blurs", "Channels", "Effects", "Normal map", "Tiling", "Transforms"]),
|
||||
("Material filters", &["1-click", "Effects", "Transforms", "Blending", "PBR utilities", "Scan processing"]),
|
||||
("Mesh-based generators", &["Mask generators", "Weathering", "Utilities"]),
|
||||
("Spline & Path tools", &["Spline tools", "Path tools"]),
|
||||
("MCF functions", &["Primitives", "Operators", "Transforms"]),
|
||||
("Functions", &["Color", "Comparison", "Constant", "Conversion", "Maths", "Parity", "Random", "Transformation", "Various", "Easings"]),
|
||||
("3D view", &["HDRI environments", "HDRI tools"]),
|
||||
("PBR materials", &["Bricks", "Concrete", "Fabric", "Ground", "Metal", "Paper", "Pavement", "Tiles", "Wood", "Stone"]),
|
||||
("Values", &["Constant"]),
|
||||
];
|
||||
|
||||
/// Older layouts name categories MaterialCraft has renamed: (old, current)
|
||||
const RENAMED: &[(&str, &str)] = &[("SDF functions", "MCF functions")];
|
||||
|
||||
/// Words that place a material in a sub-category when its layout frame names only the top level
|
||||
const SUB_KEYWORDS: &[(&str, &str, &[&str])] = &[
|
||||
("PBR materials", "Bricks", &["brick"]),
|
||||
("PBR materials", "Concrete", &["concrete", "cement"]),
|
||||
("PBR materials", "Fabric", &["fabric", "cloth", "textile", "leather"]),
|
||||
("PBR materials", "Ground", &["ground", "gravel", "soil", "sand", "dirt", "grass", "mud"]),
|
||||
("PBR materials", "Metal", &["metal", "steel", "iron", "copper", "rust"]),
|
||||
("PBR materials", "Paper", &["paper", "cardboard"]),
|
||||
("PBR materials", "Pavement", &["pavement", "paving", "cobble", "asphalt"]),
|
||||
("PBR materials", "Tiles", &["tile"]),
|
||||
("PBR materials", "Wood", &["wood", "plank", "bark"]),
|
||||
("PBR materials", "Stone", &["stone", "rock", "marble", "granite"]),
|
||||
];
|
||||
|
||||
/// Everything loaded from the library folder
|
||||
#[derive(Debug, Default)]
|
||||
pub struct NodeLibrary {
|
||||
/// Library packages (layouts excluded) and their own dependencies, by `sbs://` path
|
||||
pub packages: BTreeMap<String, Arc<Package>>,
|
||||
/// The `sbs://` files that laid the library out
|
||||
pub layouts: Vec<String>,
|
||||
pub warnings: Vec<String>,
|
||||
placements: Vec<LibraryPlacement>,
|
||||
}
|
||||
|
||||
static SHARED: Mutex<Option<Arc<NodeLibrary>>> = Mutex::new(None);
|
||||
|
||||
impl NodeLibrary {
|
||||
/// The process's library, loaded on first use
|
||||
pub fn shared() -> Arc<NodeLibrary> {
|
||||
let mut shared = SHARED.lock().unwrap_or_else(std::sync::PoisonError::into_inner);
|
||||
shared.get_or_insert_with(|| Arc::new(Self::load(&library::files()))).clone()
|
||||
}
|
||||
|
||||
/// Read the library folder again (after packages were added or changed on disk)
|
||||
pub fn reload() -> Arc<NodeLibrary> {
|
||||
let library = Arc::new(Self::load(&library::files()));
|
||||
*SHARED.lock().unwrap_or_else(std::sync::PoisonError::into_inner) = Some(library.clone());
|
||||
library
|
||||
}
|
||||
|
||||
/// Load `files` (`sbs://` paths)
|
||||
pub fn load(files: &[String]) -> NodeLibrary {
|
||||
let mut out = NodeLibrary::default();
|
||||
for uri in files {
|
||||
let bytes = match library::read(uri) {
|
||||
Ok(bytes) => bytes,
|
||||
Err(error) => {
|
||||
out.warnings.push(format!("Library package {uri}: {error}"));
|
||||
continue;
|
||||
}
|
||||
};
|
||||
|
||||
// A layout's frames name library categories; anything else is a package of graphs
|
||||
let placements = match materialcraft_formats::sbs::read_layout(&bytes, uri) {
|
||||
Ok(frames) => placements(&frames),
|
||||
Err(error) => {
|
||||
out.warnings.push(format!("Library package {uri}: {error}"));
|
||||
continue;
|
||||
}
|
||||
};
|
||||
if !placements.is_empty() {
|
||||
out.placements.extend(placements);
|
||||
out.layouts.push(uri.clone());
|
||||
continue;
|
||||
}
|
||||
|
||||
match materialcraft_formats::sbs::read_sbs(&bytes, uri, &crate::file_cmds::linked_files(uri)) {
|
||||
Ok(mut read) => {
|
||||
crate::linked_files::normalize_references(&mut read.pkg, uri);
|
||||
read.warnings.extend(crate::linked_files::load(&mut read.pkg));
|
||||
out.warnings.extend(read.warnings);
|
||||
for (path, package) in std::mem::take(&mut read.pkg.dependencies) {
|
||||
out.packages.entry(path).or_insert(package);
|
||||
}
|
||||
out.packages.insert(uri.clone(), Arc::new(read.pkg));
|
||||
}
|
||||
Err(error) => out.warnings.push(format!("Library package {uri}: {error}")),
|
||||
}
|
||||
}
|
||||
out
|
||||
}
|
||||
|
||||
/// Every entry, resolved against `dependencies` (a session's loaded packages): layout
|
||||
/// placements first, then graph items and native nodes no layout placed, then graphs of
|
||||
/// `sbs://` packages no layout placed
|
||||
pub fn entries(&self, dependencies: &BTreeMap<String, Arc<Package>>) -> Vec<LibraryEntry> {
|
||||
let mut out = Vec::new();
|
||||
let mut ids = BTreeSet::new();
|
||||
let mut placed_graphs = BTreeSet::new();
|
||||
let mut push = |out: &mut Vec<LibraryEntry>, mut entry: LibraryEntry| {
|
||||
// Reroute nodes are placed through the shared Graph items entry
|
||||
if matches!(&entry.item, LibraryItem::Operation { operation } if operation == "passthrough")
|
||||
|| matches!(&entry.item, LibraryItem::Pattern { kind: PatternNodeKind::Dot })
|
||||
|| matches!(&entry.item, LibraryItem::Node { def } if def == "dot" && entry.category != "Graph items")
|
||||
{
|
||||
return;
|
||||
}
|
||||
// The same node may sit in two categories; the id keeps each placement apart
|
||||
if !ids.insert(entry.id.clone()) {
|
||||
entry.id = format!("{}@{}", entry.id, entry.category);
|
||||
if !ids.insert(entry.id.clone()) {
|
||||
return;
|
||||
}
|
||||
}
|
||||
out.push(entry);
|
||||
};
|
||||
|
||||
for (item, category) in [(LibraryItem::Comment, "Comment"), (LibraryItem::Frame, "Frame"), (LibraryItem::Pin, "Pin")] {
|
||||
let id = format!("item:{}", category.to_ascii_lowercase());
|
||||
push(&mut out, entry(id, category, "Graph items", "", item, None));
|
||||
}
|
||||
push(&mut out, entry("node:dot".into(), "Dot node", "Graph items", "A reroute point for wires.", LibraryItem::Node { def: "dot".into() }, None));
|
||||
|
||||
for placement in &self.placements {
|
||||
if let LayoutItem::Instance { package, graph, .. } | LayoutItem::FunctionInstance { package, graph } = &placement.item {
|
||||
placed_graphs.insert((package.clone(), graph.clone()));
|
||||
}
|
||||
if let Some(entry) = resolve(placement, dependencies) {
|
||||
push(&mut out, entry);
|
||||
}
|
||||
}
|
||||
|
||||
let listed: BTreeSet<String> = out.iter().map(|entry| entry.id.clone()).collect();
|
||||
for definition in materialcraft_nodes::catalog() {
|
||||
let id = format!("node:{}", definition.id);
|
||||
if definition.id == "graph_instance" || listed.contains(&id) {
|
||||
continue;
|
||||
}
|
||||
|
||||
let item = LibraryItem::Node { def: definition.id.into() };
|
||||
|
||||
// Graph inputs and outputs sit with the atomic nodes; Graph items holds annotations and the Dot
|
||||
let category =
|
||||
if matches!(definition.id, "input_color" | "input_grayscale" | "input_value" | "output") { "Atomic nodes" } else { definition.category };
|
||||
push(&mut out, entry(id, definition.label, category, definition.description, item, None));
|
||||
}
|
||||
for operation in materialcraft_nodes::function::FUNCTIONS {
|
||||
let id = format!("function:{}", operation.id);
|
||||
if operation.id == "passthrough" || listed.contains(&id) {
|
||||
continue;
|
||||
}
|
||||
|
||||
let category = category_path("Function nodes", Some(operation.category));
|
||||
push(&mut out, entry(id, operation.label, &category, "", LibraryItem::Operation { operation: operation.id.into() }, None));
|
||||
}
|
||||
for kind in PatternNodeKind::ALL.into_iter().filter(|kind| *kind != PatternNodeKind::Dot) {
|
||||
let id = format!("pattern:{}", kind.native_id());
|
||||
push(&mut out, entry(id, kind.label(), "FxMap nodes", "", LibraryItem::Pattern { kind }, None));
|
||||
}
|
||||
|
||||
for (path, package) in dependencies.iter().filter(|(path, _)| path.starts_with("sbs://")) {
|
||||
for graph in &package.graphs {
|
||||
let name = graph.sbs_path();
|
||||
if placed_graphs.contains(&(path.clone(), name.clone())) {
|
||||
continue;
|
||||
}
|
||||
|
||||
if graph.function.is_some() {
|
||||
for category in function_categories(graph) {
|
||||
let placement = LibraryPlacement { category, item: LayoutItem::FunctionInstance { package: path.clone(), graph: name.clone() } };
|
||||
if let Some(entry) = resolve(&placement, dependencies) {
|
||||
push(&mut out, entry);
|
||||
}
|
||||
}
|
||||
continue;
|
||||
}
|
||||
|
||||
let placement = if graph.nodes.iter().any(|node| node.def == "output") {
|
||||
let category = known_category(&graph.attributes.category).unwrap_or_else(|| "Other".into());
|
||||
LibraryPlacement { category, item: LayoutItem::Instance { package: path.clone(), graph: name, outputs: Vec::new() } }
|
||||
} else {
|
||||
continue;
|
||||
};
|
||||
|
||||
if let Some(entry) = resolve(&placement, dependencies) {
|
||||
push(&mut out, entry);
|
||||
}
|
||||
}
|
||||
}
|
||||
out
|
||||
}
|
||||
}
|
||||
|
||||
/// Build an entry with a canvas derived from its item kind.
|
||||
fn entry(id: String, label: &str, category: &str, description: &str, item: LibraryItem, missing: Option<String>) -> LibraryEntry {
|
||||
let canvas = item.canvas();
|
||||
LibraryEntry { id, label: label.into(), category: category.into(), description: description.into(), item, canvas, missing, warning: None }
|
||||
}
|
||||
|
||||
/// A layout item as an entry, its label and availability taken from the loaded packages
|
||||
fn resolve(placement: &LibraryPlacement, dependencies: &BTreeMap<String, Arc<Package>>) -> Option<LibraryEntry> {
|
||||
let category = placement.category.as_str();
|
||||
Some(match &placement.item {
|
||||
LayoutItem::Atomic { node: Some(def), .. } | LayoutItem::Node(def) => {
|
||||
let definition = materialcraft_nodes::find(def)?;
|
||||
entry(format!("node:{def}"), definition.label, category, definition.description, LibraryItem::Node { def: def.to_string() }, None)
|
||||
}
|
||||
LayoutItem::Atomic { filter, node: None } => {
|
||||
let item = LibraryItem::Node { def: filter.clone() };
|
||||
entry(format!("atomic:{filter}"), &humanize(filter), category, "", item, Some(format!("The atomic `{filter}` node is not in MaterialCraft yet")))
|
||||
}
|
||||
LayoutItem::Operation(operation) => {
|
||||
let definition = materialcraft_nodes::function::FUNCTIONS.iter().find(|definition| definition.id == operation);
|
||||
let label = definition.map_or_else(|| humanize(operation), |definition| definition.label.to_string());
|
||||
let missing = definition.is_none().then(|| format!("The `{operation}` function node is not in MaterialCraft yet"));
|
||||
entry(format!("function:{operation}"), &label, category, "", LibraryItem::Operation { operation: operation.clone() }, missing)
|
||||
}
|
||||
LayoutItem::Instance { package, graph, .. } | LayoutItem::FunctionInstance { package, graph } => {
|
||||
let function = matches!(placement.item, LayoutItem::FunctionInstance { .. });
|
||||
let source = dependencies.get(package).and_then(|source| source.graph_by_name(graph)).map(|(_, graph)| graph);
|
||||
let source = source.filter(|source| source.function.is_some() == function);
|
||||
let label = source.map_or_else(|| humanize(graph), |source| source.display_name().to_string());
|
||||
let description = source.map(|source| source.attributes.description.clone()).unwrap_or_default();
|
||||
let missing = source.is_none().then(|| format!("Not in MaterialCraft yet: needs {graph} from {package}"));
|
||||
let item = if function {
|
||||
LibraryItem::FunctionInstance { package: package.clone(), graph: graph.clone() }
|
||||
} else {
|
||||
LibraryItem::Instance { package: package.clone(), graph: graph.clone() }
|
||||
};
|
||||
let mut out = entry(format!("{package}#{graph}"), &label, category, &description, item, missing);
|
||||
out.category = sub_category(category, graph);
|
||||
out.warning = source
|
||||
.and_then(|source| source.function.as_ref())
|
||||
.filter(|function| function.output.is_none() || function.nodes.iter().any(|node| node.missing.is_some()))
|
||||
.map(|_| "This function uses nodes MaterialCraft does not have yet".to_string());
|
||||
out
|
||||
}
|
||||
|
||||
// A bitmap anywhere but the 3D view stands for the atomic Bitmap node, not its image
|
||||
LayoutItem::Bitmap { .. } if !category.starts_with("3D view") => {
|
||||
let definition = materialcraft_nodes::find("bitmap")?;
|
||||
entry("node:bitmap".into(), definition.label, category, definition.description, LibraryItem::Node { def: "bitmap".into() }, None)
|
||||
}
|
||||
LayoutItem::Bitmap { resource } => {
|
||||
let name = resource.rsplit('/').next().unwrap_or(resource);
|
||||
let missing = Some(format!("Not in MaterialCraft yet: the {} image is not bundled", humanize(name)));
|
||||
entry(format!("bitmap:{resource}"), &humanize(name), category, "", LibraryItem::Bitmap { resource: resource.clone() }, missing)
|
||||
}
|
||||
})
|
||||
}
|
||||
|
||||
/// The categories of a layout's frames, and what each places
|
||||
fn placements(frames: &[materialcraft_formats::sbs::LayoutFrame]) -> Vec<LibraryPlacement> {
|
||||
let mut out = Vec::new();
|
||||
for frame in frames {
|
||||
let native = frame.items.iter().any(|item| matches!(item, LayoutItem::Operation(_)));
|
||||
let Some(category) = frame_category(&frame.title, frame.function, native) else { continue };
|
||||
out.extend(frame.items.iter().map(|item| LibraryPlacement { category: category.clone(), item: item.clone() }));
|
||||
}
|
||||
out
|
||||
}
|
||||
|
||||
/// Letters and digits, lower case: "Spline & Path Tools", "spline & path tools" and
|
||||
/// "Spline-and-path tools" differ, but "1 click" and "1-click" match
|
||||
fn key(text: &str) -> String {
|
||||
text.chars().filter(char::is_ascii_alphanumeric).map(|c| c.to_ascii_lowercase()).collect()
|
||||
}
|
||||
|
||||
/// `Top/Sub` for a frame title. Graph frames read "Top - Sub" (or "Top"); function frames name
|
||||
/// only the sub-category, under Function nodes when they hold native operations and Functions
|
||||
/// otherwise
|
||||
pub fn frame_category(title: &str, function: bool, native_operations: bool) -> Option<String> {
|
||||
if function {
|
||||
let top = if native_operations { "Function nodes" } else { "Functions" };
|
||||
let (_, subs) = CATEGORIES.iter().find(|(name, _)| *name == top)?;
|
||||
let sub = subs.iter().find(|sub| key(sub) == key(title))?;
|
||||
return Some(category_path(top, Some(sub)));
|
||||
}
|
||||
|
||||
let (top, sub) = title.split_once(" - ").map_or((title, None), |(top, sub)| (top, Some(sub)));
|
||||
let top = RENAMED.iter().find(|(old, _)| key(old) == key(top)).map_or(top, |(_, current)| current);
|
||||
let (top, subs) = CATEGORIES.iter().find(|(name, _)| key(name) == key(top))?;
|
||||
match sub {
|
||||
None => Some((*top).to_string()),
|
||||
Some(sub) => subs.iter().find(|name| key(name) == key(sub)).map(|sub| category_path(top, Some(sub))),
|
||||
}
|
||||
}
|
||||
|
||||
/// A category text from a graph's attributes, when it names a library category
|
||||
fn known_category(text: &str) -> Option<String> {
|
||||
let mut parts = text.split('/');
|
||||
let top = parts.next()?;
|
||||
let (top, subs) = CATEGORIES.iter().find(|(name, _)| key(name) == key(top))?;
|
||||
|
||||
// A sub-category the tree doesn't have names no category ("Functions/colorValues" is a folder)
|
||||
let sub = match parts.next() {
|
||||
None => None,
|
||||
Some(sub) => Some(*subs.iter().find(|name| key(name) == key(sub))?),
|
||||
};
|
||||
Some(category_path(top, sub))
|
||||
}
|
||||
|
||||
/// Function tags select filters; explicit category paths and package paths remain fallbacks.
|
||||
fn function_categories(graph: &materialcraft_core::Graph) -> Vec<String> {
|
||||
let subcategories = CATEGORIES.iter().find(|(name, _)| *name == "Functions").map_or(&[][..], |(_, subcategories)| *subcategories);
|
||||
let mut categories = Vec::new();
|
||||
for tag in graph.attributes.tags.split([',', ';']) {
|
||||
let tag = key(tag);
|
||||
let tag = if tag == "easing" { "easings" } else { tag.as_str() };
|
||||
if let Some(subcategory) = subcategories.iter().find(|subcategory| key(subcategory) == tag) {
|
||||
let category = category_path("Functions", Some(subcategory));
|
||||
if !categories.contains(&category) {
|
||||
categories.push(category);
|
||||
}
|
||||
}
|
||||
}
|
||||
if categories.is_empty() {
|
||||
categories.push(known_category(&graph.attributes.category).unwrap_or_else(|| function_category(&graph.sbs_path())));
|
||||
}
|
||||
categories
|
||||
}
|
||||
|
||||
/// Join a top-level category with its optional subcategory.
|
||||
fn category_path(top: &str, sub: Option<&str>) -> String {
|
||||
match sub {
|
||||
Some(sub) => format!("{top}/{sub}"),
|
||||
None => top.to_string(),
|
||||
}
|
||||
}
|
||||
|
||||
/// The sub-category a graph's name suggests, for layouts that name only a top level
|
||||
fn sub_category(category: &str, graph: &str) -> String {
|
||||
if category.contains('/') {
|
||||
return category.to_string();
|
||||
}
|
||||
|
||||
let name = graph.rsplit('/').next().unwrap_or(graph).to_ascii_lowercase();
|
||||
SUB_KEYWORDS
|
||||
.iter()
|
||||
.find(|(top, _, words)| *top == category && words.iter().any(|word| name.contains(word)))
|
||||
.map_or_else(|| category.to_string(), |(top, sub, _)| category_path(top, Some(sub)))
|
||||
}
|
||||
|
||||
/// Function graphs whose name decides their Functions sub-category
|
||||
const FUNCTION_NAMES: &[(&str, &str)] = &[
|
||||
("Pi", "Constant"),
|
||||
("2Pi", "Constant"),
|
||||
("deg_to_rad", "Conversion"),
|
||||
("Degrees_to_Turn", "Conversion"),
|
||||
("Curve_Function", "Various"),
|
||||
("Roughness", "Various"),
|
||||
];
|
||||
/// Name prefixes that decide a function graph's sub-category
|
||||
const FUNCTION_PREFIXES: &[(&str, &str)] = &[("Equality_", "Comparison"), ("NotEqual_", "Comparison")];
|
||||
/// Library folders (below `Functions/`) and the Functions sub-category of the graphs in them; the
|
||||
/// first folder that holds the graph wins
|
||||
const FUNCTION_FOLDERS: &[(&str, &str)] = &[
|
||||
("colorValues", "Color"),
|
||||
("Tonemappers", "Color"),
|
||||
("easings", "Easings"),
|
||||
("Math/Parity", "Parity"),
|
||||
("Random", "Random"),
|
||||
("Ranges", "Conversion"),
|
||||
("typeConverters", "Conversion"),
|
||||
("Transforms", "Transformation"),
|
||||
("switch", "Various"),
|
||||
("Various", "Various"),
|
||||
("Cycles", "Various"),
|
||||
("Math", "Maths"),
|
||||
];
|
||||
|
||||
/// The Functions sub-category of a function graph, from its path in the library package
|
||||
/// (`Functions/Math/Pi` → `Functions/Constant`); `Functions` when nothing matches
|
||||
pub fn function_category(path: &str) -> String {
|
||||
let (folder, name) = path.rsplit_once('/').unwrap_or(("", path));
|
||||
let folder = folder.strip_prefix("Functions").map_or(folder, |rest| rest.trim_start_matches('/'));
|
||||
let sub = FUNCTION_NAMES
|
||||
.iter()
|
||||
.find(|(known, _)| *known == name)
|
||||
.or_else(|| FUNCTION_PREFIXES.iter().find(|(prefix, _)| name.starts_with(prefix)))
|
||||
.or_else(|| FUNCTION_FOLDERS.iter().find(|(known, _)| folder == *known || folder.strip_prefix(known).is_some_and(|rest| rest.starts_with('/'))))
|
||||
.map(|(_, sub)| *sub);
|
||||
category_path("Functions", sub)
|
||||
}
|
||||
|
||||
/// A readable label from an SBS identifier: `3D_perlin_noise` → "3D Perlin Noise"
|
||||
pub fn humanize(identifier: &str) -> String {
|
||||
const WORDS: &[(&str, &str)] = &[
|
||||
("2d", "2D"),
|
||||
("3d", "3D"),
|
||||
("acescg", "ACEScg"),
|
||||
("ao", "AO"),
|
||||
("bnw", "BnW"),
|
||||
("hdr", "HDR"),
|
||||
("hdri", "HDRI"),
|
||||
("hq", "HQ"),
|
||||
("id", "ID"),
|
||||
("mg", "MG"),
|
||||
("pbr", "PBR"),
|
||||
("rgb", "RGB"),
|
||||
("rgba", "RGBA"),
|
||||
("rgb-a", "RGB-A"),
|
||||
("srgb", "sRGB"),
|
||||
("uv", "UV"),
|
||||
];
|
||||
let name = identifier.rsplit('/').next().unwrap_or(identifier);
|
||||
name.split(['_', ' '])
|
||||
.filter(|word| !word.is_empty())
|
||||
.map(|word| {
|
||||
let lower = word.to_ascii_lowercase();
|
||||
if let Some((_, known)) = WORDS.iter().find(|(from, _)| *from == lower) {
|
||||
return (*known).to_string();
|
||||
}
|
||||
|
||||
let mut chars = word.chars();
|
||||
chars.next().map_or_else(String::new, |first| first.to_uppercase().chain(chars).collect())
|
||||
})
|
||||
.collect::<Vec<_>>()
|
||||
.join(" ")
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
#[path = "node_library.test.rs"]
|
||||
mod tests;
|
||||
@@ -0,0 +1,173 @@
|
||||
use super::*;
|
||||
use materialcraft_core::Graph;
|
||||
|
||||
#[path = "../tests/support/node_library.rs"]
|
||||
mod fixture;
|
||||
|
||||
/// Category aliases and frame kinds resolve only to recognized categories.
|
||||
#[test]
|
||||
fn frame_titles_map_to_library_categories() {
|
||||
assert_eq!(frame_category("Texture Generators - Noises", false, false).as_deref(), Some("Texture generators/Noises"));
|
||||
assert_eq!(frame_category("Spline & Path tools - Path tools", false, false).as_deref(), Some("Spline & Path tools/Path tools"));
|
||||
assert_eq!(frame_category("Material Filters - 1 click", false, false).as_deref(), Some("Material filters/1-click"));
|
||||
assert_eq!(frame_category("Mesh-based generators - Weathering", false, false).as_deref(), Some("Mesh-based generators/Weathering"));
|
||||
assert_eq!(frame_category("PBR Materials", false, false).as_deref(), Some("PBR materials"));
|
||||
assert_eq!(frame_category("Atomic Nodes", false, false).as_deref(), Some("Atomic nodes"));
|
||||
|
||||
// The category MaterialCraft renamed still reads from older layouts
|
||||
assert_eq!(frame_category("SDF functions - Primitives", false, false).as_deref(), Some("MCF functions/Primitives"));
|
||||
assert_eq!(frame_category("Functions Inside", false, false), None);
|
||||
assert_eq!(frame_category("Filters - Nowhere", false, false), None);
|
||||
assert_eq!(frame_category("Comparison", true, true).as_deref(), Some("Function nodes/Comparison"));
|
||||
assert_eq!(frame_category("Comparison", true, false).as_deref(), Some("Functions/Comparison"));
|
||||
assert_eq!(frame_category("Unknown", true, true), None);
|
||||
}
|
||||
|
||||
/// Identifier labels preserve recognized acronyms and omit empty words.
|
||||
#[test]
|
||||
fn identifiers_read_as_labels() {
|
||||
assert_eq!(humanize("3D_perlin_noise"), "3D Perlin Noise");
|
||||
assert_eq!(humanize("bnw_spots_1"), "BnW Spots 1");
|
||||
assert_eq!(humanize("rgb-a_merge"), "RGB-A Merge");
|
||||
assert_eq!(humanize("Functions/Math/acescg_to_srgb"), "ACEScg To sRGB");
|
||||
assert_eq!(humanize("__"), "");
|
||||
}
|
||||
|
||||
/// Function categories use exact path segments and known name overrides.
|
||||
#[test]
|
||||
fn functions_sort_into_sub_categories_by_folder_and_name() {
|
||||
assert_eq!(function_category("Functions/Math/Pi"), "Functions/Constant");
|
||||
assert_eq!(function_category("Functions/Math/Equality_Float2"), "Functions/Comparison");
|
||||
assert_eq!(function_category("Functions/Math/Parity/EvenCount"), "Functions/Parity");
|
||||
assert_eq!(function_category("Functions/Math/Trigo/acos"), "Functions/Maths");
|
||||
assert_eq!(function_category("Functions/Math/Trigo/deg_to_rad"), "Functions/Conversion");
|
||||
assert_eq!(function_category("Functions/easings/sine/ease_in_sine"), "Functions/Easings");
|
||||
assert_eq!(function_category("Functions/switch/Float2/switch_float2_4_inputs"), "Functions/Various");
|
||||
assert_eq!(function_category("Functions/Tonemappers/tonemap_ACES"), "Functions/Color");
|
||||
assert_eq!(function_category("Functions/Mathematics/x"), "Functions", "a folder name must match whole");
|
||||
assert_eq!(function_category("Loose"), "Functions");
|
||||
}
|
||||
|
||||
/// The isolated bundled catalog has unique entries in recognized categories.
|
||||
#[test]
|
||||
fn the_bundled_library_fills_the_tree_with_what_materialcraft_has() {
|
||||
let library = fixture::library();
|
||||
assert!(library.layouts.is_empty());
|
||||
assert!(library.packages.contains_key("sbs://functions.sbs"));
|
||||
|
||||
let entries = library.entries(&library.packages);
|
||||
let ids: BTreeSet<_> = entries.iter().map(|entry| entry.id.as_str()).collect();
|
||||
assert_eq!(ids.len(), entries.len(), "ids are unique");
|
||||
assert!(entries.iter().all(|entry| entry.missing.is_none()), "everything listed can be added");
|
||||
let known = |category: &str| {
|
||||
let mut parts = category.split('/');
|
||||
let top = parts.next().unwrap_or("");
|
||||
CATEGORIES.iter().any(|(name, subs)| *name == top && parts.next().is_none_or(|sub| subs.contains(&sub)))
|
||||
};
|
||||
for entry in &entries {
|
||||
assert!(known(&entry.category), "{} sits in unknown category {}", entry.id, entry.category);
|
||||
}
|
||||
let count = |category: &str| entries.iter().filter(|entry| entry.category == category).count();
|
||||
let find = |id: &str| entries.iter().find(|entry| entry.id == id).unwrap_or_else(|| panic!("no entry {id}"));
|
||||
|
||||
for top in ["Function nodes", "Functions"] {
|
||||
let (_, subs) = CATEGORIES.iter().find(|(name, _)| *name == top).unwrap();
|
||||
for sub in *subs {
|
||||
assert!(count(&format!("{top}/{sub}")) > 0, "{top}/{sub} is empty");
|
||||
}
|
||||
}
|
||||
|
||||
// Every bundled function has a sub-category
|
||||
let functions = library.packages["sbs://functions.sbs"].graphs.iter().filter(|graph| graph.function.is_some()).count();
|
||||
assert_eq!(entries.iter().filter(|entry| entry.category.starts_with("Functions/")).count(), functions);
|
||||
assert_eq!(count("Functions"), 0);
|
||||
assert_eq!(find("sbs://functions.sbs#Functions/Tonemappers/tonemap_ACES").category, "Functions/Color");
|
||||
assert_eq!(
|
||||
entries.iter().filter(|entry| entry.category == "Graph items").map(|entry| entry.label.as_str()).collect::<Vec<_>>(),
|
||||
["Comment", "Frame", "Pin", "Dot node"]
|
||||
);
|
||||
for id in ["node:blur", "node:bitmap", "node:output", "node:input_color", "node:input_value"] {
|
||||
assert_eq!(find(id).category, "Atomic nodes", "{id}");
|
||||
}
|
||||
assert_eq!(find("function:add").category, "Function nodes/Operator");
|
||||
assert_eq!(find("pattern:paramset").category, "FxMap nodes");
|
||||
let pi = find("sbs://functions.sbs#Functions/Math/Pi");
|
||||
assert_eq!((pi.label.as_str(), pi.category.as_str()), ("Pi", "Functions/Constant"));
|
||||
assert_eq!(find("sbs://functions.sbs#Functions/Math/Equality_Float2").category, "Functions/Comparison");
|
||||
}
|
||||
|
||||
/// A layout that places a library node MaterialCraft doesn't have yet, a function and a sub-category
|
||||
/// the PBR keywords decide
|
||||
const LAYOUT: &str = r#"<package><dependencies>
|
||||
<dependency><filename v="sbs://3d_perlin_noise.sbs"/><uid v="2"/></dependency>
|
||||
<dependency><filename v="sbs://materials/bricks_001.sbs"/><uid v="3"/></dependency></dependencies>
|
||||
<content><graph><identifier v="Layout"/><compNodes>
|
||||
<compNode><uid v="10"/><GUILayout><gpos v="20 40 0"/></GUILayout><compImplementation><compInstance><path v="pkg:///3D_perlin_noise?dependency=2"/></compInstance></compImplementation></compNode>
|
||||
<compNode><uid v="11"/><GUILayout><gpos v="220 40 0"/></GUILayout><compImplementation><compInstance><path v="pkg:///bricks_001?dependency=3"/></compInstance></compImplementation></compNode>
|
||||
</compNodes><GUIObjects>
|
||||
<GUIObject><type v="COMMENT"/><GUILayout><gpos v="0 0 0"/><size v="160 200"/></GUILayout><title v="Texture Generators - Noises"/></GUIObject>
|
||||
<GUIObject><type v="COMMENT"/><GUILayout><gpos v="200 0 0"/><size v="160 200"/></GUILayout><title v="PBR Materials"/></GUIObject>
|
||||
</GUIObjects></graph></content></package>"#;
|
||||
|
||||
/// A missing layout entry becomes available when its package is supplied.
|
||||
#[test]
|
||||
fn a_layout_lists_what_it_places_and_a_library_package_makes_it_available() {
|
||||
let frames = materialcraft_formats::sbs::read_layout(LAYOUT.as_bytes(), "sbs://layout.sbs").unwrap();
|
||||
let library = NodeLibrary { placements: placements(&frames), ..Default::default() };
|
||||
let entries = library.entries(&BTreeMap::new());
|
||||
let perlin = entries.iter().find(|entry| entry.id == "sbs://3d_perlin_noise.sbs#3D_perlin_noise").unwrap();
|
||||
assert_eq!((perlin.label.as_str(), perlin.category.as_str()), ("3D Perlin Noise", "Texture generators/Noises"));
|
||||
assert!(perlin.missing.is_some(), "a placed node whose package is absent is listed but not addable");
|
||||
let bricks = entries.iter().find(|entry| entry.id == "sbs://materials/bricks_001.sbs#bricks_001").unwrap();
|
||||
assert_eq!(bricks.category, "PBR materials/Bricks");
|
||||
|
||||
let mut graph = Graph::new("3D_perlin_noise");
|
||||
graph.add_node("uniform", [0.0; 2]);
|
||||
graph.add_node("output", [200.0, 0.0]);
|
||||
let mut package = Package::new("3d_perlin_noise");
|
||||
package.graphs.push(graph.clone());
|
||||
graph.name = "Loose".into();
|
||||
graph.attributes.category = "Filters/Blurs".into();
|
||||
package.graphs.push(graph);
|
||||
let dependencies = BTreeMap::from([("sbs://3d_perlin_noise.sbs".to_string(), Arc::new(package))]);
|
||||
|
||||
let entries = library.entries(&dependencies);
|
||||
let perlin = entries.iter().find(|entry| entry.id == "sbs://3d_perlin_noise.sbs#3D_perlin_noise").unwrap();
|
||||
assert!(perlin.missing.is_none());
|
||||
assert_eq!(perlin.category, "Texture generators/Noises");
|
||||
let loose = entries.iter().find(|entry| entry.id == "sbs://3d_perlin_noise.sbs#Loose").unwrap();
|
||||
assert_eq!((loose.category.as_str(), loose.canvas), ("Filters/Blurs", LibraryCanvas::Material));
|
||||
}
|
||||
|
||||
/// Invalid library files produce warnings while native entries remain usable.
|
||||
#[test]
|
||||
fn unreadable_library_files_warn_instead_of_failing() {
|
||||
let library = NodeLibrary::load(&["sbs://does_not_exist.sbs".into(), "sbs://../escape.sbs".into()]);
|
||||
assert!(library.packages.is_empty() && library.layouts.is_empty());
|
||||
assert_eq!(library.warnings.len(), 2);
|
||||
let entries = library.entries(&BTreeMap::new());
|
||||
assert!(entries.iter().any(|entry| entry.id == "node:blur" && entry.category == "Atomic nodes"));
|
||||
assert!(entries.iter().any(|entry| entry.id == "function:add" && entry.category == "Function nodes/Operator"));
|
||||
}
|
||||
|
||||
/// Classification tags take precedence over package folders and support multiple placements.
|
||||
#[test]
|
||||
fn function_tags_choose_library_filters_before_path_fallbacks() {
|
||||
let mut package = Package::new("Functions");
|
||||
for (name, category, tags) in [("Pi", "Function", "Maths"), ("Tagged", "", "Comparison; Easing"), ("Fallback", "", "Unknown")] {
|
||||
let mut graph = Graph::new(name);
|
||||
graph.folder = "Functions/Math".into();
|
||||
graph.function = Some(Default::default());
|
||||
graph.attributes.category = category.into();
|
||||
graph.attributes.tags = tags.into();
|
||||
package.graphs.push(graph);
|
||||
}
|
||||
let dependencies = BTreeMap::from([("sbs://classification.sbs".to_string(), Arc::new(package))]);
|
||||
|
||||
let entries = NodeLibrary::default().entries(&dependencies);
|
||||
let categories = |name: &str| entries.iter().filter(|entry| entry.label == name).map(|entry| entry.category.as_str()).collect::<Vec<_>>();
|
||||
|
||||
assert_eq!(categories("Pi"), ["Functions/Maths"]);
|
||||
assert_eq!(categories("Tagged"), ["Functions/Comparison", "Functions/Easings"]);
|
||||
assert_eq!(categories("Fallback"), ["Functions/Maths"]);
|
||||
}
|
||||
@@ -0,0 +1,11 @@
|
||||
use serde::Serialize;
|
||||
|
||||
/// The graph kind that can take an entry
|
||||
#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize)]
|
||||
#[serde(rename_all = "camelCase")]
|
||||
pub enum LibraryCanvas {
|
||||
Any,
|
||||
Material,
|
||||
Function,
|
||||
Pattern,
|
||||
}
|
||||
@@ -0,0 +1,22 @@
|
||||
use super::{LibraryCanvas, LibraryItem};
|
||||
use serde::Serialize;
|
||||
|
||||
/// One selectable library entry and its availability on a destination canvas.
|
||||
#[derive(Clone, Debug, PartialEq, Serialize)]
|
||||
pub struct LibraryEntry {
|
||||
/// Stable id, e.g. `node:blur`, `function:add`, `sbs://functions.sbs#Functions/Math/Pi`
|
||||
pub id: String,
|
||||
pub label: String,
|
||||
/// `Top` or `Top/Sub`, from [`super::CATEGORIES`]
|
||||
pub category: String,
|
||||
pub description: String,
|
||||
#[serde(flatten)]
|
||||
pub item: LibraryItem,
|
||||
pub canvas: LibraryCanvas,
|
||||
/// Why the entry can't be added yet (the package it needs is not in MaterialCraft)
|
||||
#[serde(skip_serializing_if = "Option::is_none")]
|
||||
pub missing: Option<String>,
|
||||
/// It can be added, but is incomplete (it uses operations MaterialCraft lacks)
|
||||
#[serde(skip_serializing_if = "Option::is_none")]
|
||||
pub warning: Option<String>,
|
||||
}
|
||||
@@ -0,0 +1,51 @@
|
||||
use super::LibraryCanvas;
|
||||
use materialcraft_core::PatternNodeKind;
|
||||
use serde::Serialize;
|
||||
|
||||
/// What adding an entry puts in the graph
|
||||
#[derive(Clone, Debug, PartialEq, Serialize)]
|
||||
#[serde(tag = "type", rename_all = "camelCase")]
|
||||
pub enum LibraryItem {
|
||||
/// A native node, by catalog id
|
||||
Node {
|
||||
def: String,
|
||||
},
|
||||
Comment,
|
||||
Frame,
|
||||
Pin,
|
||||
/// An instance of a graph from a library package
|
||||
Instance {
|
||||
package: String,
|
||||
graph: String,
|
||||
},
|
||||
/// A native function operation
|
||||
Operation {
|
||||
operation: String,
|
||||
},
|
||||
/// An instance of a function graph from a library package
|
||||
FunctionInstance {
|
||||
package: String,
|
||||
graph: String,
|
||||
},
|
||||
/// An FX-Map node
|
||||
Pattern {
|
||||
kind: PatternNodeKind,
|
||||
},
|
||||
/// An environment image
|
||||
Bitmap {
|
||||
resource: String,
|
||||
},
|
||||
}
|
||||
|
||||
impl LibraryItem {
|
||||
/// Return the canvas that accepts this item.
|
||||
pub fn canvas(&self) -> LibraryCanvas {
|
||||
match self {
|
||||
Self::Comment | Self::Frame | Self::Pin => LibraryCanvas::Any,
|
||||
Self::Node { def } if def == "dot" => LibraryCanvas::Any,
|
||||
Self::Operation { .. } | Self::FunctionInstance { .. } => LibraryCanvas::Function,
|
||||
Self::Pattern { .. } => LibraryCanvas::Pattern,
|
||||
_ => LibraryCanvas::Material,
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,8 @@
|
||||
use materialcraft_formats::sbs::LayoutItem;
|
||||
|
||||
/// A layout placement, before it is resolved against the loaded packages
|
||||
#[derive(Clone, Debug)]
|
||||
pub(super) struct LibraryPlacement {
|
||||
pub(super) category: String,
|
||||
pub(super) item: LayoutItem,
|
||||
}
|
||||
@@ -0,0 +1,194 @@
|
||||
//! Library commands: list the categorized library, add an entry to the open graph, and read the
|
||||
//! library folder again
|
||||
|
||||
use crate::commands::{CommandSpec, always, bad, boolp, has_graph, point, strp};
|
||||
use crate::node_library::{CATEGORIES, LibraryCanvas, LibraryEntry, LibraryItem, NodeLibrary};
|
||||
use crate::{FunctionGraphTarget, Result, Session, cmd};
|
||||
use serde_json::{Value, json};
|
||||
use std::collections::BTreeSet;
|
||||
|
||||
const ADD: &str = "library.add";
|
||||
|
||||
/// Register catalog queries, insertion and library reload commands.
|
||||
pub(crate) fn specs() -> Vec<CommandSpec> {
|
||||
vec![
|
||||
cmd!(
|
||||
"library.tree",
|
||||
"Library categories",
|
||||
[],
|
||||
None,
|
||||
"{filter?, category? (Top or Top/Sub), canvas? (material|function|pattern)} the library tree and its entries: id, label, category, type, canvas, missing (not addable yet), warning",
|
||||
always,
|
||||
tree
|
||||
),
|
||||
cmd!(
|
||||
"library.add",
|
||||
"Add library entry",
|
||||
[],
|
||||
None,
|
||||
"{entry (id from library.tree), at? [x, y], snapToGrid?, function?: FunctionGraphTarget, pattern?: owner node id} adds a library entry to the open graph (function entries to a Function canvas)",
|
||||
has_graph,
|
||||
add
|
||||
),
|
||||
cmd!("library.reload", "Reload library", [], None, "{} reads the SBS library folder again", always, reload),
|
||||
]
|
||||
}
|
||||
|
||||
impl Session {
|
||||
/// The library's entries, resolved against this session's loaded packages
|
||||
pub fn library_entries(&self) -> Vec<LibraryEntry> {
|
||||
self.library.entries(&self.pkg.dependencies)
|
||||
}
|
||||
}
|
||||
|
||||
/// List entries that match the requested text, category and destination canvas.
|
||||
fn tree(session: &mut Session, parameters: &Value) -> Result<Value> {
|
||||
let filter = strp(parameters, "filter").unwrap_or("").to_lowercase();
|
||||
let category = strp(parameters, "category").unwrap_or("");
|
||||
let canvas = match strp(parameters, "canvas") {
|
||||
None => None,
|
||||
Some("material") => Some(LibraryCanvas::Material),
|
||||
Some("function") => Some(LibraryCanvas::Function),
|
||||
Some("pattern") => Some(LibraryCanvas::Pattern),
|
||||
Some(other) => return Err(bad("library.tree", format!("unknown canvas `{other}`: material, function or pattern"))),
|
||||
};
|
||||
let entries: Vec<_> = session
|
||||
.library_entries()
|
||||
.into_iter()
|
||||
.filter(|entry| category.is_empty() || entry.category == category || entry.category.starts_with(&format!("{category}/")))
|
||||
.filter(|entry| canvas.is_none_or(|canvas| entry.canvas == LibraryCanvas::Any || entry.canvas == canvas))
|
||||
.filter(|entry| filter.is_empty() || entry.label.to_lowercase().contains(&filter) || entry.id.to_lowercase().contains(&filter))
|
||||
.collect();
|
||||
let categories: Vec<_> = CATEGORIES.iter().map(|(name, subcategories)| json!({"name": name, "subcategories": subcategories})).collect();
|
||||
Ok(json!({"categories": categories, "layouts": session.library.layouts, "entries": entries}))
|
||||
}
|
||||
|
||||
/// Validate an entry and dispatch its insertion through the destination graph command.
|
||||
fn add(session: &mut Session, parameters: &Value) -> Result<Value> {
|
||||
let id = strp(parameters, "entry").ok_or_else(|| bad(ADD, "`entry` is required (an id from library.tree)"))?;
|
||||
let entry = session.library_entries().into_iter().find(|entry| entry.id == id).ok_or_else(|| bad(ADD, format!("no library entry `{id}`")))?;
|
||||
if let Some(missing) = &entry.missing {
|
||||
return Err(bad(ADD, format!("{}: {missing}", entry.label)));
|
||||
}
|
||||
|
||||
let at = point(parameters, "at").unwrap_or([0.0, 0.0]);
|
||||
let snap = boolp(parameters, "snapToGrid").unwrap_or(false);
|
||||
let function_graph = session.graph()?.function.is_some();
|
||||
let target = parameters.get("function").cloned().filter(|target| !target.is_null());
|
||||
if entry.canvas == LibraryCanvas::Any {
|
||||
let destination = crate::AnnotationTarget::resolve(session, parameters)?;
|
||||
let mut arguments = destination.parameters();
|
||||
arguments["at"] = json!(at);
|
||||
let command = match &entry.item {
|
||||
LibraryItem::Comment => "graph.comment.add",
|
||||
LibraryItem::Frame => {
|
||||
arguments["rect"] = json!([at[0], at[1], 400.0, 260.0]);
|
||||
"graph.frame.add"
|
||||
}
|
||||
LibraryItem::Pin => "graph.pin.add",
|
||||
LibraryItem::Node { def } if def == "dot" => match crate::SelectionTarget::resolve(session, parameters)? {
|
||||
Some(crate::SelectionTarget::Function(target)) => {
|
||||
arguments = json!({"target": target, "edit": {"action": "add", "operation": "passthrough", "at": at, "snap": snap}});
|
||||
"graph.function.edit"
|
||||
}
|
||||
Some(crate::SelectionTarget::Pattern(owner)) => {
|
||||
arguments = json!({"id": owner.0, "edit": {"action": "add", "kind": "passthrough", "at": at, "snap": snap}});
|
||||
"graph.pattern.edit"
|
||||
}
|
||||
None => {
|
||||
arguments = json!({"def": "dot", "at": at, "snapToGrid": snap});
|
||||
"graph.node.add"
|
||||
}
|
||||
},
|
||||
_ => return Err(bad(ADD, "unknown graph item")),
|
||||
};
|
||||
let result = crate::execute(session, command, &arguments)?;
|
||||
if matches!(&entry.item, LibraryItem::Node { .. }) {
|
||||
session.annotation_selection = None;
|
||||
}
|
||||
return Ok(json!({"entry": entry.id, "result": result}));
|
||||
}
|
||||
if entry.canvas == LibraryCanvas::Function {
|
||||
let target = match target {
|
||||
Some(target) => serde_json::from_value::<FunctionGraphTarget>(target).map_err(|error| bad(ADD, error.to_string()))?,
|
||||
None if function_graph => FunctionGraphTarget::Graph,
|
||||
None => return Err(bad(ADD, format!("{} goes in a Function canvas: open a Function Graph or pass `function`", entry.label))),
|
||||
};
|
||||
let target = serde_json::to_value(target).map_err(|error| bad(ADD, error.to_string()))?;
|
||||
let result = match &entry.item {
|
||||
LibraryItem::Operation { operation } => crate::execute(
|
||||
session,
|
||||
"graph.function.edit",
|
||||
&json!({"target": target, "edit": {"action": "add", "operation": operation, "at": at, "snap": snap}}),
|
||||
)?,
|
||||
LibraryItem::FunctionInstance { package, graph } => {
|
||||
crate::execute(session, "library.function.add", &json!({"package": package, "graph": graph, "function": target, "at": at, "snapToGrid": snap}))?
|
||||
}
|
||||
_ => return Err(bad(ADD, "unexpected function entry")),
|
||||
};
|
||||
return Ok(json!({"entry": entry.id, "result": result}));
|
||||
}
|
||||
|
||||
if entry.canvas == LibraryCanvas::Pattern {
|
||||
return Err(bad(ADD, format!("{} is an FX-Map node: add it with graph.pattern.edit", entry.label)));
|
||||
}
|
||||
|
||||
if function_graph || target.is_some() || parameters.get("pattern").is_some() {
|
||||
return Err(bad(ADD, format!("{} goes in a material graph, not a Function Graph", entry.label)));
|
||||
}
|
||||
|
||||
let result = match &entry.item {
|
||||
LibraryItem::Node { def } => crate::execute(session, "graph.node.add", &json!({"def": def, "at": at, "snapToGrid": snap}))?,
|
||||
LibraryItem::Comment => crate::execute(session, "graph.comment.add", &json!({"at": at}))?,
|
||||
LibraryItem::Frame => crate::execute(session, "graph.frame.add", &json!({"rect": [at[0], at[1], 400.0, 260.0]}))?,
|
||||
LibraryItem::Pin => crate::execute(session, "graph.pin.add", &json!({"at": at}))?,
|
||||
LibraryItem::Instance { package, graph } => {
|
||||
crate::execute(session, "graph.instance.add", &json!({"package": package, "graph": graph, "at": at, "snapToGrid": snap}))?
|
||||
}
|
||||
_ => return Err(bad(ADD, format!("{} can't be added to a graph", entry.label))),
|
||||
};
|
||||
Ok(json!({"entry": entry.id, "result": result}))
|
||||
}
|
||||
|
||||
/// Replace library-owned snapshots while retaining explicit user dependencies.
|
||||
fn replace_library(session: &mut Session, library: std::sync::Arc<NodeLibrary>) {
|
||||
let mut changed = BTreeSet::new();
|
||||
session.library_sources.retain(|path, owned| session.linked_sources.get(path).is_some_and(|source| std::sync::Arc::ptr_eq(source, owned)));
|
||||
for path in session.library_sources.keys() {
|
||||
if !library.packages.contains_key(path) {
|
||||
session.linked_sources.remove(path);
|
||||
changed.insert(path.clone());
|
||||
}
|
||||
}
|
||||
session.library_sources.retain(|path, _| library.packages.contains_key(path));
|
||||
|
||||
for (path, package) in &library.packages {
|
||||
if session.linked_sources.contains_key(path) && !session.library_sources.contains_key(path) {
|
||||
continue;
|
||||
}
|
||||
|
||||
if session.linked_sources.get(path).is_none_or(|current| current.as_ref() != package.as_ref()) {
|
||||
session.linked_sources.insert(path.clone(), package.clone());
|
||||
changed.insert(path.clone());
|
||||
}
|
||||
if let Some(source) = session.linked_sources.get(path) {
|
||||
session.library_sources.insert(path.clone(), source.clone());
|
||||
}
|
||||
}
|
||||
for warning in &library.warnings {
|
||||
session.warn(warning.clone());
|
||||
}
|
||||
session.library = library;
|
||||
session.refresh_links_from(changed);
|
||||
}
|
||||
|
||||
/// Reload the installed library and report the catalog visible to this session.
|
||||
fn reload(session: &mut Session, _: &Value) -> Result<Value> {
|
||||
replace_library(session, NodeLibrary::reload());
|
||||
let entries = session.library_entries();
|
||||
Ok(json!({"entries": entries.len(), "available": entries.iter().filter(|entry| entry.missing.is_none()).count(), "layouts": session.library.layouts}))
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
#[path = "node_library_commands.test.rs"]
|
||||
mod tests;
|
||||
@@ -0,0 +1,46 @@
|
||||
use super::*;
|
||||
use materialcraft_core::{FunctionGraph, Graph, Package};
|
||||
use std::sync::Arc;
|
||||
|
||||
/// Build a small library with one reusable function and no filesystem dependencies.
|
||||
fn library(name: &str) -> Arc<NodeLibrary> {
|
||||
let mut function = Graph::new(name);
|
||||
function.function = Some(FunctionGraph::default());
|
||||
let mut package = Package::new("Custom library");
|
||||
package.graphs.push(function);
|
||||
let mut library = NodeLibrary::default();
|
||||
library.packages.insert("sbs://custom.sbs".into(), Arc::new(package));
|
||||
Arc::new(library)
|
||||
}
|
||||
|
||||
/// Reload replaces owned sources and removes sources no longer installed.
|
||||
#[test]
|
||||
fn reload_updates_and_removes_library_owned_sources() {
|
||||
let mut session = Session::with_library(Package::new("Project"), library("Before"));
|
||||
|
||||
replace_library(&mut session, library("After"));
|
||||
|
||||
assert!(session.library_entries().iter().any(|entry| entry.id == "sbs://custom.sbs#After"));
|
||||
assert!(!session.library_entries().iter().any(|entry| entry.id == "sbs://custom.sbs#Before"));
|
||||
|
||||
replace_library(&mut session, Arc::new(NodeLibrary::default()));
|
||||
|
||||
assert!(!session.pkg.dependencies.contains_key("sbs://custom.sbs"));
|
||||
assert!(!session.library_entries().iter().any(|entry| entry.id.starts_with("sbs://custom.sbs#")));
|
||||
assert!(!session.modified);
|
||||
}
|
||||
|
||||
/// Opening a package transfers dependency ownership even after initial session construction.
|
||||
#[test]
|
||||
fn reload_keeps_dependencies_supplied_by_later_opened_packages() {
|
||||
let mut session = Session::with_library(Package::new("First"), library("Original"));
|
||||
let custom = library("User_function");
|
||||
let mut package = Package::new("Second");
|
||||
package.dependencies = custom.packages.clone();
|
||||
session.open_package(package, None).unwrap();
|
||||
|
||||
replace_library(&mut session, library("Replacement"));
|
||||
|
||||
assert!(session.library_entries().iter().any(|entry| entry.id == "sbs://custom.sbs#User_function"));
|
||||
assert!(!session.library_entries().iter().any(|entry| entry.id == "sbs://custom.sbs#Replacement"));
|
||||
}
|
||||
@@ -10,6 +10,7 @@ pub struct OpenDocument {
|
||||
pub modified: bool,
|
||||
selection: Vec<NodeId>,
|
||||
annotation_selection: Option<AnnotationSelection>,
|
||||
annotation_target: crate::AnnotationTarget,
|
||||
view2d: View2d,
|
||||
view3d: View3d,
|
||||
material_preview: MaterialPreview,
|
||||
@@ -26,6 +27,7 @@ impl OpenDocument {
|
||||
graph: self.graph,
|
||||
selection: self.selection.clone(),
|
||||
annotation_selection: self.annotation_selection,
|
||||
annotation_target: self.annotation_target.clone(),
|
||||
material_preview: self.material_preview.clone(),
|
||||
label: label.into(),
|
||||
modified: self.modified,
|
||||
@@ -40,6 +42,7 @@ impl OpenDocument {
|
||||
self.graph = snapshot.graph.min(self.pkg.graphs.len().saturating_sub(1));
|
||||
self.selection = snapshot.selection;
|
||||
self.annotation_selection = snapshot.annotation_selection;
|
||||
self.annotation_target = snapshot.annotation_target;
|
||||
self.material_preview = snapshot.material_preview;
|
||||
self.modified = snapshot.modified;
|
||||
}
|
||||
@@ -90,6 +93,7 @@ impl OpenDocument {
|
||||
modified: false,
|
||||
selection: Vec::new(),
|
||||
annotation_selection: None,
|
||||
annotation_target: Default::default(),
|
||||
view2d: View2d::default(),
|
||||
view3d: View3d::default(),
|
||||
load_warnings: Vec::new(),
|
||||
@@ -114,6 +118,7 @@ impl OpenDocument {
|
||||
modified,
|
||||
selection,
|
||||
annotation_selection,
|
||||
annotation_target,
|
||||
view2d,
|
||||
view3d,
|
||||
material_preview,
|
||||
|
||||
@@ -0,0 +1,65 @@
|
||||
use crate::commands::{CommandSpec, bad, has_graph, point, strp, u64p};
|
||||
use crate::{AnnotationSelection, AnnotationTarget, Result, Session, cmd};
|
||||
use materialcraft_core::Pin;
|
||||
use serde_json::{Value, json};
|
||||
|
||||
/// Register navigation pin creation, description/position editing and deletion.
|
||||
pub(crate) fn specs() -> Vec<CommandSpec> {
|
||||
vec![
|
||||
cmd!("graph.pin.add", "Add Navigation pin", [], None, "{name?, description?, at? [x, y], function?, pattern?}", has_graph, add),
|
||||
cmd!("graph.pin.edit", "Edit Navigation pin", [], None, "{id, description?, at? [x, y], function?, pattern?}", has_graph, edit),
|
||||
cmd!("graph.pin.delete", "Delete pin", [], None, "{id, function?, pattern?}", has_graph, delete),
|
||||
]
|
||||
}
|
||||
|
||||
fn add(session: &mut Session, parameters: &Value) -> Result<Value> {
|
||||
let target = AnnotationTarget::resolve(session, parameters)?;
|
||||
let mut items = target.items(session)?;
|
||||
let id = target.next_id(session, &items)?;
|
||||
let name =
|
||||
strp(parameters, "description").or_else(|| strp(parameters, "name")).map(str::to_string).unwrap_or_else(|| format!("Pin {}", items.pins.len() + 1));
|
||||
let pos = point(parameters, "at").unwrap_or([0.0; 2]);
|
||||
items.pins.push(Pin { id, name, pos });
|
||||
|
||||
session.edit("Add pin", |session| {
|
||||
target.replace(session, items)?;
|
||||
session.selection.clear();
|
||||
session.annotation_target = target;
|
||||
session.annotation_selection = Some(AnnotationSelection::Pin(id));
|
||||
Ok(json!({"id": id}))
|
||||
})
|
||||
}
|
||||
|
||||
fn edit(session: &mut Session, parameters: &Value) -> Result<Value> {
|
||||
let target = AnnotationTarget::resolve(session, parameters)?;
|
||||
let id = u64p(parameters, "id").ok_or_else(|| bad("graph.pin.edit", "`id` is required"))?;
|
||||
let mut items = target.items(session)?;
|
||||
let pin = items.pins.iter_mut().find(|pin| pin.id == id).ok_or_else(|| bad("graph.pin.edit", format!("no pin {id}")))?;
|
||||
if let Some(description) = strp(parameters, "description").or_else(|| strp(parameters, "name")) {
|
||||
pin.name = description.into();
|
||||
}
|
||||
if let Some(position) = point(parameters, "at") {
|
||||
pin.pos = position;
|
||||
}
|
||||
|
||||
session.edit_merged(&format!("pin:{target:?}:{id}"), "Edit pin", |session| {
|
||||
target.replace(session, items)?;
|
||||
Ok(Value::Null)
|
||||
})
|
||||
}
|
||||
|
||||
fn delete(session: &mut Session, parameters: &Value) -> Result<Value> {
|
||||
let target = AnnotationTarget::resolve(session, parameters)?;
|
||||
let id = u64p(parameters, "id").ok_or_else(|| bad("graph.pin.delete", "`id` is required"))?;
|
||||
let mut items = target.items(session)?;
|
||||
let previous = items.pins.len();
|
||||
items.pins.retain(|pin| pin.id != id);
|
||||
if previous == items.pins.len() {
|
||||
return Err(bad("graph.pin.delete", format!("no pin {id}")));
|
||||
}
|
||||
|
||||
session.edit("Delete pin", |session| {
|
||||
target.replace(session, items)?;
|
||||
Ok(Value::Null)
|
||||
})
|
||||
}
|
||||
@@ -123,6 +123,8 @@ pub struct Session {
|
||||
pub(crate) next_document_id: u64,
|
||||
pub(crate) documents: std::collections::BTreeMap<u64, crate::OpenDocument>,
|
||||
pub(crate) linked_sources: std::collections::BTreeMap<String, Arc<Package>>,
|
||||
/// Snapshots inserted by the library, excluding explicitly supplied dependencies
|
||||
pub(crate) library_sources: std::collections::BTreeMap<String, Arc<Package>>,
|
||||
pub pkg: Package,
|
||||
/// Where the package was opened from or last saved to.
|
||||
pub path: Option<String>,
|
||||
@@ -130,6 +132,7 @@ pub struct Session {
|
||||
pub graph: usize,
|
||||
pub selection: Vec<NodeId>,
|
||||
pub annotation_selection: Option<AnnotationSelection>,
|
||||
pub annotation_target: crate::AnnotationTarget,
|
||||
pub view2d: View2d,
|
||||
pub view3d: View3d,
|
||||
pub material_preview: crate::MaterialPreview,
|
||||
@@ -157,17 +160,26 @@ pub struct Session {
|
||||
pub cache: Arc<Mutex<Cache>>,
|
||||
/// A mesh loaded for the 3D view (`scene: "custom"`): its file name and geometry.
|
||||
pub custom_mesh: Option<(String, Arc<materialcraft_geom::Mesh>)>,
|
||||
/// The node library loaded from the SBS library folder
|
||||
pub library: Arc<crate::node_library::NodeLibrary>,
|
||||
pub(crate) history: crate::document_history::DocumentHistory,
|
||||
group: Option<(Snapshot, bool)>,
|
||||
decoded: Arc<Mutex<HashMap<(u64, bool), Image>>>,
|
||||
}
|
||||
|
||||
impl Session {
|
||||
pub fn new(mut pkg: Package) -> Session {
|
||||
let library = crate::function_library::load();
|
||||
if let Ok(library) = &library {
|
||||
for (path, package) in &library.packages {
|
||||
pkg.dependencies.entry(path.clone()).or_insert_with(|| package.clone());
|
||||
/// Open a package with the process's installed node library.
|
||||
pub fn new(pkg: Package) -> Session {
|
||||
Self::with_library(pkg, crate::node_library::NodeLibrary::shared())
|
||||
}
|
||||
|
||||
/// Open a package with an explicit library, preserving dependencies supplied by the caller.
|
||||
pub fn with_library(mut pkg: Package, library: Arc<crate::NodeLibrary>) -> Session {
|
||||
let mut library_sources = std::collections::BTreeMap::new();
|
||||
for (path, package) in &library.packages {
|
||||
if let std::collections::btree_map::Entry::Vacant(entry) = pkg.dependencies.entry(path.clone()) {
|
||||
entry.insert(package.clone());
|
||||
library_sources.insert(path.clone(), package.clone());
|
||||
}
|
||||
}
|
||||
let mut session = Session {
|
||||
@@ -177,6 +189,7 @@ impl Session {
|
||||
next_document_id: 1,
|
||||
documents: std::collections::BTreeMap::new(),
|
||||
linked_sources: pkg.dependencies.clone(),
|
||||
library_sources,
|
||||
material_preview: crate::MaterialPreview::for_graph(&pkg, 0),
|
||||
cooked_graph: None,
|
||||
material_cooked: std::collections::BTreeMap::new(),
|
||||
@@ -185,6 +198,7 @@ impl Session {
|
||||
graph: 0,
|
||||
selection: Vec::new(),
|
||||
annotation_selection: None,
|
||||
annotation_target: Default::default(),
|
||||
view2d: View2d { channel: "rgba".into(), ..View2d::default() },
|
||||
view3d: View3d::default(),
|
||||
preview_size: Some(512),
|
||||
@@ -201,19 +215,19 @@ impl Session {
|
||||
cook_epoch: 0,
|
||||
cache: Arc::new(Mutex::new(Cache::default())),
|
||||
custom_mesh: None,
|
||||
library: Default::default(),
|
||||
history: Default::default(),
|
||||
group: None,
|
||||
decoded: Arc::new(Mutex::new(HashMap::new())),
|
||||
};
|
||||
session.refresh_links();
|
||||
match library {
|
||||
Ok(library) => {
|
||||
for warning in library.warnings {
|
||||
session.warn(warning);
|
||||
}
|
||||
}
|
||||
Err(error) => session.warn(format!("Missing function library: {error}")),
|
||||
for warning in &library.warnings {
|
||||
session.warn(warning.clone());
|
||||
}
|
||||
if !library.packages.contains_key(crate::function_library::STANDARD_PACKAGE) {
|
||||
session.warn(format!("Missing function library: {} did not load", crate::function_library::STANDARD_PACKAGE));
|
||||
}
|
||||
session.library = library;
|
||||
session
|
||||
}
|
||||
|
||||
@@ -232,6 +246,7 @@ impl Session {
|
||||
graph: self.graph,
|
||||
selection: self.selection.clone(),
|
||||
annotation_selection: self.annotation_selection,
|
||||
annotation_target: self.annotation_target.clone(),
|
||||
material_preview: self.material_preview.clone(),
|
||||
label: label.into(),
|
||||
modified: self.modified,
|
||||
@@ -330,6 +345,7 @@ impl Session {
|
||||
self.graph = s.graph.min(self.pkg.graphs.len().saturating_sub(1));
|
||||
self.selection = s.selection;
|
||||
self.annotation_selection = s.annotation_selection;
|
||||
self.annotation_target = s.annotation_target;
|
||||
self.material_preview = s.material_preview;
|
||||
self.modified = s.modified;
|
||||
self.dirty = s.dirty || self.cook_epoch != s.cook_epoch;
|
||||
|
||||
@@ -7,6 +7,7 @@ pub(crate) struct Snapshot {
|
||||
pub(crate) graph: usize,
|
||||
pub(crate) selection: Vec<NodeId>,
|
||||
pub(crate) annotation_selection: Option<AnnotationSelection>,
|
||||
pub(crate) annotation_target: crate::AnnotationTarget,
|
||||
pub(crate) material_preview: crate::MaterialPreview,
|
||||
pub(crate) label: String,
|
||||
pub(crate) modified: bool,
|
||||
|
||||
@@ -66,3 +66,110 @@ fn annotation_properties_and_selection_survive_edits_undo_and_native_save() {
|
||||
assert!(session.graph().unwrap().frames.is_empty());
|
||||
assert_eq!(session.graph().unwrap().comments.len(), 1);
|
||||
}
|
||||
|
||||
/// Pins share annotation selection, properties, deletion and undo.
|
||||
#[test]
|
||||
fn navigation_pins_select_edit_delete_and_save() {
|
||||
for kind in ["material", "function"] {
|
||||
let mut session = new_session();
|
||||
if kind == "function" {
|
||||
execute(&mut session, "file.new", &json!({"kind": kind})).unwrap();
|
||||
}
|
||||
let id = execute(&mut session, "graph.pin.add", &json!({"at": [-64, 128]})).unwrap()["id"].as_u64().unwrap();
|
||||
execute(&mut session, "graph.annotation.select", &json!({"kind": "pin", "id": id})).unwrap();
|
||||
execute(&mut session, "graph.pin.edit", &json!({"id": id, "description": "Start & <finish>", "at": [48, -96]})).unwrap();
|
||||
let loaded = read_sbs(&write_sbs(&session.pkg).unwrap(), "pins.sbs", &|_| None).unwrap();
|
||||
assert!(loaded.warnings.is_empty());
|
||||
let graph = loaded.pkg.graph_by_name(&session.graph().unwrap().sbs_path()).unwrap().1;
|
||||
assert_eq!(graph.pins[0].name, "Start & <finish>");
|
||||
assert_eq!(graph.pins[0].pos, [48.0, -96.0]);
|
||||
|
||||
execute(&mut session, "edit.delete", &json!({})).unwrap();
|
||||
assert!(session.graph().unwrap().pins.is_empty());
|
||||
assert!(session.annotation_selection.is_none());
|
||||
session.undo().unwrap();
|
||||
assert_eq!(session.graph().unwrap().pins[0].name, "Start & <finish>");
|
||||
assert_eq!(serde_json::to_value(session.annotation_selection).unwrap(), json!({"kind": "pin", "id": id}));
|
||||
let original = session.pkg.clone();
|
||||
assert!(execute(&mut session, "graph.pin.edit", &json!({"id": 999999, "description": "Missing"})).is_err());
|
||||
assert_eq!(session.pkg, original);
|
||||
}
|
||||
}
|
||||
|
||||
/// Every graph item edits its destination canvas and survives native SBS save/reload.
|
||||
#[test]
|
||||
fn library_graph_items_work_in_material_function_and_embedded_canvases() {
|
||||
use materialcraft_engine::{
|
||||
AnnotationTarget, FunctionGraphTarget, Session,
|
||||
core::{FunctionGraph, NodeId, Value},
|
||||
};
|
||||
for kind in ["material", "function", "pixel_processor", "value_processor", "dynamic", "fx_map"] {
|
||||
let mut session = new_session();
|
||||
let target = match kind {
|
||||
"material" => AnnotationTarget::Graph,
|
||||
"function" => {
|
||||
execute(&mut session, "file.new", &json!({"kind": "function"})).unwrap();
|
||||
AnnotationTarget::Graph
|
||||
}
|
||||
_ => {
|
||||
let definition = if kind == "dynamic" { "uniform" } else { kind };
|
||||
let node = NodeId(execute(&mut session, "graph.node.add", &json!({"def": definition})).unwrap()["id"].as_u64().unwrap());
|
||||
match kind {
|
||||
"fx_map" => AnnotationTarget::Pattern { owner: node },
|
||||
"dynamic" => {
|
||||
session.graph_mut().unwrap().node_mut(node).unwrap().functions.insert("color".into(), FunctionGraph::default());
|
||||
AnnotationTarget::Function { target: FunctionGraphTarget::Dynamic { node, parameter: "color".into() } }
|
||||
}
|
||||
_ => AnnotationTarget::Function { target: FunctionGraphTarget::Parameter { node, parameter: "function".into() } },
|
||||
}
|
||||
}
|
||||
};
|
||||
let mut parameters = target.parameters();
|
||||
parameters["at"] = json!([64, 128]);
|
||||
for entry in ["item:comment", "item:frame", "item:pin", "node:dot"] {
|
||||
parameters["entry"] = json!(entry);
|
||||
let before = session.pkg.clone();
|
||||
execute(&mut session, "library.add", ¶meters).unwrap();
|
||||
let after = session.pkg.clone();
|
||||
session.undo().unwrap();
|
||||
assert_eq!(session.pkg, before, "{kind}: {entry} undo");
|
||||
session.redo().unwrap();
|
||||
assert_eq!(session.pkg, after, "{kind}: {entry} redo");
|
||||
}
|
||||
let items = target.items(&session).unwrap();
|
||||
assert_eq!((items.comments.len(), items.frames.len(), items.pins.len()), (1, 1, 1), "{kind}");
|
||||
let mut pin_parameters = target.parameters();
|
||||
pin_parameters["id"] = json!(items.pins[0].id);
|
||||
pin_parameters["kind"] = json!("pin");
|
||||
execute(&mut session, "graph.annotation.select", &pin_parameters).unwrap();
|
||||
pin_parameters["description"] = json!("Checkpoint & <finish>");
|
||||
execute(&mut session, "graph.pin.edit", &pin_parameters).unwrap();
|
||||
|
||||
let loaded = read_sbs(&write_sbs(&session.pkg).unwrap(), "graph-items.sbs", &|_| None).unwrap();
|
||||
let mut reopened = Session::new(loaded.pkg);
|
||||
reopened.graph = reopened.pkg.graph_by_name(&session.graph().unwrap().sbs_path()).unwrap().0;
|
||||
let graph = reopened.graph().unwrap();
|
||||
let saved = match kind {
|
||||
"material" | "function" => AnnotationTarget::Graph.items(&reopened).unwrap(),
|
||||
"fx_map" => match &graph.nodes.iter().find(|node| node.def == kind).unwrap().params["pattern"] {
|
||||
Value::PatternGraph(graph) => graph.annotations.clone(),
|
||||
other => panic!("unexpected {other:?}"),
|
||||
},
|
||||
"dynamic" => graph.nodes.iter().find(|node| node.def == "uniform").unwrap().functions["color"].annotations.clone(),
|
||||
_ => match &graph.nodes.iter().find(|node| node.def == kind).unwrap().params["function"] {
|
||||
Value::Function(graph) => graph.annotations.clone(),
|
||||
other => panic!("unexpected {other:?}"),
|
||||
},
|
||||
};
|
||||
assert_eq!((saved.comments.len(), saved.frames.len(), saved.pins.len()), (1, 1, 1), "{kind}");
|
||||
assert_eq!(saved.pins[0].name, "Checkpoint & <finish>", "{kind}");
|
||||
assert_eq!(saved.pins[0].pos, [64.0, 128.0], "{kind}");
|
||||
if target != AnnotationTarget::Graph {
|
||||
assert!(graph.frames.is_empty() && graph.comments.is_empty() && graph.pins.is_empty(), "{kind}: parent must stay untouched");
|
||||
}
|
||||
execute(&mut session, "edit.delete", &json!({})).unwrap();
|
||||
assert!(target.items(&session).unwrap().pins.is_empty(), "{kind}");
|
||||
session.undo().unwrap();
|
||||
assert_eq!(target.items(&session).unwrap().pins[0].name, "Checkpoint & <finish>");
|
||||
}
|
||||
}
|
||||
@@ -594,20 +594,19 @@ fn processor_node_availability_is_shared_and_preserves_existing_sampler_graphs()
|
||||
let target = FunctionGraphTarget::Parameter { node, parameter: "function".into() };
|
||||
let operations: Vec<_> = target.available_operations(&session).map(|operation| operation.id).collect();
|
||||
let full_catalog = materialcraft_engine::nodes::function::FUNCTIONS;
|
||||
let sampling = definition == "pixel_processor";
|
||||
assert_eq!(operations.len(), full_catalog.len() - if sampling { 0 } else { 2 });
|
||||
assert_eq!(operations.len(), full_catalog.len());
|
||||
assert!(operations.contains(&"add"));
|
||||
for sampler in ["samplelum", "samplecol"] {
|
||||
assert_eq!(operations.contains(&sampler), sampling);
|
||||
assert!(operations.contains(&sampler));
|
||||
let original = session.pkg.clone();
|
||||
let history = session.history();
|
||||
let result =
|
||||
execute(&mut session, "graph.function.edit", &json!({"target": target, "edit": {"action": "add", "operation": sampler, "at": [0, 0]}}));
|
||||
assert_eq!(result.is_ok(), sampling);
|
||||
if !sampling {
|
||||
assert_eq!(session.pkg, original);
|
||||
assert_eq!(session.history(), history);
|
||||
}
|
||||
|
||||
execute(&mut session, "graph.function.edit", &json!({"target": target, "edit": {"action": "add", "operation": sampler, "at": [0, 0]}})).unwrap();
|
||||
|
||||
let inserted = session.pkg.clone();
|
||||
session.undo().unwrap();
|
||||
assert_eq!(session.pkg, original);
|
||||
session.redo().unwrap();
|
||||
assert_eq!(session.pkg, inserted);
|
||||
}
|
||||
let mut existing = FunctionGraph::default();
|
||||
existing.add("samplelum", &[], Some(Value::Int2([0, 1])));
|
||||
@@ -619,3 +618,41 @@ fn processor_node_availability_is_shared_and_preserves_existing_sampler_graphs()
|
||||
assert_eq!(target.available_operations(&session).count(), materialcraft_engine::nodes::function::FUNCTIONS.len());
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn library_samplers_read_image_inputs_in_both_processors() {
|
||||
for definition in ["pixel_processor", "value_processor"] {
|
||||
for sampler in ["samplelum", "samplecol"] {
|
||||
let mut session = new_session();
|
||||
session.preview_size = Some(16);
|
||||
let color = [0.25, 0.5, 0.75, 1.0];
|
||||
let image = NodeId(
|
||||
execute(&mut session, "graph.node.add", &json!({"def": "uniform", "params": {"color_mode": true, "color": color}})).unwrap()["id"]
|
||||
.as_u64()
|
||||
.unwrap(),
|
||||
);
|
||||
let parameters = if definition == "pixel_processor" { json!({"color_mode": sampler == "samplecol"}) } else { json!({}) };
|
||||
let owner = NodeId(execute(&mut session, "graph.node.add", &json!({"def": definition, "params": parameters})).unwrap()["id"].as_u64().unwrap());
|
||||
session.graph_mut().unwrap().connect(image, "output", owner, "input0").unwrap();
|
||||
let target = FunctionGraphTarget::Parameter { node: owner, parameter: "function".into() };
|
||||
let mut function = FunctionGraph::default();
|
||||
let position = function.add_constant(Value::Float2([0.5; 2]));
|
||||
execute(&mut session, "graph.function.set", &json!({"target": target, "function": function})).unwrap();
|
||||
|
||||
let result = execute(&mut session, "library.add", &json!({"entry": format!("function:{sampler}"), "function": target, "at": [160, 0]})).unwrap();
|
||||
let id = result["result"]["id"].as_u64().unwrap();
|
||||
execute(&mut session, "graph.function.edit", &json!({"target": target, "edit": {"action": "connect", "from": position, "to": id, "input": 0}}))
|
||||
.unwrap();
|
||||
execute(&mut session, "graph.function.edit", &json!({"target": target, "edit": {"action": "output", "id": id}})).unwrap();
|
||||
session.cook();
|
||||
|
||||
if definition == "value_processor" {
|
||||
let expected = if sampler == "samplecol" { Value::Float4(color) } else { Value::Float(color[0]) };
|
||||
assert_eq!(session.cooked.value(owner, 0), Some(&expected));
|
||||
} else {
|
||||
let expected = if sampler == "samplecol" { color } else { [color[0], color[0], color[0], 1.0] };
|
||||
assert_eq!(session.cooked.image(owner, 0).unwrap().get(0, 0, false), expected);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -20,6 +20,7 @@ mod graph_properties;
|
||||
mod linked_instances;
|
||||
mod linked_resources;
|
||||
mod material_preview;
|
||||
mod node_library;
|
||||
mod normal_maps;
|
||||
mod open_documents;
|
||||
mod optimization_perf;
|
||||
|
||||
@@ -0,0 +1,110 @@
|
||||
use materialcraft_engine::{
|
||||
Session,
|
||||
core::{FunctionGraph, Graph, Package},
|
||||
execute,
|
||||
};
|
||||
use serde_json::{Value, json};
|
||||
|
||||
#[path = "../support/node_library.rs"]
|
||||
mod fixture;
|
||||
|
||||
/// Return the catalog entries exposed by the library command.
|
||||
fn entries(session: &mut Session, parameters: Value) -> Vec<Value> {
|
||||
execute(session, "library.tree", ¶meters).unwrap()["entries"].as_array().unwrap().clone()
|
||||
}
|
||||
|
||||
/// Catalog filters preserve matching entries and reject unknown canvases.
|
||||
#[test]
|
||||
fn the_library_tree_lists_categories_and_filters_entries() {
|
||||
let mut session = fixture::session();
|
||||
let tree = execute(&mut session, "library.tree", &json!({})).unwrap();
|
||||
let names: Vec<_> = tree["categories"].as_array().unwrap().iter().map(|category| category["name"].as_str().unwrap()).collect();
|
||||
assert_eq!(names[..4], ["Graph items", "Atomic nodes", "FxMap nodes", "Function nodes"]);
|
||||
assert!(names.contains(&"MCF functions") && !names.contains(&"SDF functions"));
|
||||
assert_eq!(tree["layouts"], json!([]));
|
||||
|
||||
let constants = entries(&mut session, json!({"category": "Functions/Constant"}));
|
||||
assert!(constants.iter().any(|entry| entry["label"] == "Pi"));
|
||||
let functions = entries(&mut session, json!({"category": "Functions"}));
|
||||
let expected = fixture::library().packages["sbs://functions.sbs"].graphs.iter().filter(|graph| graph.function.is_some()).count();
|
||||
assert_eq!(functions.len(), expected, "every bundled function, across the sub-categories");
|
||||
assert!(entries(&mut session, json!({})).iter().all(|entry| entry["missing"].is_null()));
|
||||
assert!(entries(&mut session, json!({"category": "Texture generators"})).is_empty());
|
||||
|
||||
let functions = entries(&mut session, json!({"canvas": "function", "filter": "pi"}));
|
||||
assert!(functions.iter().any(|entry| entry["id"] == "sbs://functions.sbs#Functions/Math/Pi" && entry["type"] == "functionInstance"));
|
||||
assert!(functions.iter().all(|entry| entry["canvas"] == "function" || entry["canvas"] == "any"));
|
||||
assert!(execute(&mut session, "library.tree", &json!({"canvas": "teapot"})).is_err());
|
||||
}
|
||||
|
||||
/// Library additions use compatible canvases and participate in undo.
|
||||
#[test]
|
||||
fn library_entries_add_to_the_graph_they_fit() {
|
||||
let mut session = fixture::session();
|
||||
let before = session.graph().unwrap().nodes.len();
|
||||
let added = execute(&mut session, "library.add", &json!({"entry": "node:blur", "at": [32.0, 64.0]})).unwrap();
|
||||
assert_eq!(added["entry"], "node:blur");
|
||||
let graph = session.graph().unwrap();
|
||||
assert_eq!(graph.nodes.len(), before + 1);
|
||||
assert_eq!(graph.nodes.last().unwrap().def, "blur");
|
||||
assert_eq!(graph.nodes.last().unwrap().pos, [32.0, 64.0]);
|
||||
|
||||
for (entry, check) in [("item:comment", "comments"), ("item:frame", "frames"), ("item:pin", "pins")] {
|
||||
let count = |session: &Session| serde_json::to_value(session.graph().unwrap()).unwrap()[check].as_array().map_or(0, Vec::len);
|
||||
let previous = count(&session);
|
||||
execute(&mut session, "library.add", &json!({"entry": entry})).unwrap();
|
||||
assert_eq!(count(&session), previous + 1, "{entry}");
|
||||
}
|
||||
|
||||
assert!(execute(&mut session, "library.add", &json!({"entry": "nothing"})).is_err());
|
||||
assert!(execute(&mut session, "library.add", &json!({})).is_err());
|
||||
|
||||
// Function entries need a Function canvas
|
||||
assert!(execute(&mut session, "library.add", &json!({"entry": "function:add"})).is_err());
|
||||
assert!(execute(&mut session, "library.add", &json!({"entry": "pattern:paramset"})).is_err());
|
||||
|
||||
let mut package = Package::new("Functions");
|
||||
let mut graph = Graph::new("Caller");
|
||||
graph.function = Some(FunctionGraph::default());
|
||||
package.graphs.push(graph);
|
||||
let mut session = Session::with_library(package, fixture::library());
|
||||
execute(&mut session, "library.add", &json!({"entry": "function:add", "at": [0.0, 0.0]})).unwrap();
|
||||
execute(&mut session, "library.add", &json!({"entry": "sbs://functions.sbs#Functions/Math/Pi", "at": [140.0, 0.0]})).unwrap();
|
||||
let function = session.graph().unwrap().function.as_ref().unwrap();
|
||||
assert_eq!(function.nodes.len(), 2);
|
||||
assert!(function.nodes.iter().any(|node| node.op == "add"));
|
||||
assert!(function.nodes.iter().any(|node| node.instance.as_ref().is_some_and(|instance| instance.graph == "Functions/Math/Pi")));
|
||||
assert!(execute(&mut session, "library.add", &json!({"entry": "node:blur"})).is_err());
|
||||
execute(&mut session, "edit.undo", &json!({})).unwrap();
|
||||
assert_eq!(session.graph().unwrap().function.as_ref().unwrap().nodes.len(), 1);
|
||||
}
|
||||
|
||||
/// Reload reports the installed catalog without modifying an unrelated graph.
|
||||
#[test]
|
||||
fn reloading_the_library_keeps_open_work_unmodified() {
|
||||
let mut session = fixture::session();
|
||||
let reloaded = execute(&mut session, "library.reload", &json!({})).unwrap();
|
||||
let entries = session.library_entries();
|
||||
assert_eq!(reloaded["entries"].as_u64(), Some(entries.len() as u64));
|
||||
assert_eq!(reloaded["available"].as_u64(), Some(entries.iter().filter(|entry| entry.missing.is_none()).count() as u64));
|
||||
assert!(!session.modified);
|
||||
assert!(session.library.packages.keys().all(|path| session.pkg.dependencies.contains_key(path)));
|
||||
}
|
||||
|
||||
/// Reload must retain an explicitly supplied package even when its alias matches the library.
|
||||
#[test]
|
||||
fn review_reload_preserves_user_library_alias() {
|
||||
let mut dependency = Package::new("User functions");
|
||||
let mut function = Graph::new("User_function");
|
||||
function.function = Some(FunctionGraph::default());
|
||||
dependency.graphs.push(function);
|
||||
let mut package = Package::new("Project");
|
||||
package.graphs.push(Graph::new("Material"));
|
||||
package.dependencies.insert("sbs://functions.sbs".into(), std::sync::Arc::new(dependency.clone()));
|
||||
let mut session = Session::with_library(package, fixture::library());
|
||||
|
||||
execute(&mut session, "library.reload", &json!({})).unwrap();
|
||||
|
||||
assert!(session.pkg.dependencies["sbs://functions.sbs"].graphs == dependency.graphs, "the user dependency was replaced");
|
||||
assert!(entries(&mut session, json!({})).iter().any(|entry| entry["id"] == "sbs://functions.sbs#User_function"));
|
||||
}
|
||||
@@ -0,0 +1,27 @@
|
||||
//! An isolated catalog fixture shared by the library unit and integration tests.
|
||||
|
||||
use materialcraft_core::{Graph, Package};
|
||||
use materialcraft_engine::{NodeLibrary, Session};
|
||||
use std::sync::{Arc, OnceLock};
|
||||
|
||||
/// Load only the embedded functions, independent of the installed library directory.
|
||||
pub fn library() -> Arc<NodeLibrary> {
|
||||
static LIBRARY: OnceLock<Arc<NodeLibrary>> = OnceLock::new();
|
||||
LIBRARY
|
||||
.get_or_init(|| {
|
||||
let read = materialcraft_formats::sbs::read_sbs(include_bytes!("../../../../assets/sbs/functions.sbs"), "sbs://functions.sbs", &|_| None).unwrap();
|
||||
assert!(read.warnings.is_empty(), "{:?}", read.warnings);
|
||||
let mut library = NodeLibrary::default();
|
||||
library.packages.insert("sbs://functions.sbs".into(), Arc::new(read.pkg));
|
||||
Arc::new(library)
|
||||
})
|
||||
.clone()
|
||||
}
|
||||
|
||||
/// Start an empty material graph with the isolated bundled library.
|
||||
#[allow(dead_code)]
|
||||
pub fn session() -> Session {
|
||||
let mut package = Package::new("Library tests");
|
||||
package.graphs.push(Graph::new("Material"));
|
||||
Session::with_library(package, library())
|
||||
}
|
||||
@@ -265,7 +265,11 @@ fn input_change_recooks_only_readers() {
|
||||
value: Some(Value::Text("a".into())),
|
||||
pos: [0.0; 2],
|
||||
};
|
||||
p.graphs[0].node_mut(reader).unwrap().params.insert("function".into(), Value::Function(Box::new(FunctionGraph { nodes: vec![get_a], output: Some(1) })));
|
||||
p.graphs[0]
|
||||
.node_mut(reader)
|
||||
.unwrap()
|
||||
.params
|
||||
.insert("function".into(), Value::Function(Box::new(FunctionGraph { nodes: vec![get_a], output: Some(1), ..Default::default() })));
|
||||
let cache = &Mutex::new(Cache::default());
|
||||
let mut opts = Options::new(&no_res);
|
||||
opts.overrides.insert("a".into(), Value::Float(0.25));
|
||||
|
||||
@@ -32,11 +32,9 @@ pub(super) fn package(bytes: &[u8], source: &str) -> Result<Package, Box<dyn std
|
||||
graph.exposed.iter().map(|parameter| parameter.id.as_str()).collect::<Vec<_>>().join(", ")
|
||||
};
|
||||
graph.attributes.description = format!("Evaluates the {} function graph. Result type: {}. Inputs: {inputs}.", graph.name, result.label());
|
||||
graph.attributes.category = graph.folder.clone();
|
||||
graph.attributes.author.clear();
|
||||
graph.attributes.author_url.clear();
|
||||
graph.attributes.user_data.clear();
|
||||
graph.attributes.tags.clear();
|
||||
graph.frames.clear();
|
||||
graph.comments.clear();
|
||||
graph.pins.clear();
|
||||
|
||||
@@ -10,7 +10,8 @@ fn conversion_preserves_function_bodies_and_replaces_presentation_metadata() {
|
||||
graph.attributes.author = "Source author".into();
|
||||
graph.attributes.author_url = "https://example.org/source".into();
|
||||
graph.attributes.user_data = "Source notes".into();
|
||||
graph.attributes.tags = "Source tags".into();
|
||||
graph.attributes.category = "Function".into();
|
||||
graph.attributes.tags = "Maths".into();
|
||||
graph.function_type = 256;
|
||||
let mut body = FunctionGraph::default();
|
||||
let left = body.add_constant(Value::Float(1.0));
|
||||
@@ -30,7 +31,10 @@ fn conversion_preserves_function_bodies_and_replaces_presentation_metadata() {
|
||||
assert!(converted.graphs[0].attributes.author.is_empty());
|
||||
assert!(converted.graphs[0].attributes.author_url.is_empty());
|
||||
assert!(converted.graphs[0].attributes.user_data.is_empty());
|
||||
assert!(converted.graphs[0].attributes.tags.is_empty());
|
||||
assert_eq!(converted.graphs[0].attributes.category, "Function");
|
||||
assert_eq!(converted.graphs[0].attributes.tags, "Maths");
|
||||
assert_eq!(reopened.graphs[0].attributes.category, "Function");
|
||||
assert_eq!(reopened.graphs[0].attributes.tags, "Maths");
|
||||
assert_eq!(converted.graphs[0].function, reopened.graphs[0].function);
|
||||
let mut restored = converted.graphs[0].function.clone().unwrap();
|
||||
let original = imported.graphs[0].function.as_ref().unwrap();
|
||||
@@ -64,3 +68,21 @@ fn layout_separates_nodes_and_rejects_invalid_connections_without_partial_edits(
|
||||
function.nodes[0].inputs = vec![Some(9999)];
|
||||
assert!(super::layout::reposition(&mut function).unwrap_err().contains("missing node"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn conversion_preserves_empty_classification_attributes() {
|
||||
let mut package = Package::new("Functions");
|
||||
let mut graph = Graph::new("EmptyMetadata");
|
||||
graph.folder = "Functions/Math".into();
|
||||
let mut function = FunctionGraph::default();
|
||||
function.output = Some(function.add_constant(Value::Float(1.0)));
|
||||
graph.function = Some(function);
|
||||
graph.function_type = 256;
|
||||
package.graphs.push(graph);
|
||||
let bytes = write_sbs(&package).unwrap();
|
||||
|
||||
let converted = super::convert::package(&bytes, "source.sbs").unwrap();
|
||||
|
||||
assert!(converted.graphs[0].attributes.category.is_empty());
|
||||
assert!(converted.graphs[0].attributes.tags.is_empty());
|
||||
}
|
||||
@@ -8,9 +8,13 @@ use roxmltree::Node as XmlNode;
|
||||
use std::fmt::Write as _;
|
||||
|
||||
pub(super) fn write_canvas_items(output: &mut String, graph: &Graph, writer: &mut SbsWriter) {
|
||||
write_items(output, &graph.frames, &graph.comments, &graph.pins, writer);
|
||||
}
|
||||
|
||||
pub(super) fn write_items(output: &mut String, frames: &[Frame], comments: &[Comment], pins: &[Pin], writer: &mut SbsWriter) {
|
||||
output.push_str("<GUIObjects>");
|
||||
|
||||
for frame in &graph.frames {
|
||||
for frame in frames {
|
||||
let [x, y, width, height] = frame.rect.map(format_float);
|
||||
let [red, green, blue] = [0, 1, 2].map(|channel| format_float(linear_to_srgb(frame.color[channel])));
|
||||
let _ = write!(
|
||||
@@ -24,7 +28,7 @@ pub(super) fn write_canvas_items(output: &mut String, graph: &Graph, writer: &mu
|
||||
);
|
||||
}
|
||||
|
||||
for comment in &graph.comments {
|
||||
for comment in comments {
|
||||
let [x, y] = comment.pos.map(format_float);
|
||||
let [width, height] = comment.size.map(format_float);
|
||||
let _ = write!(
|
||||
@@ -35,7 +39,7 @@ pub(super) fn write_canvas_items(output: &mut String, graph: &Graph, writer: &mu
|
||||
);
|
||||
}
|
||||
|
||||
for pin in &graph.pins {
|
||||
for pin in pins {
|
||||
let [x, y] = pin.pos.map(format_float);
|
||||
let _ = write!(
|
||||
output,
|
||||
@@ -85,3 +89,10 @@ pub(super) fn read_canvas_items(element: XmlNode, graph: &mut Graph, warnings: &
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Embedded canvases use the same GUIObjects schema as document graphs.
|
||||
pub(super) fn read_embedded(element: XmlNode) -> materialcraft_core::CanvasAnnotations {
|
||||
let mut graph = Graph::new("embedded");
|
||||
read_canvas_items(element, &mut graph, &mut Warnings::default());
|
||||
materialcraft_core::CanvasAnnotations { frames: graph.frames, comments: graph.comments, pins: graph.pins }
|
||||
}
|
||||
@@ -8,7 +8,11 @@ use std::collections::{BTreeMap, BTreeSet};
|
||||
use std::fmt::Write;
|
||||
|
||||
pub(super) fn read(element: XmlNode<'_, '_>) -> Result<FunctionGraph, String> {
|
||||
let mut graph = FunctionGraph { output: child_value(element, "rootnode").and_then(|value| value.parse().ok()), nodes: Vec::new() };
|
||||
let mut graph = FunctionGraph {
|
||||
output: child_value(element, "rootnode").and_then(|value| value.parse().ok()),
|
||||
nodes: Vec::new(),
|
||||
annotations: super::canvas::read_embedded(element),
|
||||
};
|
||||
let mut ids = BTreeSet::new();
|
||||
for element in child_element(element, "paramNodes").into_iter().flat_map(|nodes| children_named(nodes, "paramNode")) {
|
||||
if graph.nodes.len() >= 4096 {
|
||||
@@ -153,7 +157,11 @@ pub(super) fn write(graph: &FunctionGraph, writer: &mut SbsWriter) -> Result<Str
|
||||
}
|
||||
output.push_str("</paramNode>");
|
||||
}
|
||||
output.push_str("</paramNodes></dynamicValue>");
|
||||
output.push_str("</paramNodes>");
|
||||
if !graph.annotations.is_empty() {
|
||||
super::canvas::write_items(&mut output, &graph.annotations.frames, &graph.annotations.comments, &graph.annotations.pins, writer);
|
||||
}
|
||||
output.push_str("</dynamicValue>");
|
||||
Ok(output)
|
||||
}
|
||||
|
||||
|
||||
@@ -0,0 +1,10 @@
|
||||
use super::LayoutItem;
|
||||
|
||||
/// A titled frame and the nodes inside it, top to bottom
|
||||
#[derive(Clone, Debug, PartialEq)]
|
||||
pub struct LayoutFrame {
|
||||
pub title: String,
|
||||
/// The frame groups function nodes (it sits in a function graph or a parameter function)
|
||||
pub function: bool,
|
||||
pub items: Vec<LayoutItem>,
|
||||
}
|
||||
@@ -0,0 +1,17 @@
|
||||
/// One node placed in a layout frame
|
||||
#[derive(Clone, Debug, PartialEq)]
|
||||
pub enum LayoutItem {
|
||||
/// An atomic SBS filter by its SBS name, with the MaterialCraft node it reads as (`None`
|
||||
/// when MaterialCraft has no counterpart yet)
|
||||
Atomic { filter: String, node: Option<&'static str> },
|
||||
/// A graph input (`input_color`, `input_grayscale`, `input_value`) or `output`
|
||||
Node(&'static str),
|
||||
/// An instance of graph `graph` from the library package `package`
|
||||
Instance { package: String, graph: String, outputs: Vec<String> },
|
||||
/// A native function operation, e.g. `add`
|
||||
Operation(String),
|
||||
/// An instance of function graph `graph` from the library package `package`
|
||||
FunctionInstance { package: String, graph: String },
|
||||
/// A bitmap showing one of the layout package's own resources, e.g. an environment image
|
||||
Bitmap { resource: String },
|
||||
}
|
||||
@@ -10,6 +10,7 @@ pub fn relative_path(uri: &str) -> Result<&str, String> {
|
||||
{
|
||||
return Err("invalid SBS library path".into());
|
||||
}
|
||||
|
||||
Ok(path)
|
||||
}
|
||||
|
||||
@@ -51,15 +52,18 @@ pub fn root() -> std::path::PathBuf {
|
||||
if let Some(root) = std::env::var_os("MATERIALCRAFT_SBS_DIR") {
|
||||
return root.into();
|
||||
}
|
||||
|
||||
if let Ok(executable) = std::env::current_exe()
|
||||
&& let Some(parent) = executable.parent()
|
||||
&& parent.join("assets/sbs").is_dir()
|
||||
{
|
||||
return parent.join("assets/sbs");
|
||||
}
|
||||
|
||||
std::path::Path::new(env!("CARGO_MANIFEST_DIR")).join("../../assets/sbs")
|
||||
}
|
||||
|
||||
/// Read a validated library alias from the configured directory or the embedded fallback.
|
||||
pub fn read(uri: &str) -> Result<Vec<u8>, String> {
|
||||
let relative = relative_path(uri)?;
|
||||
#[cfg(not(target_arch = "wasm32"))]
|
||||
@@ -82,3 +86,70 @@ pub fn read(uri: &str) -> Result<Vec<u8>, String> {
|
||||
_ => Err(format!("Missing library asset {uri}")),
|
||||
}
|
||||
}
|
||||
|
||||
/// The packages bundled into the binary, for installs and the browser without an asset folder
|
||||
pub const BUNDLED: &[&str] = &["sbs://functions.sbs"];
|
||||
|
||||
/// Bounds for scanning the library folder: how deep, and how many packages
|
||||
const MAX_DEPTH: usize = 6;
|
||||
const MAX_FILES: usize = 2048;
|
||||
|
||||
/// Every SBS package in the library as `sbs://` paths, sorted: the files under the asset folder
|
||||
/// (resource folders skipped), or the bundled packages when there is no folder
|
||||
pub fn files() -> Vec<String> {
|
||||
#[cfg(not(target_arch = "wasm32"))]
|
||||
{
|
||||
let root = root();
|
||||
if root.is_dir() {
|
||||
let mut found = Vec::new();
|
||||
scan(&root, "", 0, &mut found);
|
||||
found.sort();
|
||||
return found;
|
||||
}
|
||||
}
|
||||
BUNDLED.iter().map(|uri| uri.to_string()).collect()
|
||||
}
|
||||
|
||||
/// Discover packages in deterministic order within the depth and file limits.
|
||||
#[cfg(not(target_arch = "wasm32"))]
|
||||
fn scan(directory: &std::path::Path, prefix: &str, depth: usize, found: &mut Vec<String>) {
|
||||
let Ok(entries) = std::fs::read_dir(directory) else { return };
|
||||
let mut entries: Vec<_> = entries.flatten().collect();
|
||||
entries.sort_by_key(|entry| entry.file_name());
|
||||
for entry in entries {
|
||||
if found.len() >= MAX_FILES {
|
||||
return;
|
||||
}
|
||||
|
||||
let Some(name) = entry.file_name().to_str().map(str::to_string) else { continue };
|
||||
let Ok(kind) = entry.file_type() else { continue };
|
||||
let uri = format!("sbs://{prefix}{name}");
|
||||
|
||||
// Symlinks are skipped: `read` refuses files that leave the asset folder anyway
|
||||
if kind.is_dir() && depth < MAX_DEPTH && !name.ends_with(".resources") && !name.starts_with('.') {
|
||||
scan(&entry.path(), &format!("{prefix}{name}/"), depth + 1, found);
|
||||
} else if kind.is_file() && name.to_ascii_lowercase().ends_with(".sbs") && relative_path(&uri).is_ok() {
|
||||
found.push(uri);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
#[allow(clippy::unwrap_used)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
/// Discovered packages have unique valid aliases and the embedded fallback is present.
|
||||
#[test]
|
||||
fn the_library_lists_every_package_once_and_bundles_a_fallback() {
|
||||
let files = files();
|
||||
for uri in BUNDLED {
|
||||
assert!(files.iter().any(|file| file == uri), "{uri} in {files:?}");
|
||||
assert!(!read(uri).unwrap().is_empty());
|
||||
}
|
||||
let mut unique = files.clone();
|
||||
unique.dedup();
|
||||
assert_eq!(unique, files);
|
||||
assert!(files.iter().all(|file| relative_path(file).is_ok() && file.ends_with(".sbs")));
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,281 @@
|
||||
//! Library layouts. An SBS package can lay out a node library: its graphs group nodes in titled
|
||||
//! frames ("Filters - Blurs"), and a parameter function groups function nodes the same way. This
|
||||
//! reads the frames and the nodes inside each one; it does not cook anything. The engine decides
|
||||
//! which frame titles are library categories.
|
||||
|
||||
use super::{
|
||||
LayoutFrame, LayoutItem,
|
||||
constant::MAX_XML_NODES,
|
||||
filter_map::FILTERS,
|
||||
xml::{child_element, child_value, children_named, parse_floats},
|
||||
};
|
||||
use crate::{FormatError, Result};
|
||||
use roxmltree::Node as XmlNode;
|
||||
use std::collections::HashMap;
|
||||
|
||||
/// Bounds for hostile layouts: frames and placed nodes kept per file
|
||||
const MAX_FRAMES: usize = 4096;
|
||||
const MAX_ITEMS: usize = 65_536;
|
||||
|
||||
/// The frames of every graph and parameter function in `bytes`, in document order
|
||||
pub fn read_layout(bytes: &[u8], uri: &str) -> Result<Vec<LayoutFrame>> {
|
||||
let text = std::str::from_utf8(bytes).map_err(|e| FormatError::BadPackage(format!("the SBS file is not UTF-8 text: {e}")))?;
|
||||
let text = text.trim_start_matches('\u{feff}');
|
||||
let options = roxmltree::ParsingOptions { allow_dtd: false, nodes_limit: MAX_XML_NODES };
|
||||
let doc = roxmltree::Document::parse_with_options(text, options).map_err(|e| FormatError::BadPackage(format!("the SBS file is not valid XML: {e}")))?;
|
||||
let root = doc.root_element();
|
||||
if root.tag_name().name() != "package" {
|
||||
return Err(FormatError::BadPackage("not an SBS package (the root element is not <package>)".into()));
|
||||
}
|
||||
|
||||
let mut dependencies = HashMap::new();
|
||||
for dependency in child_element(root, "dependencies").into_iter().flat_map(|d| children_named(d, "dependency")) {
|
||||
if let (Some(uid), Some(file)) = (child_value(dependency, "uid"), child_value(dependency, "filename")) {
|
||||
let file = if file == "?himself" { uri.to_string() } else { super::library::resolve(uri, file).map_err(FormatError::BadPackage)? };
|
||||
dependencies.insert(uid, file);
|
||||
}
|
||||
}
|
||||
|
||||
let mut frames = Vec::new();
|
||||
let mut items = 0;
|
||||
for scope in root.descendants().filter(|node| node.is_element()) {
|
||||
let function = match scope.tag_name().name() {
|
||||
"graph" if child_element(scope, "compNodes").is_some() => false,
|
||||
_ if child_element(scope, "paramNodes").is_some() => true,
|
||||
_ => continue,
|
||||
};
|
||||
let mut scope_frames = scope_frames(scope);
|
||||
if scope_frames.is_empty() {
|
||||
continue;
|
||||
}
|
||||
|
||||
let nodes: Vec<(XmlNode, [f32; 2])> = if function {
|
||||
child_element(scope, "paramNodes").into_iter().flat_map(|n| children_named(n, "paramNode")).filter_map(|n| Some((n, position(n)?))).collect()
|
||||
} else {
|
||||
child_element(scope, "compNodes").into_iter().flat_map(|n| children_named(n, "compNode")).filter_map(|n| Some((n, position(n)?))).collect()
|
||||
};
|
||||
let mut placed: Vec<(usize, [f32; 2], LayoutItem)> = Vec::new();
|
||||
for (node, at) in nodes {
|
||||
if items >= MAX_ITEMS {
|
||||
break;
|
||||
}
|
||||
|
||||
// The smallest frame holding the node wins, so nested frames keep their own nodes
|
||||
let Some(frame) = scope_frames
|
||||
.iter()
|
||||
.enumerate()
|
||||
.filter(|(_, (_, rect))| at[0] >= rect[0] && at[1] >= rect[1] && at[0] <= rect[0] + rect[2] && at[1] <= rect[1] + rect[3])
|
||||
.min_by(|a, b| (a.1.1[2] * a.1.1[3]).total_cmp(&(b.1.1[2] * b.1.1[3])))
|
||||
.map(|(index, _)| index)
|
||||
else {
|
||||
continue;
|
||||
};
|
||||
|
||||
let item = if function { function_item(node, &dependencies) } else { graph_item(scope, node, &dependencies) };
|
||||
if let Some(item) = item {
|
||||
placed.push((frame, at, item));
|
||||
items += 1;
|
||||
}
|
||||
}
|
||||
placed.sort_by(|a, b| a.0.cmp(&b.0).then(a.1[1].total_cmp(&b.1[1])).then(a.1[0].total_cmp(&b.1[0])));
|
||||
let mut grouped: Vec<Vec<LayoutItem>> = vec![Vec::new(); scope_frames.len()];
|
||||
for (frame, _, item) in placed {
|
||||
if let Some(list) = grouped.get_mut(frame) {
|
||||
list.push(item);
|
||||
}
|
||||
}
|
||||
for ((title, _), items) in scope_frames.drain(..).zip(grouped) {
|
||||
if frames.len() >= MAX_FRAMES {
|
||||
break;
|
||||
}
|
||||
|
||||
frames.push(LayoutFrame { title, function, items });
|
||||
}
|
||||
}
|
||||
Ok(frames)
|
||||
}
|
||||
|
||||
/// The titled frames of a graph or function: (title, [x, y, width, height])
|
||||
fn scope_frames(scope: XmlNode) -> Vec<(String, [f32; 4])> {
|
||||
child_element(scope, "GUIObjects")
|
||||
.into_iter()
|
||||
.flat_map(|objects| children_named(objects, "GUIObject"))
|
||||
.filter(|object| child_value(*object, "type") == Some("COMMENT"))
|
||||
.filter_map(|object| {
|
||||
let title = child_value(object, "title")?.trim();
|
||||
let layout = child_element(object, "GUILayout")?;
|
||||
let at = parse_floats(child_value(layout, "gpos")?);
|
||||
let size = parse_floats(child_value(layout, "size")?);
|
||||
let rect = [*at.first()?, *at.get(1)?, *size.first()?, *size.get(1)?];
|
||||
(!title.is_empty() && rect[2] > 0.0 && rect[3] > 0.0).then(|| (title.chars().take(256).collect(), rect))
|
||||
})
|
||||
.take(MAX_FRAMES)
|
||||
.collect()
|
||||
}
|
||||
|
||||
/// Read a node position when its layout has both coordinates.
|
||||
fn position(node: XmlNode) -> Option<[f32; 2]> {
|
||||
let at = parse_floats(child_value(child_element(node, "GUILayout")?, "gpos")?);
|
||||
Some([*at.first()?, *at.get(1)?])
|
||||
}
|
||||
|
||||
/// `pkg:///Graph/Path?dependency=123` as (graph path, package file)
|
||||
fn reference(path: &str, dependencies: &HashMap<&str, String>) -> Option<(String, String)> {
|
||||
let path = path.strip_prefix("pkg:///")?;
|
||||
let (graph, query) = path.split_once('?').unwrap_or((path, ""));
|
||||
let uid = query.split('&').find_map(|pair| pair.strip_prefix("dependency="))?;
|
||||
let package = dependencies.get(uid)?.clone();
|
||||
let graph = graph.trim_matches('/');
|
||||
(!graph.is_empty()).then(|| (graph.chars().take(1024).collect(), package))
|
||||
}
|
||||
|
||||
/// Translate a graph node into a library placement without cooking it.
|
||||
fn graph_item(graph: XmlNode, node: XmlNode, dependencies: &HashMap<&str, String>) -> Option<LayoutItem> {
|
||||
let implementation = child_element(node, "compImplementation")?.children().find(|c| c.is_element())?;
|
||||
match implementation.tag_name().name() {
|
||||
"compFilter" => {
|
||||
let filter = child_value(implementation, "filter")?;
|
||||
if filter == "bitmap"
|
||||
&& let Some(resource) = string_parameter(implementation, "bitmapresourcepath")
|
||||
{
|
||||
let resource = resource.strip_prefix("pkg:///").unwrap_or(resource);
|
||||
let resource = resource.split_once('?').map_or(resource, |(path, _)| path);
|
||||
return Some(LayoutItem::Bitmap { resource: resource.chars().take(1024).collect() });
|
||||
}
|
||||
|
||||
Some(LayoutItem::Atomic { filter: filter.chars().take(128).collect(), node: FILTERS.iter().find(|f| f.sbs == filter).map(|f| f.def) })
|
||||
}
|
||||
"compInstance" => {
|
||||
let (graph, package) = reference(child_value(implementation, "path")?, dependencies)?;
|
||||
let outputs = child_element(implementation, "outputBridgings")
|
||||
.into_iter()
|
||||
.flat_map(|b| children_named(b, "outputBridging"))
|
||||
.filter_map(|b| child_value(b, "identifier"))
|
||||
.take(64)
|
||||
.map(str::to_string)
|
||||
.collect();
|
||||
Some(LayoutItem::Instance { package, graph, outputs })
|
||||
}
|
||||
"compInputBridge" => {
|
||||
let entry = child_value(implementation, "entry")?;
|
||||
let input = child_element(graph, "paraminputs")
|
||||
.into_iter()
|
||||
.flat_map(|inputs| children_named(inputs, "paraminput"))
|
||||
.find(|input| child_value(*input, "uid") == Some(entry));
|
||||
Some(LayoutItem::Node(match input.and_then(|input| child_value(input, "type")) {
|
||||
Some("1") | None => "input_color",
|
||||
Some("2") => "input_grayscale",
|
||||
Some(_) => "input_value",
|
||||
}))
|
||||
}
|
||||
"compOutputBridge" => Some(LayoutItem::Node("output")),
|
||||
_ => None,
|
||||
}
|
||||
}
|
||||
|
||||
/// Translate a native operation or reusable function reference into a placement.
|
||||
fn function_item(node: XmlNode, dependencies: &HashMap<&str, String>) -> Option<LayoutItem> {
|
||||
let operation = child_value(node, "function")?;
|
||||
if operation != "instance" {
|
||||
return Some(LayoutItem::Operation(operation.chars().take(128).collect()));
|
||||
}
|
||||
|
||||
let path = child_element(node, "funcDatas")
|
||||
.into_iter()
|
||||
.flat_map(|datas| children_named(datas, "funcData"))
|
||||
.find(|data| child_value(*data, "name") == Some("instance"))
|
||||
.and_then(|data| child_element(data, "constantValue"))
|
||||
.and_then(|value| child_value(value, "constantValueString"))?;
|
||||
let (graph, package) = reference(path, dependencies)?;
|
||||
Some(LayoutItem::FunctionInstance { package, graph })
|
||||
}
|
||||
|
||||
/// Read a named static string parameter from an atomic filter.
|
||||
fn string_parameter<'a>(filter: XmlNode<'a, '_>, name: &str) -> Option<&'a str> {
|
||||
child_element(filter, "parameters")
|
||||
.into_iter()
|
||||
.flat_map(|parameters| children_named(parameters, "parameter"))
|
||||
.find(|parameter| child_value(*parameter, "name") == Some(name))
|
||||
.and_then(|parameter| child_element(parameter, "paramValue"))
|
||||
.and_then(|value| child_value(value, "constantValueString"))
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
#[allow(clippy::unwrap_used, clippy::expect_used)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
const LAYOUT: &str = r#"<?xml version="1.0"?><package><dependencies>
|
||||
<dependency><filename v="?himself"/><uid v="1"/></dependency>
|
||||
<dependency><filename v="sbs://noise.sbs"/><uid v="2"/></dependency>
|
||||
<dependency><filename v="sbs://functions.sbs"/><uid v="3"/></dependency></dependencies>
|
||||
<content><graph><identifier v="Graph"/>
|
||||
<paraminputs><paraminput><identifier v="mask"/><uid v="40"/><type v="2"/></paraminput></paraminputs>
|
||||
<compNodes>
|
||||
<compNode><uid v="10"/><GUILayout><gpos v="20 90 0"/></GUILayout><compImplementation><compInstance><path v="pkg:///perlin_noise?dependency=2"/><outputBridgings><outputBridging><uid v="11"/><identifier v="output"/></outputBridging></outputBridgings></compInstance></compImplementation></compNode>
|
||||
<compNode><uid v="12"/><GUILayout><gpos v="20 40 0"/></GUILayout><compImplementation><compFilter><filter v="blur"/></compFilter></compImplementation></compNode>
|
||||
<compNode><uid v="13"/><GUILayout><gpos v="20 60 0"/></GUILayout><compImplementation><compInputBridge><entry v="40"/></compInputBridge></compImplementation></compNode>
|
||||
<compNode><uid v="14"/><GUILayout><gpos v="500 60 0"/></GUILayout><compImplementation><compFilter><filter v="bitmap"/><parameters><parameter><name v="bitmapresourcepath"/><paramValue><constantValueString v="pkg:///Resources/studio?dependency=1"/></paramValue></parameter></parameters></compFilter></compImplementation></compNode>
|
||||
<compNode><uid v="15"/><GUILayout><gpos v="900 900 0"/></GUILayout><compImplementation><compOutputBridge/></compImplementation></compNode>
|
||||
<compNode><uid v="16"/><GUILayout><gpos v="30 70 0"/></GUILayout><compImplementation><compFilter><filter v="blend"/><parameters><parameter><name v="opacitymult"/><paramValue><dynamicValue>
|
||||
<paramNodes>
|
||||
<paramNode><uid v="1"/><GUILayout><gpos v="0 10 0"/></GUILayout><function v="add"/></paramNode>
|
||||
<paramNode><uid v="2"/><GUILayout><gpos v="300 10 0"/></GUILayout><function v="instance"/><funcDatas><funcData><name v="instance"/><constantValue><constantValueString v="pkg:///Functions/Math/Pi?dependency=3"/></constantValue></funcData></funcDatas></paramNode>
|
||||
</paramNodes>
|
||||
<GUIObjects>
|
||||
<GUIObject><type v="COMMENT"/><GUILayout><gpos v="-10 0 0"/><size v="100 100"/></GUILayout><title v="Operator"/></GUIObject>
|
||||
<GUIObject><type v="COMMENT"/><GUILayout><gpos v="250 0 0"/><size v="100 100"/></GUILayout><title v="Constant"/></GUIObject>
|
||||
</GUIObjects></dynamicValue></paramValue></parameter></parameters></compFilter></compImplementation></compNode>
|
||||
</compNodes>
|
||||
<GUIObjects>
|
||||
<GUIObject><type v="COMMENT"/><GUILayout><gpos v="0 0 0"/><size v="160 200"/></GUILayout><title v="Texture Generators - Noises"/></GUIObject>
|
||||
<GUIObject><type v="COMMENT"/><GUILayout><gpos v="400 0 0"/><size v="160 200"/></GUILayout><title v="3D view - HDRI environments"/></GUIObject>
|
||||
<GUIObject><type v="COMMENT"/><GUILayout><gpos v="0 0 0"/><size v="10 10"/></GUILayout></GUIObject>
|
||||
</GUIObjects></graph></content></package>"#;
|
||||
|
||||
/// Frames preserve spatial ordering and distinguish material and function entries.
|
||||
#[test]
|
||||
fn frames_list_what_sits_inside_them_top_to_bottom() {
|
||||
let frames = read_layout(LAYOUT.as_bytes(), "sbs://layout.sbs").unwrap();
|
||||
let graph: Vec<_> = frames.iter().filter(|frame| !frame.function).collect();
|
||||
assert_eq!(graph.len(), 2);
|
||||
assert_eq!(graph[0].title, "Texture Generators - Noises");
|
||||
assert_eq!(
|
||||
graph[0].items,
|
||||
vec![
|
||||
LayoutItem::Atomic { filter: "blur".into(), node: Some("blur") },
|
||||
LayoutItem::Node("input_grayscale"),
|
||||
LayoutItem::Atomic { filter: "blend".into(), node: Some("blend") },
|
||||
LayoutItem::Instance { package: "sbs://noise.sbs".into(), graph: "perlin_noise".into(), outputs: vec!["output".into()] },
|
||||
]
|
||||
);
|
||||
assert_eq!(graph[1].items, vec![LayoutItem::Bitmap { resource: "Resources/studio".into() }]);
|
||||
|
||||
let function: Vec<_> = frames.iter().filter(|frame| frame.function).collect();
|
||||
assert_eq!(function.len(), 2);
|
||||
assert_eq!(function[0].items, vec![LayoutItem::Operation("add".into())]);
|
||||
assert_eq!(function[1].items, vec![LayoutItem::FunctionInstance { package: "sbs://functions.sbs".into(), graph: "Functions/Math/Pi".into() }]);
|
||||
}
|
||||
|
||||
/// Missing layouts and malformed input remain nonfatal.
|
||||
#[test]
|
||||
fn packages_without_frames_have_no_layout_and_bad_input_errors() {
|
||||
assert!(read_layout(b"<package><content><graph><compNodes/></graph></content></package>", "sbs://x.sbs").unwrap().is_empty());
|
||||
assert!(read_layout(b"<nope/>", "sbs://x.sbs").is_err());
|
||||
assert!(read_layout(b"\xff\xfe", "sbs://x.sbs").is_err());
|
||||
assert!(read_layout(b"<package><content><graph><compNodes><compNode><GUILayout><gpos v=\"nan\"/></GUILayout></compNode></compNodes><GUIObjects><GUIObject><type v=\"COMMENT\"/><GUILayout><gpos v=\"0 0\"/><size v=\"-5 1e40\"/></GUILayout><title v=\"X\"/></GUIObject></GUIObjects></graph></content></package>", "sbs://x.sbs").unwrap().is_empty());
|
||||
}
|
||||
|
||||
/// Relative layout references resolve beside the layout, including parent directories.
|
||||
#[test]
|
||||
fn review_layout_resolves_relative_dependencies() {
|
||||
let layout = LAYOUT.replace("sbs://noise.sbs", "../noise.sbs").replace("sbs://functions.sbs", "functions.sbs");
|
||||
|
||||
let frames = read_layout(layout.as_bytes(), "sbs://layouts/library.sbs").unwrap();
|
||||
|
||||
assert!(frames.iter().flat_map(|frame| &frame.items).any(|item| matches!(item,
|
||||
LayoutItem::Instance { package, .. } if package == "sbs://noise.sbs")));
|
||||
assert!(frames.iter().flat_map(|frame| &frame.items).any(|item| matches!(item,
|
||||
LayoutItem::FunctionInstance { package, .. } if package == "sbs://layouts/functions.sbs")));
|
||||
}
|
||||
}
|
||||
@@ -11,7 +11,10 @@ mod graph_attributes;
|
||||
mod group_layout;
|
||||
mod image_input;
|
||||
mod input_bridge;
|
||||
mod layout_frame;
|
||||
mod layout_item;
|
||||
pub mod library;
|
||||
mod library_layout;
|
||||
mod node_identifiers;
|
||||
mod node_parameter;
|
||||
mod output;
|
||||
@@ -29,6 +32,9 @@ mod warnings;
|
||||
mod xml;
|
||||
|
||||
pub use constant::SBS_EXT;
|
||||
pub use layout_frame::LayoutFrame;
|
||||
pub use layout_item::LayoutItem;
|
||||
pub use library_layout::read_layout;
|
||||
pub use read::{is_sbs, read_sbs};
|
||||
pub use sbs_read::SbsRead;
|
||||
pub use write::write_sbs;
|
||||
|
||||
@@ -32,7 +32,11 @@ pub(super) fn read(element: XmlNode<'_, '_>) -> Result<PatternGraph, String> {
|
||||
}
|
||||
}
|
||||
|
||||
let mut graph = PatternGraph { root: child_value(element, "rootnode").and_then(|id| id.parse().ok()), nodes: Vec::new() };
|
||||
let mut graph = PatternGraph {
|
||||
root: child_value(element, "rootnode").and_then(|id| id.parse().ok()),
|
||||
nodes: Vec::new(),
|
||||
annotations: super::canvas::read_embedded(element),
|
||||
};
|
||||
for element in child_element(element, "paramsGraphNodes").into_iter().flat_map(|nodes| children_named(nodes, "paramsGraphNode")) {
|
||||
if graph.nodes.len() >= 4096 {
|
||||
return Err("pattern graph exceeds the 4096-node limit".into());
|
||||
@@ -111,6 +115,10 @@ pub(super) fn write(graph: &PatternGraph, writer: &mut SbsWriter) -> Result<Stri
|
||||
}
|
||||
output.push_str("</connections></paramsGraphNode>");
|
||||
}
|
||||
output.push_str("</paramsGraphNodes></paramsGraph></paramsGraphs>");
|
||||
output.push_str("</paramsGraphNodes>");
|
||||
if !graph.annotations.is_empty() {
|
||||
super::canvas::write_items(&mut output, &graph.annotations.frames, &graph.annotations.comments, &graph.annotations.pins, writer);
|
||||
}
|
||||
output.push_str("</paramsGraph></paramsGraphs>");
|
||||
Ok(output)
|
||||
}
|
||||
@@ -184,7 +184,10 @@ impl<'text> SbsReader<'text, '_> {
|
||||
let dynamic = child_element(element, "paramValue").and_then(|value| child_element(value, "dynamicValue"));
|
||||
let function = dynamic.ok_or_else(|| "missing function body".to_string()).and_then(super::function_graph::read);
|
||||
graph.function = Some(match function {
|
||||
Ok(function) => function,
|
||||
Ok(mut function) => {
|
||||
function.annotations = Default::default();
|
||||
function
|
||||
}
|
||||
Err(error) => {
|
||||
self.warnings.add(format!("function graph `{name}`: {error}"));
|
||||
materialcraft_core::FunctionGraph::default()
|
||||
|
||||
@@ -167,9 +167,19 @@ fn bundled_library_has_complete_bodies_and_current_export_metadata() {
|
||||
assert!(function.output.is_some(), "{}", graph.sbs_path());
|
||||
assert!(function.nodes.iter().all(|node| node.missing.is_none()), "{}", graph.sbs_path());
|
||||
assert!(!graph.attributes.description.is_empty());
|
||||
assert!(graph.attributes.author.is_empty() && graph.attributes.tags.is_empty());
|
||||
assert!(graph.attributes.author.is_empty());
|
||||
assert!(graph.frames.is_empty() && graph.comments.is_empty() && graph.pins.is_empty());
|
||||
}
|
||||
let pi = &read.pkg.graph_by_name("Functions/Math/Pi").unwrap().1.attributes;
|
||||
assert!(pi.category.is_empty());
|
||||
assert_eq!(pi.tags, "Constant");
|
||||
let saved = write_sbs(&read.pkg).unwrap();
|
||||
let reopened = read_sbs(&saved, "functions.sbs", &|_| None).unwrap();
|
||||
for graph in &read.pkg.graphs {
|
||||
let reloaded = reopened.pkg.graph_by_name(&graph.sbs_path()).unwrap().1;
|
||||
assert_eq!(reloaded.attributes.category, graph.attributes.category);
|
||||
assert_eq!(reloaded.attributes.tags, graph.attributes.tags);
|
||||
}
|
||||
assert!(!xml.descendants().any(|element| element.has_tag_name("icon")));
|
||||
}
|
||||
|
||||
|
||||
@@ -3,7 +3,13 @@ use egui::Ui;
|
||||
use serde_json::json;
|
||||
|
||||
pub(super) fn show(app: &mut MaterialCraftApp, ui: &mut Ui, id: u64) {
|
||||
let Some(mut text) = app.session.graph().ok().and_then(|graph| graph.comments.iter().find(|comment| comment.id == id)).map(|comment| comment.text.clone())
|
||||
let Some(mut text) = app
|
||||
.session
|
||||
.annotation_target
|
||||
.items(&app.session)
|
||||
.ok()
|
||||
.and_then(|items| items.comments.into_iter().find(|comment| comment.id == id))
|
||||
.map(|comment| comment.text)
|
||||
else {
|
||||
return;
|
||||
};
|
||||
|
||||
@@ -3,7 +3,7 @@ use egui::Ui;
|
||||
use serde_json::json;
|
||||
|
||||
pub(super) fn show(app: &mut MaterialCraftApp, ui: &mut Ui, id: u64) {
|
||||
let Some(mut frame) = app.session.graph().ok().and_then(|graph| graph.frames.iter().find(|frame| frame.id == id)).cloned() else {
|
||||
let Some(mut frame) = app.session.annotation_target.items(&app.session).ok().and_then(|items| items.frames.into_iter().find(|frame| frame.id == id)) else {
|
||||
return;
|
||||
};
|
||||
|
||||
|
||||
@@ -1,5 +1,6 @@
|
||||
mod comment_properties;
|
||||
mod frame_properties;
|
||||
mod pin_properties;
|
||||
|
||||
use crate::MaterialCraftApp;
|
||||
use egui::Ui;
|
||||
@@ -9,5 +10,42 @@ pub(crate) fn show(app: &mut MaterialCraftApp, ui: &mut Ui, selection: Annotatio
|
||||
match selection {
|
||||
AnnotationSelection::Frame(id) => frame_properties::show(app, ui, id),
|
||||
AnnotationSelection::Comment(id) => comment_properties::show(app, ui, id),
|
||||
AnnotationSelection::Pin(id) => pin_properties::show(app, ui, id),
|
||||
}
|
||||
}
|
||||
|
||||
/// Resolve the destination before an editor is temporarily borrowed for drawing.
|
||||
pub(crate) fn target(app: &MaterialCraftApp) -> materialcraft_engine::AnnotationTarget {
|
||||
use materialcraft_engine::{AnnotationTarget, FunctionGraphTarget};
|
||||
if let Some(target) = app.function_editor.as_ref().and_then(|editor| editor.command_target()) {
|
||||
return match target {
|
||||
FunctionGraphTarget::Graph => AnnotationTarget::Graph,
|
||||
target => AnnotationTarget::Function { target },
|
||||
};
|
||||
}
|
||||
if crate::pattern::active(app)
|
||||
&& let Some(editor) = &app.pattern_editor
|
||||
{
|
||||
return AnnotationTarget::Pattern { owner: editor.node };
|
||||
}
|
||||
AnnotationTarget::Graph
|
||||
}
|
||||
|
||||
pub(crate) fn activate(app: &mut MaterialCraftApp, target: materialcraft_engine::AnnotationTarget) {
|
||||
if app.graph.annotation_target != target {
|
||||
app.session.annotation_selection = None;
|
||||
app.graph.cancel_drag();
|
||||
}
|
||||
app.graph.annotation_target = target;
|
||||
}
|
||||
|
||||
/// Read the active editor camera without replacing the parent graph's saved view.
|
||||
pub(crate) fn camera(app: &MaterialCraftApp) -> crate::state::GraphCamera {
|
||||
if let Some(editor) = &app.function_editor {
|
||||
editor.camera()
|
||||
} else if let Some(editor) = &app.pattern_editor {
|
||||
editor.camera()
|
||||
} else {
|
||||
app.ui.graph_camera
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,28 @@
|
||||
use crate::{MaterialCraftApp, i18n::tr};
|
||||
use egui::Ui;
|
||||
use serde_json::json;
|
||||
|
||||
/// The SBS pin label is edited as its Description property.
|
||||
pub(super) fn show(app: &mut MaterialCraftApp, ui: &mut Ui, id: u64) {
|
||||
let Some(mut name) =
|
||||
app.session.annotation_target.items(&app.session).ok().and_then(|items| items.pins.into_iter().find(|pin| pin.id == id)).map(|pin| pin.name)
|
||||
else {
|
||||
return;
|
||||
};
|
||||
|
||||
crate::properties::section(ui, "pin-parameters", tr("Parameters"), |ui| {
|
||||
ui.label(tr("Description"));
|
||||
let description = ui.add(egui::TextEdit::multiline(&mut name).desired_rows(4).desired_width(f32::INFINITY));
|
||||
crate::widgets::name(&description, egui::Role::TextInput, "Navigation Pin description");
|
||||
if app.graph.pin_description_focus == Some(id) {
|
||||
description.request_focus();
|
||||
app.graph.pin_description_focus = None;
|
||||
}
|
||||
if description.changed() {
|
||||
app.run("graph.pin.edit", json!({"id": id, "description": name}));
|
||||
}
|
||||
if description.lost_focus() {
|
||||
app.session.finish_edit();
|
||||
}
|
||||
});
|
||||
}
|
||||
@@ -311,6 +311,8 @@ fn handle_inner(app: &mut MaterialCraftApp, ctx: &egui::Context, method: &str, p
|
||||
crate::graph::editor_target::EditorTarget::Material => None,
|
||||
},
|
||||
"annotationSelection": app.session.annotation_selection,
|
||||
"annotationTarget": app.session.annotation_target,
|
||||
"pins": app.graph.pins.iter().map(|(id, bounds)| json!({"id": id, "rect": rect(*bounds)})).collect::<Vec<_>>(),
|
||||
"frames": app.graph.frames.iter().map(|(id, bounds)| json!({"id": id, "rect": rect(*bounds)})).collect::<Vec<_>>(),
|
||||
"comments": app.graph.comments.iter().map(|(id, bounds)| json!({"id": id, "rect": rect(*bounds)})).collect::<Vec<_>>(),
|
||||
"nodes": nodes.iter().map(|(id, r)| json!({"id": id.0, "rect": rect(*r)})).collect::<Vec<_>>(),
|
||||
|
||||
@@ -4,6 +4,8 @@ use egui::Ui;
|
||||
|
||||
mod actions;
|
||||
mod context_menu;
|
||||
mod explorer_menu_state;
|
||||
pub(crate) mod explorer_row;
|
||||
mod explorer_state;
|
||||
mod explorer_target;
|
||||
mod explorer_tree;
|
||||
@@ -16,6 +18,7 @@ use serde_json::json;
|
||||
use crate::MaterialCraftApp;
|
||||
use crate::i18n::tr;
|
||||
|
||||
/// Draw open packages and dispatch selection, resource and context-menu actions.
|
||||
pub fn show(app: &mut MaterialCraftApp, ui: &mut Ui) {
|
||||
ui.horizontal(|ui| {
|
||||
ui.spacing_mut().item_spacing.x = 2.0;
|
||||
@@ -49,11 +52,12 @@ pub fn show(app: &mut MaterialCraftApp, ui: &mut Ui) {
|
||||
inspected_graph: None,
|
||||
inspected_folder: None,
|
||||
};
|
||||
egui::ScrollArea::vertical().auto_shrink([false, false]).show(ui, |ui| {
|
||||
let scroll = egui::ScrollArea::vertical().auto_shrink([false, false]).show(ui, |ui| {
|
||||
for (document, package, path, modified) in tree.session.open_packages() {
|
||||
ui.push_id(document, |ui| tree.package(ui, document, package, path, modified));
|
||||
}
|
||||
});
|
||||
tree.state.hovered = ui.rect_contains_pointer(scroll.inner_rect);
|
||||
let action = tree.action;
|
||||
let opened_node = tree.opened_node;
|
||||
let assignment = tree.assignment;
|
||||
@@ -111,6 +115,35 @@ pub fn show(app: &mut MaterialCraftApp, ui: &mut Ui) {
|
||||
}
|
||||
}
|
||||
|
||||
/// Enter opens, F2 renames and Delete removes the selected graph or folder while the pointer is
|
||||
/// over the Explorer; elsewhere those keys keep their graph shortcuts. True when a key was used
|
||||
pub(crate) fn shortcuts(app: &mut MaterialCraftApp, ctx: &egui::Context) -> bool {
|
||||
if !app.ui.dock.is_visible(crate::docking::Panel::Explorer) || !app.ui.explorer.hovered || app.ui.explorer.rename.is_some() {
|
||||
return false;
|
||||
}
|
||||
|
||||
let Some(target) = app.ui.explorer.selected.clone() else { return false };
|
||||
let command = match &target {
|
||||
ExplorerTarget::Graph { .. } => [(egui::Key::Enter, "graph.open"), (egui::Key::F2, "graph.rename"), (egui::Key::Delete, "graph.delete")]
|
||||
.into_iter()
|
||||
.find(|(key, _)| pressed(ctx, *key)),
|
||||
ExplorerTarget::Folder { .. } if !target.is_resources_root() => {
|
||||
[(egui::Key::F2, "folder.rename"), (egui::Key::Delete, "folder.remove")].into_iter().find(|(key, _)| pressed(ctx, *key))
|
||||
}
|
||||
_ => None,
|
||||
};
|
||||
let Some((key, command)) = command else { return false };
|
||||
ctx.input_mut(|input| input.consume_key(egui::Modifiers::NONE, key));
|
||||
actions::invoke(app, ctx, target, command);
|
||||
true
|
||||
}
|
||||
|
||||
/// Match an unmodified Explorer shortcut key.
|
||||
fn pressed(ctx: &egui::Context, key: egui::Key) -> bool {
|
||||
ctx.input(|input| input.modifiers.is_none() && input.key_pressed(key))
|
||||
}
|
||||
|
||||
/// Draw the pending Explorer rename dialog.
|
||||
pub(crate) fn dialogs(app: &mut MaterialCraftApp, ctx: &egui::Context) {
|
||||
actions::rename_dialog(app, ctx);
|
||||
}
|
||||
@@ -2,10 +2,12 @@ use super::ExplorerTarget;
|
||||
use crate::{MaterialCraftApp, i18n::tr};
|
||||
use serde_json::json;
|
||||
|
||||
/// Activate the target package before dispatching its Explorer action.
|
||||
pub(super) fn activate(app: &mut MaterialCraftApp, document: u64) -> bool {
|
||||
document == app.session.document_id || app.run("package.activate", json!({"document": document})).is_some()
|
||||
}
|
||||
|
||||
/// Dispatch an Explorer action using the selected item and its owning package.
|
||||
pub(super) fn invoke(app: &mut MaterialCraftApp, ctx: &egui::Context, target: ExplorerTarget, command: &str) {
|
||||
if command == "graph.resource.add" {
|
||||
let mut parameters = target.parameters();
|
||||
@@ -55,15 +57,92 @@ pub(super) fn invoke(app: &mut MaterialCraftApp, ctx: &egui::Context, target: Ex
|
||||
"package.close" | "file.reload" => {
|
||||
crate::unsaved::guard(app, crate::unsaved::Guarded::Package { document: target.document(), reload: command == "file.reload" })
|
||||
}
|
||||
"file.save" | "file.saveAs" | "file.saveCopyAs" => {
|
||||
"file.save" | "file.saveAs" | "file.saveCopyAs" | "file.exportMaterial" | "file.sendToTextureCraft" => {
|
||||
crate::windows::file_action(app, ctx, command);
|
||||
}
|
||||
crate::menus::EXPLORER_COMPUTE => compute_outputs(app, &target),
|
||||
crate::menus::EXPLORER_VIEW_OUTPUTS => {
|
||||
if let ExplorerTarget::Graph { index, .. } = target
|
||||
&& app.run("view.3d.outputs", json!({"graph": index})).is_some()
|
||||
{
|
||||
app.ui.dock.focus(crate::docking::Panel::View3d);
|
||||
}
|
||||
}
|
||||
crate::menus::EXPLORER_EXPORT_OUTPUTS => {
|
||||
if let ExplorerTarget::Graph { index, .. } = target
|
||||
&& (index == app.session.graph || app.run("graph.open", json!({"graph": index})).is_some())
|
||||
{
|
||||
app.ui.windows.export = true;
|
||||
}
|
||||
}
|
||||
crate::menus::EXPLORER_SHOW_IN_FOLDER => show_in_folder(app),
|
||||
crate::menus::EXPLORER_OPEN_DEPENDENCIES => open_dependencies(app),
|
||||
_ => {
|
||||
app.run(command, target.parameters());
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// A dependency that is another package file on disk (not a library package or an unsaved one)
|
||||
pub(super) fn is_package_file(path: &str) -> bool {
|
||||
!path.starts_with("sbs://") && !path.starts_with("unsaved:") && !path.is_empty()
|
||||
}
|
||||
|
||||
/// Cook the graph's outputs, or every graph of the package with outputs, at full size
|
||||
fn compute_outputs(app: &mut MaterialCraftApp, target: &ExplorerTarget) {
|
||||
let graphs: Vec<usize> = match target {
|
||||
ExplorerTarget::Graph { index, .. } => vec![*index],
|
||||
_ => app.session.pkg.graphs.iter().enumerate().filter(|(_, graph)| graph.function.is_none()).map(|(index, _)| index).collect(),
|
||||
};
|
||||
let (mut milliseconds, mut errors) = (0.0, 0);
|
||||
for index in &graphs {
|
||||
let Some(result) = app.run("graph.cook", json!({"graph": index, "full": true})) else { return };
|
||||
milliseconds += result["ms"].as_f64().unwrap_or(0.0);
|
||||
errors += result["nodes"].as_array().map_or(0, |nodes| nodes.iter().filter(|node| !node["error"].is_null()).count());
|
||||
}
|
||||
let summary = crate::i18n::trf("Computed {count} graph(s) in {ms} ms", &[("count", &graphs.len()), ("ms", &format!("{milliseconds:.0}"))]);
|
||||
if errors > 0 {
|
||||
app.toast(format!("{summary}; {}", crate::i18n::trf("{count} node(s) failed: see the graph", &[("count", &errors)])), true);
|
||||
} else {
|
||||
app.toast(summary, false);
|
||||
}
|
||||
}
|
||||
|
||||
/// Return the active package path for native file actions.
|
||||
#[cfg(not(target_arch = "wasm32"))]
|
||||
fn package_path(app: &MaterialCraftApp) -> Option<String> {
|
||||
app.session.open_packages().into_iter().find(|entry| entry.0 == app.session.document_id).and_then(|entry| entry.2.map(str::to_string))
|
||||
}
|
||||
|
||||
/// Reveal the active package file when supported by the platform.
|
||||
#[cfg(not(target_arch = "wasm32"))]
|
||||
fn show_in_folder(app: &mut MaterialCraftApp) {
|
||||
let Some(path) = package_path(app) else { return };
|
||||
if let Err(error) = craft_update::process::reveal(std::path::Path::new(&path)) {
|
||||
app.toast(format!("{}: {error}", tr("Could not show the package file")), true);
|
||||
}
|
||||
}
|
||||
|
||||
/// Reveal the active package file when supported by the platform.
|
||||
#[cfg(target_arch = "wasm32")]
|
||||
fn show_in_folder(_: &mut MaterialCraftApp) {}
|
||||
|
||||
/// Open every package file the active package links, next to it in the Explorer
|
||||
#[cfg(not(target_arch = "wasm32"))]
|
||||
fn open_dependencies(app: &mut MaterialCraftApp) {
|
||||
let document = app.session.document_id;
|
||||
let paths: Vec<String> = app.session.pkg.dependencies.keys().filter(|path| is_package_file(path)).cloned().collect();
|
||||
for path in paths {
|
||||
crate::windows::open_path(app, &path);
|
||||
}
|
||||
activate(app, document);
|
||||
}
|
||||
|
||||
/// Native dependency-file actions are unavailable in the browser.
|
||||
#[cfg(target_arch = "wasm32")]
|
||||
fn open_dependencies(_: &mut MaterialCraftApp) {}
|
||||
|
||||
/// Apply a validated graph or folder rename through the engine.
|
||||
pub(super) fn rename_dialog(app: &mut MaterialCraftApp, ctx: &egui::Context) {
|
||||
let Some((target, mut name)) = app.ui.explorer.rename.clone() else { return };
|
||||
let mut open = true;
|
||||
|
||||
@@ -1,64 +1,86 @@
|
||||
use super::ExplorerTarget;
|
||||
use crate::{i18n::tr, menus};
|
||||
use super::{ExplorerTarget, explorer_menu_state::ExplorerMenuState};
|
||||
use crate::menus::{self, ExplorerRow};
|
||||
use crate::{i18n::tr, menus::shortcut_label};
|
||||
|
||||
pub(super) fn show(ui: &mut egui::Ui, target: &ExplorerTarget, paste: bool, reload: bool) -> Option<&'static str> {
|
||||
ui.set_min_width(190.0);
|
||||
/// Rows the browser can't offer: it has no folders to show or package files to open
|
||||
fn hidden(command: &str) -> bool {
|
||||
cfg!(target_arch = "wasm32") && matches!(command, menus::EXPLORER_SHOW_IN_FOLDER | menus::EXPLORER_OPEN_DEPENDENCIES)
|
||||
}
|
||||
|
||||
/// Draw one action with its shortcut and disabled-state explanation.
|
||||
fn item(ui: &mut egui::Ui, label: &str, command: &'static str, shortcut: Option<&str>, enabled: bool, action: &mut Option<&'static str>) {
|
||||
let mut button = egui::Button::new(tr(label));
|
||||
if let Some(shortcut) = shortcut {
|
||||
button = button.shortcut_text(shortcut_label(ui.ctx(), shortcut));
|
||||
}
|
||||
let response = ui.add_enabled(enabled, button);
|
||||
let response = if command.is_empty() { response.on_disabled_hover_text(tr("Not available yet")) } else { response };
|
||||
if response.clicked() {
|
||||
*action = Some(command);
|
||||
ui.close();
|
||||
}
|
||||
}
|
||||
|
||||
/// Draw menu rows while respecting resource-folder and platform restrictions.
|
||||
fn rows(ui: &mut egui::Ui, rows: &[ExplorerRow], state: &ExplorerMenuState, resources: bool, action: &mut Option<&'static str>) {
|
||||
for row in rows {
|
||||
match *row {
|
||||
ExplorerRow::Separator => {
|
||||
ui.separator();
|
||||
}
|
||||
ExplorerRow::Item(label, command, shortcut) if !hidden(command) => item(ui, label, command, shortcut, state.enabled(command), action),
|
||||
ExplorerRow::Item(..) => {}
|
||||
ExplorerRow::Sub(label, entries) => {
|
||||
let available = entries.iter().any(|(_, command)| !command.is_empty());
|
||||
ui.add_enabled_ui(available, |ui| {
|
||||
let submenu = ui.menu_button(tr(label), |ui| {
|
||||
for (entry, command) in entries {
|
||||
// Resource folders hold folders and resources, not graphs
|
||||
if resources && label == "New" && *command != "folder.create" {
|
||||
continue;
|
||||
}
|
||||
|
||||
item(ui, entry, command, None, state.enabled(command), action);
|
||||
}
|
||||
});
|
||||
submenu.response.on_disabled_hover_text(tr("Not available yet"));
|
||||
});
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Build the context menu for a package, folder, graph or resource.
|
||||
pub(super) fn show(ui: &mut egui::Ui, target: &ExplorerTarget, state: &ExplorerMenuState) -> Option<&'static str> {
|
||||
ui.set_min_width(220.0);
|
||||
let mut action = None;
|
||||
let resources = target.is_resources();
|
||||
if matches!(target, ExplorerTarget::Package { .. } | ExplorerTarget::Folder { .. }) {
|
||||
ui.menu_button(tr("New"), |ui| {
|
||||
for (label, command) in menus::EXPLORER_NEW {
|
||||
if resources && *command != "folder.create" {
|
||||
continue;
|
||||
}
|
||||
|
||||
if ui.button(tr(label)).clicked() {
|
||||
action = Some(*command);
|
||||
ui.close();
|
||||
}
|
||||
match target {
|
||||
ExplorerTarget::Package { .. } => rows(ui, menus::EXPLORER_PACKAGE, state, false, &mut action),
|
||||
ExplorerTarget::Folder { .. } if resources => {
|
||||
rows(ui, &[ExplorerRow::Sub("New", menus::EXPLORER_NEW), ExplorerRow::Sub("Import", menus::EXPLORER_IMPORT)], state, true, &mut action);
|
||||
if !target.is_resources_root() {
|
||||
ui.separator();
|
||||
rows(
|
||||
ui,
|
||||
&[ExplorerRow::Item("Rename", "folder.rename", Some("F2")), ExplorerRow::Item("Remove", "folder.remove", Some("Delete"))],
|
||||
state,
|
||||
true,
|
||||
&mut action,
|
||||
);
|
||||
}
|
||||
});
|
||||
if matches!(target, ExplorerTarget::Package { .. }) || resources {
|
||||
ui.menu_button(tr("Import"), |ui| {
|
||||
for (label, command) in menus::EXPLORER_IMPORT {
|
||||
if ui.button(tr(label)).clicked() {
|
||||
action = Some(*command);
|
||||
ui.close();
|
||||
}
|
||||
}
|
||||
});
|
||||
}
|
||||
ui.separator();
|
||||
}
|
||||
if resources {
|
||||
if !target.is_resources_root() {
|
||||
for (label, command) in [("Rename", "folder.rename"), ("Remove", "folder.remove")] {
|
||||
if ui.button(tr(label)).clicked() {
|
||||
action = Some(command);
|
||||
ui.close();
|
||||
}
|
||||
ExplorerTarget::Folder { .. } => {
|
||||
rows(ui, &[ExplorerRow::Sub("New", menus::EXPLORER_NEW), ExplorerRow::Separator], state, false, &mut action);
|
||||
rows(ui, menus::EXPLORER_FOLDER, state, false, &mut action);
|
||||
}
|
||||
ExplorerTarget::Graph { .. } => rows(ui, menus::EXPLORER_GRAPH, state, false, &mut action),
|
||||
ExplorerTarget::Resource { .. } => {
|
||||
for (label, command) in menus::EXPLORER_RESOURCE {
|
||||
item(ui, label, command, None, true, &mut action);
|
||||
}
|
||||
}
|
||||
return action;
|
||||
}
|
||||
|
||||
let entries = match target {
|
||||
ExplorerTarget::Package { .. } => menus::EXPLORER_PACKAGE,
|
||||
ExplorerTarget::Folder { .. } => menus::EXPLORER_FOLDER,
|
||||
ExplorerTarget::Graph { .. } => menus::EXPLORER_GRAPH,
|
||||
ExplorerTarget::Resource { .. } => menus::EXPLORER_RESOURCE,
|
||||
ExplorerTarget::Node { .. } => return None,
|
||||
};
|
||||
for (label, command) in entries {
|
||||
let enabled = match *command {
|
||||
"explorer.paste" => paste,
|
||||
"file.reload" => reload,
|
||||
_ => true,
|
||||
};
|
||||
if ui.add_enabled(enabled, egui::Button::new(tr(label))).clicked() {
|
||||
action = Some(*command);
|
||||
ui.close();
|
||||
}
|
||||
}
|
||||
action
|
||||
}
|
||||
@@ -0,0 +1,28 @@
|
||||
use crate::menus;
|
||||
|
||||
/// What the right-clicked item allows right now
|
||||
#[derive(Clone, Copy, Debug, Default)]
|
||||
pub(super) struct ExplorerMenuState {
|
||||
/// The Explorer clipboard holds something to paste
|
||||
pub paste: bool,
|
||||
/// The package has a file on disk (reload, show in folder)
|
||||
pub saved: bool,
|
||||
/// The package links other package files
|
||||
pub dependencies: bool,
|
||||
/// The graph (or, for a package, one of its graphs) has image outputs
|
||||
pub outputs: bool,
|
||||
}
|
||||
|
||||
impl ExplorerMenuState {
|
||||
/// Check the selected item supports this context-menu command.
|
||||
pub(super) fn enabled(&self, command: &str) -> bool {
|
||||
match command {
|
||||
"" => false,
|
||||
"explorer.paste" => self.paste,
|
||||
"file.reload" | menus::EXPLORER_SHOW_IN_FOLDER => self.saved,
|
||||
menus::EXPLORER_OPEN_DEPENDENCIES => self.dependencies,
|
||||
menus::EXPLORER_COMPUTE | menus::EXPLORER_VIEW_OUTPUTS | menus::EXPLORER_EXPORT_OUTPUTS => self.outputs,
|
||||
_ => true,
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,9 @@
|
||||
/// A row of an Explorer context menu
|
||||
#[derive(Clone, Copy, Debug, PartialEq)]
|
||||
pub(crate) enum ExplorerRow {
|
||||
/// A label, the action id (empty: not available yet) and the shortcut shown beside it
|
||||
Item(&'static str, &'static str, Option<&'static str>),
|
||||
/// A submenu of (label, action id); an empty id is not available yet
|
||||
Sub(&'static str, &'static [(&'static str, &'static str)]),
|
||||
Separator,
|
||||
}
|
||||
@@ -6,4 +6,7 @@ use serde::{Deserialize, Serialize};
|
||||
pub struct ExplorerState {
|
||||
pub selected: Option<ExplorerTarget>,
|
||||
pub rename: Option<(ExplorerTarget, String)>,
|
||||
/// The pointer was over the Explorer last frame, so Enter, F2 and Delete act on its selection
|
||||
#[serde(skip)]
|
||||
pub hovered: bool,
|
||||
}
|
||||
@@ -158,7 +158,14 @@ impl ExplorerTree<'_> {
|
||||
self.action = Some((target.clone(), "activate"));
|
||||
}
|
||||
response.context_menu(|ui| {
|
||||
if let Some(command) = context_menu::show(ui, target, self.session.explorer_clipboard.is_some(), reload) {
|
||||
let outputs = match target {
|
||||
ExplorerTarget::Graph { index, .. } => package.graphs.get(*index).is_some_and(|graph| graph.function.is_none()),
|
||||
_ => package.graphs.iter().any(|graph| graph.function.is_none()),
|
||||
};
|
||||
let dependencies = package.dependencies.keys().any(|path| super::actions::is_package_file(path));
|
||||
let state =
|
||||
super::explorer_menu_state::ExplorerMenuState { paste: self.session.explorer_clipboard.is_some(), saved: reload, dependencies, outputs };
|
||||
if let Some(command) = context_menu::show(ui, target, &state) {
|
||||
self.action = Some((target.clone(), command));
|
||||
}
|
||||
});
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
use super::{FunctionEditor, FunctionTarget};
|
||||
use super::FunctionEditor;
|
||||
use crate::MaterialCraftApp;
|
||||
|
||||
pub(super) fn editor_enabled(app: &MaterialCraftApp, editor: &FunctionEditor, command: &str) -> Option<bool> {
|
||||
@@ -12,8 +12,8 @@ pub(super) fn editor_enabled(app: &MaterialCraftApp, editor: &FunctionEditor, co
|
||||
if let Some(enabled) = crate::graph::wire_actions::enabled(app, command, &editor.selected_wires, target.as_ref()) {
|
||||
return Some(enabled && editor.current(app).is_some());
|
||||
}
|
||||
let standalone = matches!(editor.target, FunctionTarget::Graph);
|
||||
if standalone && app.session.annotation_selection.is_some() && matches!(command, "edit.delete" | "edit.deleteRelink") {
|
||||
|
||||
if app.session.annotation_selection.is_some() && matches!(command, "edit.delete" | "edit.deleteRelink") {
|
||||
return None;
|
||||
}
|
||||
if let Some(target) = editor.command_target()
|
||||
@@ -28,7 +28,7 @@ pub(super) fn editor_enabled(app: &MaterialCraftApp, editor: &FunctionEditor, co
|
||||
}
|
||||
match command {
|
||||
"edit.undo" | "edit.redo" | "edit.finish" | "graph.cook" | "ui.graph.snapToGrid" => None,
|
||||
"ui.graph.previousPin" | "ui.graph.nextPin" | "graph.comment.add" | "graph.frame.add" | "graph.pin.add" if standalone => None,
|
||||
"ui.graph.previousPin" | "ui.graph.nextPin" | "graph.comment.add" | "graph.frame.add" | "graph.pin.add" => None,
|
||||
command if command.starts_with("graph.") || command.starts_with("ui.graph.") || command.starts_with("edit.") => Some(false),
|
||||
_ => None,
|
||||
}
|
||||
|
||||
@@ -11,9 +11,10 @@ pub(super) fn canvas(app: &mut MaterialCraftApp, editor: &mut FunctionEditor, ui
|
||||
app.ui.frame_all = false;
|
||||
if standalone {
|
||||
app.ui.graph_camera = frame.camera.state();
|
||||
app.graph.frames = frame.frames.iter().map(|frame| (frame.id, frame.rect)).collect();
|
||||
app.graph.comments = frame.comments.clone();
|
||||
}
|
||||
app.graph.frames = frame.frames.iter().map(|frame| (frame.id, frame.rect)).collect();
|
||||
app.graph.comments = frame.comments.clone();
|
||||
app.graph.pins = frame.pins.clone();
|
||||
if frame.clear_annotation {
|
||||
app.run("graph.annotation.select", json!({}));
|
||||
}
|
||||
@@ -30,25 +31,26 @@ pub(super) fn canvas(app: &mut MaterialCraftApp, editor: &mut FunctionEditor, ui
|
||||
super::context_menu::show(app, editor, ui, Some(*id));
|
||||
});
|
||||
}
|
||||
let on_annotation = ui
|
||||
.input(|input| input.pointer.hover_pos())
|
||||
.is_some_and(|pointer| frame.frames.iter().any(|frame| frame.contains(pointer)) || frame.comments.iter().any(|(_, rect)| rect.contains(pointer)));
|
||||
let on_annotation = ui.input(|input| input.pointer.hover_pos()).is_some_and(|pointer| {
|
||||
frame.frames.iter().any(|frame| frame.contains(pointer))
|
||||
|| frame.comments.iter().any(|(_, rect)| rect.contains(pointer))
|
||||
|| frame.pins.iter().any(|(_, rect)| rect.contains(pointer))
|
||||
});
|
||||
super::input::handle(app, editor, ui, &frame.response, &frame.ports, &frame.geometry, on_annotation);
|
||||
let camera = GraphCamera { origin: frame.response.rect.min, pan: editor.pan, zoom: editor.zoom };
|
||||
super::search::show(app, editor, ui, &camera);
|
||||
frame.geometry.publish(&mut app.graph, frame.response.rect);
|
||||
if standalone {
|
||||
if editor.drag.is_none() {
|
||||
let camera = GraphCamera { origin: frame.response.rect.min, pan: editor.pan, zoom: editor.zoom };
|
||||
crate::graph::annotation_input::handle(app, ui, &camera, &frame.frames, &frame.comments);
|
||||
if app.session.annotation_selection.is_some() {
|
||||
editor.selection.clear();
|
||||
editor.selected_wires.clear();
|
||||
}
|
||||
if editor.drag.is_none() {
|
||||
let camera = GraphCamera { origin: frame.response.rect.min, pan: editor.pan, zoom: editor.zoom };
|
||||
crate::graph::annotation_input::handle(app, ui, &camera, &frame.frames, &frame.comments, &frame.pins);
|
||||
if app.session.annotation_selection.is_some() {
|
||||
editor.selection.clear();
|
||||
editor.selected_wires.clear();
|
||||
}
|
||||
app.ui.graph_camera = crate::state::GraphCamera { pan: editor.pan.into(), zoom: editor.zoom };
|
||||
}
|
||||
if standalone {
|
||||
app.ui.graph_camera = editor.camera();
|
||||
app.session.selection = editor.selection.iter().map(|id| materialcraft_engine::core::NodeId(u64::from(*id))).collect();
|
||||
} else {
|
||||
app.graph.frames.clear();
|
||||
app.graph.comments.clear();
|
||||
}
|
||||
editor.inspected_node = crate::graph::node_selection::inspected(&editor.selection, editor.inspected_node);
|
||||
}
|
||||
@@ -1,4 +1,4 @@
|
||||
use super::{FunctionEditor, FunctionTarget};
|
||||
use super::FunctionEditor;
|
||||
use crate::{MaterialCraftApp, graph::edit_menu, i18n::tr, menus};
|
||||
use egui::Ui;
|
||||
use materialcraft_engine::FunctionEdit;
|
||||
@@ -54,14 +54,13 @@ fn background_actions(app: &mut MaterialCraftApp, editor: &mut FunctionEditor, u
|
||||
let Some(target) = editor.command_target() else { return };
|
||||
|
||||
let mut add = None;
|
||||
let standalone = matches!(editor.target, FunctionTarget::Graph);
|
||||
ui.menu_button(tr("Add node"), |ui| {
|
||||
let entries =
|
||||
target.available_operations(&app.session).filter(|operation| operation.id != "passthrough").map(|operation| (operation.id, operation.label, ""));
|
||||
add = crate::graph::add_node_menu::show(app, ui, entries);
|
||||
});
|
||||
annotations(app, editor, ui);
|
||||
if edit_menu::button(ui, "Add Navigation pin", "graph.pin.add", standalone) {
|
||||
if edit_menu::button(ui, "Add Navigation pin", "graph.pin.add", true) {
|
||||
app.run("graph.pin.add", json!({"at": [editor.menu_at.x, editor.menu_at.y]}));
|
||||
editor.selection.clear();
|
||||
}
|
||||
@@ -77,7 +76,7 @@ fn background_actions(app: &mut MaterialCraftApp, editor: &mut FunctionEditor, u
|
||||
selection_action(app, editor, ui, label, command);
|
||||
}
|
||||
for (label, command) in [("Previous pin", "ui.graph.previousPin"), ("Next pin", "ui.graph.nextPin")] {
|
||||
if edit_menu::button(ui, label, command, standalone && menus::enabled(app, command)) {
|
||||
if edit_menu::button(ui, label, command, menus::enabled(app, command)) {
|
||||
crate::graph::actions::invoke(app, command);
|
||||
editor.set_camera(app.ui.graph_camera);
|
||||
}
|
||||
@@ -89,12 +88,11 @@ fn background_actions(app: &mut MaterialCraftApp, editor: &mut FunctionEditor, u
|
||||
}
|
||||
|
||||
fn annotations(app: &mut MaterialCraftApp, editor: &mut FunctionEditor, ui: &mut Ui) {
|
||||
let standalone = matches!(editor.target, FunctionTarget::Graph);
|
||||
for (label, command, parameters) in [
|
||||
("Add Comment", "graph.comment.add", json!({"at": [editor.menu_at.x, editor.menu_at.y]})),
|
||||
("Add Frame", "graph.frame.add", json!({"rect": [editor.menu_at.x, editor.menu_at.y, 400, 260]})),
|
||||
] {
|
||||
if edit_menu::button(ui, label, command, standalone) {
|
||||
if edit_menu::button(ui, label, command, true) {
|
||||
app.run(command, parameters);
|
||||
editor.selection.clear();
|
||||
}
|
||||
|
||||
@@ -12,5 +12,6 @@ pub(super) struct FunctionCanvas {
|
||||
pub values: Vec<(u32, Value)>,
|
||||
pub frames: Vec<FrameHit>,
|
||||
pub comments: Vec<(u64, Rect)>,
|
||||
pub pins: Vec<(u64, Rect)>,
|
||||
pub clear_annotation: bool,
|
||||
}
|
||||
@@ -19,6 +19,8 @@ pub struct FunctionEditor {
|
||||
pub(super) menu_at: Pos2,
|
||||
pub(crate) framed: bool,
|
||||
pub(super) open_reference: Option<u32>,
|
||||
/// The open node search (Space, Tab, double-click or a wire dropped on empty canvas)
|
||||
pub(crate) search: Option<super::search::FunctionSearch>,
|
||||
}
|
||||
|
||||
impl FunctionEditor {
|
||||
@@ -26,6 +28,10 @@ impl FunctionEditor {
|
||||
Self::with_target(graph, None, FunctionTarget::Graph)
|
||||
}
|
||||
|
||||
pub(crate) fn camera(&self) -> crate::state::GraphCamera {
|
||||
crate::state::GraphCamera { pan: self.pan.into(), zoom: self.zoom }
|
||||
}
|
||||
|
||||
pub(crate) fn set_camera(&mut self, camera: crate::state::GraphCamera) {
|
||||
self.pan = camera.pan.into();
|
||||
self.zoom = camera.zoom;
|
||||
@@ -49,6 +55,7 @@ impl FunctionEditor {
|
||||
menu_at: Pos2::ZERO,
|
||||
framed: false,
|
||||
open_reference: None,
|
||||
search: None,
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -1,4 +1,6 @@
|
||||
pub(super) enum FunctionLibraryDrag {
|
||||
/// A library function being dragged onto a Function canvas
|
||||
#[derive(Clone, Debug)]
|
||||
pub(crate) enum FunctionLibraryDrag {
|
||||
Operation(String),
|
||||
Instance { package: String, graph: String },
|
||||
}
|
||||
@@ -0,0 +1,18 @@
|
||||
use super::search_wire::SearchWire;
|
||||
use egui::Pos2;
|
||||
|
||||
#[derive(Clone, Debug)]
|
||||
pub(crate) struct FunctionSearch {
|
||||
/// Where the new node goes, in canvas coordinates
|
||||
pub(crate) at: Pos2,
|
||||
pub(crate) text: String,
|
||||
pub(crate) selected_index: usize,
|
||||
pub(crate) wire: Option<SearchWire>,
|
||||
pub(crate) focus: bool,
|
||||
}
|
||||
|
||||
impl FunctionSearch {
|
||||
pub(crate) fn at(at: Pos2, wire: Option<SearchWire>) -> Self {
|
||||
Self { at, text: String::new(), selected_index: 0, wire, focus: true }
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,9 @@
|
||||
use super::function_library_drag::FunctionLibraryDrag;
|
||||
|
||||
/// One search result: its label, what it is (shown dimmed on the right) and what adding it does
|
||||
#[derive(Clone, Debug)]
|
||||
pub(crate) struct FunctionSearchCandidate {
|
||||
pub(crate) label: String,
|
||||
pub(crate) group: String,
|
||||
pub(crate) entry: FunctionLibraryDrag,
|
||||
}
|
||||
@@ -1,4 +1,4 @@
|
||||
use super::{FunctionDrag, FunctionEditor, FunctionTarget};
|
||||
use super::{FunctionDrag, FunctionEditor};
|
||||
use crate::{MaterialCraftApp, graph::node_card};
|
||||
use egui::{Color32, Pos2, Rect, vec2};
|
||||
use materialcraft_engine::core::FunctionNode;
|
||||
@@ -39,8 +39,6 @@ pub(super) fn preview_rect(app: &MaterialCraftApp, editor: &FunctionEditor, node
|
||||
let position = materialcraft_engine::graph_grid::translate(node.pos, (*delta).into(), snap);
|
||||
bounds = bounds.translate(vec2(position[0] - node.pos[0], position[1] - node.pos[1]));
|
||||
}
|
||||
if matches!(editor.target, FunctionTarget::Graph) {
|
||||
bounds = bounds.translate(crate::graph::annotation_canvas::offset(app, |contents| contents.function_nodes.contains(&node.id)));
|
||||
}
|
||||
bounds = bounds.translate(crate::graph::annotation_canvas::offset(app, |contents| contents.function_nodes.contains(&node.id)));
|
||||
bounds
|
||||
}
|
||||
@@ -1,4 +1,5 @@
|
||||
use super::function_port::FunctionPort;
|
||||
use super::search::{FunctionSearch, SearchWire};
|
||||
use super::{FunctionDrag, FunctionEditor};
|
||||
use crate::{
|
||||
MaterialCraftApp,
|
||||
@@ -26,15 +27,12 @@ pub(super) fn handle(
|
||||
editor.drag = None;
|
||||
return;
|
||||
}
|
||||
|
||||
let on_wire = editor.drag.is_none()
|
||||
&& !on_annotation
|
||||
&& !ui.input(|input| input.modifiers.alt)
|
||||
&& crate::graph::wire_selection::handle(&mut editor.selected_wires, &mut editor.selection, ui, response, &geometry.wires);
|
||||
if on_wire
|
||||
&& matches!(editor.target, super::FunctionTarget::Graph)
|
||||
&& app.session.annotation_selection.is_some()
|
||||
&& (ui.input(|input| input.pointer.primary_pressed()) || response.secondary_clicked())
|
||||
{
|
||||
if on_wire && app.session.annotation_selection.is_some() && (ui.input(|input| input.pointer.primary_pressed()) || response.secondary_clicked()) {
|
||||
app.run("graph.annotation.select", serde_json::json!({}));
|
||||
}
|
||||
|
||||
@@ -68,7 +66,7 @@ pub(super) fn handle(
|
||||
&& !on_annotation
|
||||
&& !on_wire
|
||||
{
|
||||
if matches!(editor.target, super::FunctionTarget::Graph) && app.session.annotation_selection.is_some() {
|
||||
if app.session.annotation_selection.is_some() {
|
||||
app.run("graph.annotation.select", serde_json::json!({}));
|
||||
}
|
||||
editor.drag = Some(FunctionDrag::Box { start });
|
||||
@@ -97,6 +95,7 @@ pub(super) fn handle(
|
||||
None => {}
|
||||
}
|
||||
|
||||
let camera = GraphCamera { origin: canvas_bounds.min, pan: editor.pan, zoom: editor.zoom };
|
||||
let owner = match editor.drag {
|
||||
Some(FunctionDrag::Pan(button)) => button,
|
||||
_ => egui::PointerButton::Primary,
|
||||
@@ -118,23 +117,22 @@ pub(super) fn handle(
|
||||
crate::graph::node_selection::select_box(&mut editor.selection, nodes, start, pointer, ui.input(|input| input.modifiers));
|
||||
}
|
||||
}
|
||||
Some(FunctionDrag::Wire(from)) => {
|
||||
if let Some(pointer) = pointer
|
||||
&& let Some((to, Some(input))) = near(pointer)
|
||||
&& from != to
|
||||
{
|
||||
editor.edit(app, FunctionEdit::Connect { from, to, input }, false);
|
||||
Some(FunctionDrag::Wire(from)) => match pointer.map(|pointer| (pointer, near(pointer))) {
|
||||
Some((_, Some((to, Some(input))))) if from != to => editor.edit(app, FunctionEdit::Connect { from, to, input }, false),
|
||||
// Dropped on empty canvas: search for a node that takes the wire
|
||||
Some((pointer, None)) if canvas_bounds.contains(pointer) => {
|
||||
editor.search = Some(FunctionSearch::at(camera.to_graph(pointer), Some(SearchWire::From(from))));
|
||||
}
|
||||
}
|
||||
Some(FunctionDrag::InputWire(to, input)) => {
|
||||
// Dropped anywhere but on another node's output, the input stays unconnected
|
||||
if let Some(pointer) = pointer
|
||||
&& let Some((from, None)) = near(pointer)
|
||||
&& from != to
|
||||
{
|
||||
editor.edit(app, FunctionEdit::Connect { from, to, input }, false);
|
||||
_ => {}
|
||||
},
|
||||
Some(FunctionDrag::InputWire(to, input)) => match pointer.map(|pointer| (pointer, near(pointer))) {
|
||||
Some((_, Some((from, None)))) if from != to => editor.edit(app, FunctionEdit::Connect { from, to, input }, false),
|
||||
// Dropped on empty canvas: search for a node whose output feeds the input
|
||||
Some((pointer, None)) if canvas_bounds.contains(pointer) => {
|
||||
editor.search = Some(FunctionSearch::at(camera.to_graph(pointer), Some(SearchWire::To(to, input))));
|
||||
}
|
||||
}
|
||||
_ => {}
|
||||
},
|
||||
_ => {}
|
||||
}
|
||||
}
|
||||
@@ -144,8 +142,6 @@ pub(super) fn handle(
|
||||
crate::graph::node_selection::select(&mut editor.selected_wires, None, ui.input(|input| input.modifiers));
|
||||
}
|
||||
|
||||
let camera = GraphCamera { origin: canvas_bounds.min, pan: editor.pan, zoom: editor.zoom };
|
||||
|
||||
if let Some(payload) = crate::widgets::dnd_release::<super::function_library_drag::FunctionLibraryDrag>(response)
|
||||
&& let Some(pointer) = pointer
|
||||
{
|
||||
@@ -170,20 +166,40 @@ pub(super) fn handle(
|
||||
}
|
||||
}
|
||||
|
||||
if let Some(payload) = crate::widgets::dnd_release::<crate::graph::LibraryDrag>(response)
|
||||
&& let Some(pointer) = pointer
|
||||
{
|
||||
let at = camera.to_graph(pointer);
|
||||
if let Some(result) = app.run("library.add", serde_json::json!({"entry": payload.0, "at": [at.x, at.y], "snapToGrid": snap})) {
|
||||
editor.selection = if app.session.annotation_selection.is_some() {
|
||||
Vec::new()
|
||||
} else {
|
||||
result["result"]["id"].as_u64().and_then(|id| u32::try_from(id).ok()).into_iter().collect()
|
||||
};
|
||||
editor.selected_wires.clear();
|
||||
}
|
||||
}
|
||||
|
||||
// Adding operations
|
||||
if response.secondary_clicked()
|
||||
&& let Some(pointer_position) = pointer
|
||||
{
|
||||
editor.menu_at = camera.to_graph(pointer_position);
|
||||
}
|
||||
if response.hovered()
|
||||
&& !ui.ctx().egui_wants_keyboard_input()
|
||||
&& ui.input(|input| input.key_pressed(egui::Key::Space))
|
||||
// Space or Tab over the canvas, or a double-click on empty canvas, searches for a node to add
|
||||
// Tab moves focus between widgets, so it waits only for text fields and focus held before this frame
|
||||
let space = !ui.ctx().egui_wants_keyboard_input() && ui.input(|input| input.key_pressed(egui::Key::Space));
|
||||
let tab = !app.graph.keyboard_was_focused && !ui.ctx().text_edit_focused() && ui.input(|input| input.key_pressed(egui::Key::Tab));
|
||||
let keys = space || tab;
|
||||
let on_node = pointer.is_some_and(|pointer| geometry.rects.iter().any(|(_, bounds)| bounds.contains(pointer)));
|
||||
let double_click = response.double_clicked() && !on_wire && !on_annotation && !on_node && pointer.and_then(near).is_none();
|
||||
if editor.search.is_none()
|
||||
&& ((response.hovered() && keys) || double_click)
|
||||
&& !crate::shell::modality::Modality::capture(app, ui.ctx()).is_blocked()
|
||||
&& let Some(pointer_position) = pointer
|
||||
{
|
||||
editor.menu_at = camera.to_graph(pointer_position);
|
||||
egui::Popup::open_id(ui.ctx(), response.id.with("menu"));
|
||||
editor.search = Some(FunctionSearch::at(editor.menu_at, None));
|
||||
}
|
||||
response.context_menu(|ui| {
|
||||
super::context_menu::show(app, editor, ui, None);
|
||||
|
||||
@@ -1,78 +1,73 @@
|
||||
use super::function_library_drag::FunctionLibraryDrag;
|
||||
use crate::{MaterialCraftApp, i18n::tr};
|
||||
use egui::{Sense, Ui};
|
||||
pub(crate) use super::function_library_drag::FunctionLibraryDrag;
|
||||
use crate::MaterialCraftApp;
|
||||
use materialcraft_engine::FunctionEdit;
|
||||
|
||||
pub(crate) fn show(app: &mut MaterialCraftApp, ui: &mut Ui) {
|
||||
let Some(target) = app.function_editor.as_ref().and_then(|editor| editor.command_target()) else { return };
|
||||
|
||||
let operations = target.available_operations(&app.session);
|
||||
ui.add(egui::TextEdit::singleline(&mut app.ui.library_search).hint_text(tr("Search functions")));
|
||||
let search = app.ui.library_search.to_ascii_lowercase();
|
||||
let functions: Vec<_> = app
|
||||
.session
|
||||
.pkg
|
||||
.dependencies
|
||||
.iter()
|
||||
.filter(|(path, _)| path.starts_with("sbs://"))
|
||||
.flat_map(|(path, package)| {
|
||||
package.graphs.iter().filter(|graph| graph.function.is_some()).map(move |graph| {
|
||||
(
|
||||
path.clone(),
|
||||
graph.sbs_path(),
|
||||
graph.display_name().to_string(),
|
||||
graph.attributes.description.clone(),
|
||||
graph.function.as_ref().is_some_and(|function| function.output.is_none() || function.nodes.iter().any(|node| node.missing.is_some())),
|
||||
)
|
||||
})
|
||||
})
|
||||
.filter(|(_, path, label, _, _)| path.to_ascii_lowercase().contains(&search) || label.to_ascii_lowercase().contains(&search))
|
||||
.collect();
|
||||
let mut add = None;
|
||||
egui::ScrollArea::vertical().show(ui, |ui| {
|
||||
ui.strong(tr("SBS functions"));
|
||||
if !app.session.pkg.dependencies.keys().any(|path| path.starts_with("sbs://")) {
|
||||
ui.colored_label(egui::Color32::from_rgb(255, 90, 180), tr("Missing SBS function library"));
|
||||
}
|
||||
|
||||
for (package, graph, label, description, missing) in functions {
|
||||
let text = if missing {
|
||||
egui::RichText::new(format!("{}: {label}", tr("Missing"))).color(egui::Color32::from_rgb(255, 90, 180))
|
||||
} else {
|
||||
egui::RichText::new(&label)
|
||||
};
|
||||
let response = ui.add(egui::Label::new(text).selectable(false).sense(Sense::click_and_drag()));
|
||||
crate::widgets::name(&response, egui::Role::ListItem, &label);
|
||||
if response.drag_started() {
|
||||
egui::DragAndDrop::set_payload(ui.ctx(), FunctionLibraryDrag::Instance { package: package.clone(), graph: graph.clone() });
|
||||
}
|
||||
if response.double_clicked() {
|
||||
add = Some(FunctionLibraryDrag::Instance { package: package.clone(), graph: graph.clone() });
|
||||
}
|
||||
response.on_hover_text(format!("{description}\n{package}/{graph}"));
|
||||
}
|
||||
ui.separator();
|
||||
ui.strong(tr("Native operations"));
|
||||
for definition in operations.filter(|definition| definition.label.to_ascii_lowercase().contains(&search)) {
|
||||
let response = ui.add(egui::Label::new(tr(definition.label)).selectable(false).sense(Sense::click_and_drag()));
|
||||
crate::widgets::name(&response, egui::Role::ListItem, definition.label);
|
||||
if response.drag_started() {
|
||||
egui::DragAndDrop::set_payload(ui.ctx(), FunctionLibraryDrag::Operation(definition.id.into()));
|
||||
}
|
||||
if response.double_clicked() {
|
||||
add = Some(FunctionLibraryDrag::Operation(definition.id.into()));
|
||||
}
|
||||
}
|
||||
});
|
||||
if let Some(add) = add
|
||||
&& let Some(mut editor) = app.function_editor.take()
|
||||
{
|
||||
/// Add `entry` to the open Function canvas, after its last node
|
||||
pub(crate) fn add(app: &mut MaterialCraftApp, entry: &FunctionLibraryDrag) {
|
||||
if let Some(mut editor) = app.function_editor.take() {
|
||||
let at = editor.current(app).map_or([0.0; 2], |graph| [graph.nodes.len() as f32 * 140.0, 0.0]);
|
||||
insert(app, &mut editor, &add, at);
|
||||
insert(app, &mut editor, entry, at);
|
||||
app.function_editor = Some(editor);
|
||||
}
|
||||
}
|
||||
|
||||
/// The common function nodes on the canvas toolbar, in groups: (operation, what the button shows).
|
||||
/// Icons where one fits, short text where the node is a value or an operator
|
||||
pub(crate) const QUICK: &[&[(&str, &str)]] = &[
|
||||
&[("const_float1", "F1"), ("const_float2", "F2"), ("const_float3", "F3"), ("const_float4", "F4"), ("const_int1", "I1"), ("const_bool", "B")],
|
||||
&[("get_float1", "$1"), ("get_float2", "$2"), ("get_float3", "$3"), ("get_float4", "$4")],
|
||||
&[("vector2", "V2"), ("vector3", "V3"), ("vector4", "V4"), ("swizzle1", egui_phosphor::regular::SHUFFLE)],
|
||||
&[("add", "+"), ("sub", "\u{2212}"), ("mul", "\u{d7}"), ("div", "\u{f7}"), ("mulscalar", "k\u{d7}"), ("dot", "\u{b7}")],
|
||||
&[
|
||||
("lerp", egui_phosphor::regular::SLIDERS_HORIZONTAL),
|
||||
("min", egui_phosphor::regular::ARROW_LINE_DOWN),
|
||||
("max", egui_phosphor::regular::ARROW_LINE_UP),
|
||||
("abs", "|x|"),
|
||||
],
|
||||
&[("ifelse", egui_phosphor::regular::GIT_BRANCH), ("sequence", egui_phosphor::regular::LIST_NUMBERS)],
|
||||
&[
|
||||
("samplecol", egui_phosphor::regular::EYEDROPPER_SAMPLE),
|
||||
("samplelum", egui_phosphor::regular::EYEDROPPER),
|
||||
("passthrough", egui_phosphor::regular::DOT_OUTLINE),
|
||||
],
|
||||
];
|
||||
|
||||
/// Add `operation` right of the one selected node, wired from it when the new node has an input;
|
||||
/// in the middle of the view otherwise
|
||||
pub(crate) fn add_near_selection(app: &mut MaterialCraftApp, operation: &str) {
|
||||
let Some(mut editor) = app.function_editor.take() else { return };
|
||||
let source = match editor.selection.as_slice() {
|
||||
[id] => editor.current(app).and_then(|graph| graph.node(*id)).map(|node| (node.id, node.pos)),
|
||||
_ => None,
|
||||
};
|
||||
let at = source.map_or_else(
|
||||
|| {
|
||||
let center = editor.pan + app.graph.view.size() * 0.5 / editor.zoom;
|
||||
[center.x - crate::graph::NODE_W * 0.5, center.y - 40.0]
|
||||
},
|
||||
|(_, position)| [position[0] + 180.0, position[1]],
|
||||
);
|
||||
let before = editor.selection.clone();
|
||||
editor.edit(app, FunctionEdit::Add { operation: operation.into(), at, snap: app.ui.prefs.snap_to_grid }, false);
|
||||
if let Some((from, _)) = source
|
||||
&& let Some(&id) = editor.selection.first().filter(|_| editor.selection != before)
|
||||
&& editor.current(app).and_then(|graph| graph.node(id)).is_some_and(|node| !node.inputs.is_empty())
|
||||
{
|
||||
editor.edit(app, FunctionEdit::Connect { from, to: id, input: 0 }, false);
|
||||
editor.selection = vec![id];
|
||||
}
|
||||
app.function_editor = Some(editor);
|
||||
}
|
||||
|
||||
/// The native operations accepted by the open Function canvas.
|
||||
pub(crate) fn available_operations(app: &MaterialCraftApp) -> Vec<&'static str> {
|
||||
app.function_editor
|
||||
.as_ref()
|
||||
.and_then(|editor| editor.command_target())
|
||||
.map(|target| target.available_operations(&app.session).map(|definition| definition.id).collect())
|
||||
.unwrap_or_default()
|
||||
}
|
||||
|
||||
pub(super) fn insert(app: &mut MaterialCraftApp, editor: &mut super::FunctionEditor, entry: &FunctionLibraryDrag, at: [f32; 2]) {
|
||||
match entry {
|
||||
FunctionLibraryDrag::Operation(operation) => {
|
||||
|
||||
@@ -3,10 +3,14 @@ mod context_menu;
|
||||
mod function_drag;
|
||||
mod function_editor;
|
||||
mod function_library_drag;
|
||||
mod function_search;
|
||||
mod function_search_candidate;
|
||||
mod function_target;
|
||||
pub(crate) mod library;
|
||||
mod port_label;
|
||||
pub(crate) mod properties;
|
||||
pub(crate) mod search;
|
||||
mod search_wire;
|
||||
|
||||
pub(crate) use actions::{enabled, invoke};
|
||||
use function_drag::FunctionDrag;
|
||||
|
||||
@@ -1,12 +1,14 @@
|
||||
use super::geometry::{in_port, node_rect, out_port, preview_rect};
|
||||
use super::{FunctionDrag, FunctionEditor, FunctionTarget, port_label::port_label};
|
||||
use super::{FunctionDrag, FunctionEditor, port_label::port_label};
|
||||
use super::{function_canvas::FunctionCanvas, function_port::FunctionPort};
|
||||
use crate::graph::canvas_geometry::CanvasGeometry;
|
||||
use crate::{MaterialCraftApp, graph::node_card, theme::Tokens};
|
||||
use egui::{Align2, Color32, Rect, Sense, Stroke, Ui, Vec2, pos2, vec2};
|
||||
use std::collections::{BTreeMap, BTreeSet};
|
||||
|
||||
pub(super) fn paint(app: &MaterialCraftApp, editor: &mut FunctionEditor, ui: &mut Ui) -> Option<FunctionCanvas> {
|
||||
pub(super) fn paint(app: &mut MaterialCraftApp, editor: &mut FunctionEditor, ui: &mut Ui) -> Option<FunctionCanvas> {
|
||||
let (canvas_bounds, response) = ui.allocate_exact_size(ui.available_size().max(vec2(200.0, 200.0)), Sense::click_and_drag());
|
||||
app.graph.view = canvas_bounds;
|
||||
let graph = editor.current(app)?;
|
||||
let snap = app.ui.prefs.snap_to_grid;
|
||||
let selected: BTreeSet<_> = editor.selection.iter().copied().collect();
|
||||
@@ -21,9 +23,8 @@ pub(super) fn paint(app: &MaterialCraftApp, editor: &mut FunctionEditor, ui: &mu
|
||||
.is_some_and(Option::is_some)
|
||||
});
|
||||
editor.inspected_node = crate::graph::node_selection::inspected(&editor.selection, editor.inspected_node);
|
||||
let standalone = matches!(editor.target, FunctionTarget::Graph);
|
||||
let document = app.graph.annotation_target.items(&app.session).ok();
|
||||
let tokens = Tokens::get(ui.ctx());
|
||||
let (canvas_bounds, response) = ui.allocate_exact_size(ui.available_size().max(vec2(200.0, 200.0)), Sense::click_and_drag());
|
||||
crate::widgets::name(&response, egui::Role::Canvas, "Function Graph");
|
||||
let painter = ui.painter_at(canvas_bounds);
|
||||
painter.rect_filled(canvas_bounds, 4.0, Color32::from_rgb(0x26, 0x28, 0x2c));
|
||||
@@ -42,10 +43,7 @@ pub(super) fn paint(app: &MaterialCraftApp, editor: &mut FunctionEditor, ui: &mu
|
||||
.filter(|node| !selected_only || selected.contains(&node.id))
|
||||
.map(|node| node_rect(node, app.ui.prefs.thumbnails))
|
||||
.fold(Rect::NOTHING, |combined, bounds| combined.union(bounds));
|
||||
if standalone
|
||||
&& !selected_only
|
||||
&& let Ok(document) = app.session.graph()
|
||||
{
|
||||
if !selected_only && let Some(document) = &document {
|
||||
for frame in &document.frames {
|
||||
destination = destination.union(Rect::from_min_size(pos2(frame.rect[0], frame.rect[1] - 32.0), vec2(frame.rect[2], frame.rect[3] + 32.0)));
|
||||
}
|
||||
@@ -59,7 +57,7 @@ pub(super) fn paint(app: &MaterialCraftApp, editor: &mut FunctionEditor, ui: &mu
|
||||
camera.zoom_from_input(ui, canvas_bounds);
|
||||
editor.pan = camera.pan;
|
||||
editor.zoom = camera.zoom;
|
||||
let document = standalone.then(|| app.session.graph().ok()).flatten();
|
||||
|
||||
let frame_hits = document.as_ref().map(|graph| crate::graph::annotation_canvas::frames(app, ui, &graph.frames, &camera)).unwrap_or_default();
|
||||
crate::graph::grid::paint(&painter, &camera, canvas_bounds);
|
||||
|
||||
@@ -167,7 +165,7 @@ pub(super) fn paint(app: &MaterialCraftApp, editor: &mut FunctionEditor, ui: &mu
|
||||
if !keep_wires {
|
||||
editor.selected_wires.clear();
|
||||
}
|
||||
if standalone && app.session.annotation_selection.is_some() {
|
||||
if app.session.annotation_selection.is_some() {
|
||||
clear_annotation = true;
|
||||
}
|
||||
}
|
||||
@@ -193,8 +191,6 @@ pub(super) fn paint(app: &MaterialCraftApp, editor: &mut FunctionEditor, ui: &mu
|
||||
.collect();
|
||||
|
||||
let comments = document.as_ref().map(|document| crate::graph::annotation_canvas::comments(app, ui, &document.comments, &camera)).unwrap_or_default();
|
||||
if let Some(document) = &document {
|
||||
crate::graph::annotation_canvas::pins(app, ui, &document.pins, &camera);
|
||||
}
|
||||
Some(FunctionCanvas { response, camera, geometry, ports, nodes, values, frames: frame_hits, comments, clear_annotation })
|
||||
let pins = document.as_ref().map(|document| crate::graph::annotation_canvas::pins(app, ui, &document.pins, &camera)).unwrap_or_default();
|
||||
Some(FunctionCanvas { response, camera, geometry, ports, nodes, values, frames: frame_hits, comments, pins, clear_annotation })
|
||||
}
|
||||
@@ -0,0 +1,160 @@
|
||||
//! The node search of Function canvases (Space, Tab, a double-click, or a wire dropped on empty
|
||||
//! canvas): the operations the canvas takes, then the library's functions. A search opened from a
|
||||
//! wire connects the new node to it.
|
||||
|
||||
use super::library::FunctionLibraryDrag;
|
||||
use super::{FunctionEditor, function_search_candidate::FunctionSearchCandidate};
|
||||
pub(crate) use super::{function_search::FunctionSearch, search_wire::SearchWire};
|
||||
use crate::{MaterialCraftApp, graph::GraphCamera, i18n::tr, theme::Tokens};
|
||||
use egui::Ui;
|
||||
use egui_phosphor::regular as icon;
|
||||
use materialcraft_engine::{FunctionEdit, LibraryItem};
|
||||
use std::collections::BTreeSet;
|
||||
|
||||
/// Every operation the canvas takes, then the library's functions, matching all words of `text`
|
||||
/// (label, id or group), names that start with the first word first
|
||||
pub(crate) fn candidates(app: &MaterialCraftApp, editor: &FunctionEditor, text: &str) -> Vec<FunctionSearchCandidate> {
|
||||
let Some(target) = editor.command_target() else { return Vec::new() };
|
||||
let mut all: Vec<(String, FunctionSearchCandidate)> = target
|
||||
.available_operations(&app.session)
|
||||
.map(|operation| {
|
||||
let candidate = FunctionSearchCandidate {
|
||||
label: tr(operation.label).to_string(),
|
||||
group: tr(operation.category).to_string(),
|
||||
entry: FunctionLibraryDrag::Operation(operation.id.into()),
|
||||
};
|
||||
(operation.id.to_string(), candidate)
|
||||
})
|
||||
.collect();
|
||||
for entry in app.session.library_entries() {
|
||||
if let LibraryItem::FunctionInstance { package, graph } = &entry.item
|
||||
&& entry.missing.is_none()
|
||||
{
|
||||
let group = entry.category.rsplit('/').next().unwrap_or(&entry.category).to_string();
|
||||
let candidate = FunctionSearchCandidate {
|
||||
label: entry.label.clone(),
|
||||
group,
|
||||
entry: FunctionLibraryDrag::Instance { package: package.clone(), graph: graph.clone() },
|
||||
};
|
||||
all.push((entry.id, candidate));
|
||||
}
|
||||
}
|
||||
let words: Vec<String> = text.split_whitespace().map(str::to_lowercase).collect();
|
||||
let mut seen = BTreeSet::new();
|
||||
let mut found: Vec<FunctionSearchCandidate> = all
|
||||
.into_iter()
|
||||
.filter(|(id, candidate)| {
|
||||
let haystack = format!("{} {} {}", candidate.label.to_lowercase(), id.to_lowercase(), candidate.group.to_lowercase());
|
||||
words.iter().all(|word| haystack.contains(word.as_str()))
|
||||
})
|
||||
// Placement ids differ across categories; deduplicate the underlying function after matching
|
||||
.filter(|(_, candidate)| {
|
||||
let source = match &candidate.entry {
|
||||
FunctionLibraryDrag::Operation(operation) => (operation.clone(), String::new()),
|
||||
FunctionLibraryDrag::Instance { package, graph } => (package.clone(), graph.clone()),
|
||||
};
|
||||
seen.insert(source)
|
||||
})
|
||||
.map(|(_, candidate)| candidate)
|
||||
.collect();
|
||||
if let Some(first) = words.first() {
|
||||
found.sort_by_key(|candidate| !candidate.label.to_lowercase().starts_with(first.as_str()));
|
||||
}
|
||||
found
|
||||
}
|
||||
|
||||
/// Add `candidate` at the search position and connect it to the wire the search came from
|
||||
pub(crate) fn pick(app: &mut MaterialCraftApp, editor: &mut FunctionEditor, search: &FunctionSearch, candidate: &FunctionSearchCandidate) {
|
||||
let before = editor.selection.clone();
|
||||
let at = [search.at.x - crate::graph::NODE_W * 0.5, search.at.y - 20.0];
|
||||
super::library::insert(app, editor, &candidate.entry, at);
|
||||
let Some(&id) = editor.selection.first().filter(|_| editor.selection != before && editor.selection.len() == 1) else { return };
|
||||
|
||||
match search.wire {
|
||||
Some(SearchWire::From(from)) => {
|
||||
// Nodes without inputs (constants, variables) take no wire
|
||||
let inputs = editor.current(app).and_then(|graph| graph.node(id)).map_or(0, |node| node.inputs.len());
|
||||
if inputs > 0 {
|
||||
editor.edit(app, FunctionEdit::Connect { from, to: id, input: 0 }, false);
|
||||
}
|
||||
}
|
||||
Some(SearchWire::To(to, input)) => editor.edit(app, FunctionEdit::Connect { from: id, to, input }, false),
|
||||
None => {}
|
||||
}
|
||||
editor.selection = vec![id];
|
||||
editor.inspected_node = Some(id);
|
||||
}
|
||||
|
||||
pub(super) fn show(app: &mut MaterialCraftApp, editor: &mut FunctionEditor, ui: &mut Ui, camera: &GraphCamera) {
|
||||
let blocked = crate::shell::modality::Modality::capture(app, ui.ctx()).is_blocked();
|
||||
let Some(mut search) = editor.search.take() else { return };
|
||||
|
||||
let tokens = Tokens::get(ui.ctx());
|
||||
let area = egui::Id::unique("function-node-search");
|
||||
let mut close = false;
|
||||
let mut chosen = None;
|
||||
egui::Area::new(area).fixed_pos(camera.to_screen(search.at)).order(egui::Order::Foreground).show(ui.ctx(), |ui| {
|
||||
egui::Frame::popup(ui.style()).show(ui, |ui| {
|
||||
ui.set_width(280.0);
|
||||
if blocked {
|
||||
ui.disable();
|
||||
search.focus = true;
|
||||
}
|
||||
let mut reveal = search.focus;
|
||||
ui.horizontal(|ui| {
|
||||
ui.label(egui::RichText::new(icon::MAGNIFYING_GLASS).color(tokens.text_dim));
|
||||
let field = ui.add(egui::TextEdit::singleline(&mut search.text).hint_text(tr("Search functions...")).desired_width(240.0));
|
||||
crate::widgets::name(&field, egui::Role::SearchInput, "Search functions");
|
||||
if search.focus && !blocked {
|
||||
field.request_focus();
|
||||
search.focus = false;
|
||||
}
|
||||
if field.changed() {
|
||||
search.selected_index = 0;
|
||||
reveal = true;
|
||||
}
|
||||
});
|
||||
let list = candidates(app, editor, &search.text);
|
||||
let (up, down, enter, escape) = ui.input(|input| {
|
||||
let pressed = |key| !blocked && input.key_pressed(key);
|
||||
(pressed(egui::Key::ArrowUp), pressed(egui::Key::ArrowDown), pressed(egui::Key::Enter), pressed(egui::Key::Escape))
|
||||
});
|
||||
if down {
|
||||
search.selected_index = (search.selected_index + 1).min(list.len().saturating_sub(1));
|
||||
}
|
||||
if up {
|
||||
search.selected_index = search.selected_index.saturating_sub(1);
|
||||
}
|
||||
close |= escape;
|
||||
if enter {
|
||||
chosen = list.get(search.selected_index).cloned();
|
||||
}
|
||||
egui::ScrollArea::vertical().max_height(320.0).show(ui, |ui| {
|
||||
for (index, candidate) in list.iter().enumerate() {
|
||||
let row = ui.add(
|
||||
egui::Button::selectable(index == search.selected_index, format!("{} ", candidate.label))
|
||||
.min_size(egui::vec2(ui.available_width(), 0.0))
|
||||
.right_text(egui::RichText::new(&candidate.group).size(10.0).color(tokens.text_dim)),
|
||||
);
|
||||
if index == search.selected_index && (up || down || reveal) {
|
||||
row.scroll_to_me(None);
|
||||
}
|
||||
if row.clicked() {
|
||||
chosen = Some(candidate.clone());
|
||||
}
|
||||
}
|
||||
if list.is_empty() {
|
||||
ui.label(egui::RichText::new(tr("No matching node")).color(tokens.text_dim));
|
||||
}
|
||||
});
|
||||
});
|
||||
});
|
||||
let clicked_outside = !blocked
|
||||
&& ui.input(|input| input.pointer.any_pressed())
|
||||
&& ui.ctx().pointer_interact_pos().is_some_and(|pointer| !ui.ctx().layer_id_at(pointer).is_some_and(|layer| layer.id == area));
|
||||
if let Some(candidate) = chosen.filter(|_| !blocked) {
|
||||
pick(app, editor, &search, &candidate);
|
||||
} else if !close && !clicked_outside {
|
||||
editor.search = Some(search);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,8 @@
|
||||
/// The wire a search was opened from
|
||||
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
|
||||
pub(crate) enum SearchWire {
|
||||
/// Dragged from this node's output: the new node takes it on its first input
|
||||
From(u32),
|
||||
/// Dragged from this node's input slot: the new node's output feeds it
|
||||
To(u32, usize),
|
||||
}
|
||||
@@ -7,7 +7,7 @@ pub(crate) fn enabled(app: &MaterialCraftApp, command: &str) -> Option<bool> {
|
||||
|
||||
match command {
|
||||
"ui.graph.viewOutputs" | "ui.graph.resetViewOutputs" => Some(app.session.graph().is_ok_and(|graph| graph.function.is_none())),
|
||||
"ui.graph.previousPin" | "ui.graph.nextPin" => Some(app.session.graph().is_ok_and(|graph| !graph.pins.is_empty())),
|
||||
"ui.graph.previousPin" | "ui.graph.nextPin" => Some(app.graph.annotation_target.items(&app.session).is_ok_and(|items| !items.pins.is_empty())),
|
||||
command if command.starts_with("ui.graph.") => Some(app.session.graph().is_ok()),
|
||||
_ => None,
|
||||
}
|
||||
@@ -73,12 +73,12 @@ pub(crate) fn invoke(app: &mut MaterialCraftApp, command: &str) -> bool {
|
||||
}
|
||||
|
||||
fn navigate_pin(app: &mut MaterialCraftApp, forward: bool) {
|
||||
let Ok(graph) = app.session.graph() else { return };
|
||||
let Ok(graph) = app.graph.annotation_target.items(&app.session) else { return };
|
||||
if graph.pins.is_empty() {
|
||||
return;
|
||||
}
|
||||
|
||||
let camera = &mut app.ui.graph_camera;
|
||||
let mut camera = crate::annotation::camera(app);
|
||||
let zoom = camera.zoom.clamp(0.08, 4.0);
|
||||
let center = [camera.pan[0] + app.graph.view.width() * 0.5 / zoom, camera.pan[1] + app.graph.view.height() * 0.5 / zoom];
|
||||
let current = graph.pins.iter().position(|pin| (pin.pos[0] - center[0]).abs() < 0.1 && (pin.pos[1] - center[1]).abs() < 0.1);
|
||||
@@ -92,9 +92,11 @@ fn navigate_pin(app: &mut MaterialCraftApp, forward: bool) {
|
||||
let Some(pin) = graph.pins.get(index) else { return };
|
||||
|
||||
camera.pan = [pin.pos[0] - app.graph.view.width() * 0.5 / zoom, pin.pos[1] - app.graph.view.height() * 0.5 / zoom];
|
||||
if let Some(editor) = &mut app.function_editor
|
||||
&& editor.target == crate::function::FunctionTarget::Graph
|
||||
{
|
||||
editor.set_camera(*camera);
|
||||
if let Some(editor) = &mut app.function_editor {
|
||||
editor.set_camera(camera);
|
||||
} else if let Some(editor) = &mut app.pattern_editor {
|
||||
editor.set_camera(camera);
|
||||
} else {
|
||||
app.ui.graph_camera = camera;
|
||||
}
|
||||
}
|
||||
@@ -87,16 +87,28 @@ pub(crate) fn comments(app: &MaterialCraftApp, ui: &Ui, comments: &[Comment], ca
|
||||
hits
|
||||
}
|
||||
|
||||
pub(crate) fn pins(app: &MaterialCraftApp, ui: &Ui, pins: &[Pin], camera: &GraphCamera) {
|
||||
pub(crate) fn pins(app: &MaterialCraftApp, ui: &Ui, pins: &[Pin], camera: &GraphCamera) -> Vec<(u64, Rect)> {
|
||||
let painter = ui.painter_at(app.graph.view);
|
||||
let theme = Tokens::get(ui.ctx());
|
||||
|
||||
let mut hits = Vec::with_capacity(pins.len());
|
||||
for pin in pins {
|
||||
let position = pos2(pin.pos[0], pin.pos[1]) + offset(app, |contents| contents.pins.contains(&pin.id));
|
||||
let mut position = pos2(pin.pos[0], pin.pos[1]) + offset(app, |contents| contents.pins.contains(&pin.id));
|
||||
if let Some(GraphDrag::Pin { id, delta }) = &app.graph.drag
|
||||
&& *id == pin.id
|
||||
{
|
||||
position += *delta;
|
||||
}
|
||||
let position = camera.to_screen(position);
|
||||
painter.text(position, Align2::CENTER_BOTTOM, icon::MAP_PIN, FontId::proportional(18.0), theme.accent);
|
||||
painter.text(position + vec2(10.0, -10.0), Align2::LEFT_CENTER, &pin.name, FontId::proportional(11.0), theme.text);
|
||||
let selected = app.session.annotation_selection == Some(AnnotationSelection::Pin(pin.id));
|
||||
let marker = painter.text(position, Align2::CENTER_BOTTOM, icon::MAP_PIN, FontId::proportional(18.0), theme.accent);
|
||||
let label = painter.text(position + vec2(10.0, -10.0), Align2::LEFT_CENTER, &pin.name, FontId::proportional(11.0), theme.text);
|
||||
let bounds = marker.union(label).expand(3.0);
|
||||
if selected {
|
||||
painter.rect_stroke(bounds, 2.0, Stroke::new(1.0, theme.accent), StrokeKind::Outside);
|
||||
}
|
||||
hits.push((pin.id, bounds));
|
||||
}
|
||||
hits
|
||||
}
|
||||
|
||||
pub(crate) fn offset(app: &MaterialCraftApp, contains: impl FnOnce(&materialcraft_engine::FrameContents) -> bool) -> Vec2 {
|
||||
|
||||
@@ -3,7 +3,7 @@ use crate::MaterialCraftApp;
|
||||
use egui::{Rect, Ui, Vec2};
|
||||
use serde_json::json;
|
||||
|
||||
pub(crate) fn handle(app: &mut MaterialCraftApp, ui: &Ui, camera: &GraphCamera, frames: &[FrameHit], comments: &[(u64, Rect)]) {
|
||||
pub(crate) fn handle(app: &mut MaterialCraftApp, ui: &Ui, camera: &GraphCamera, frames: &[FrameHit], comments: &[(u64, Rect)], pins: &[(u64, Rect)]) {
|
||||
if super::gesture::cancelled(ui) {
|
||||
app.graph.drag = None;
|
||||
return;
|
||||
@@ -12,17 +12,24 @@ pub(crate) fn handle(app: &mut MaterialCraftApp, ui: &Ui, camera: &GraphCamera,
|
||||
let Some(pointer) = ui.input(|input| input.pointer.interact_pos()) else { return };
|
||||
|
||||
let pressed = ui.input(|input| input.pointer.primary_pressed());
|
||||
if ui.input(|input| input.pointer.secondary_clicked())
|
||||
&& let Some((id, _)) = pins.iter().rev().find(|(_, rect)| rect.contains(pointer))
|
||||
{
|
||||
app.run("graph.annotation.select", json!({"kind": "pin", "id": id}));
|
||||
}
|
||||
let motion = ui.input(|input| input.pointer.delta()) / camera.zoom;
|
||||
|
||||
if pressed && app.graph.view.contains(pointer) && app.graph.drag.is_none() && !app.graph.rects.iter().any(|(_, rect)| rect.contains(pointer)) {
|
||||
if let Some((id, _)) = comments.iter().rev().find(|(_, rect)| rect.contains(pointer)) {
|
||||
if let Some((id, _)) = pins.iter().rev().find(|(_, rect)| rect.contains(pointer)) {
|
||||
begin_pin(app, *id);
|
||||
} else if let Some((id, _)) = comments.iter().rev().find(|(_, rect)| rect.contains(pointer)) {
|
||||
begin_comment(app, *id);
|
||||
} else if let Some(hit) = frames.iter().rev().find(|hit| hit.contains(pointer)) {
|
||||
begin_frame(app, hit.id, hit.grip.contains(pointer));
|
||||
} else {
|
||||
app.run("graph.annotation.select", json!({}));
|
||||
}
|
||||
} else if let Some(GraphDrag::Frame { delta, .. } | GraphDrag::Comment { delta, .. }) = &mut app.graph.drag {
|
||||
} else if let Some(GraphDrag::Frame { delta, .. } | GraphDrag::Comment { delta, .. } | GraphDrag::Pin { delta, .. }) = &mut app.graph.drag {
|
||||
*delta += motion;
|
||||
}
|
||||
|
||||
@@ -40,10 +47,13 @@ pub(super) fn begin_comment(app: &mut MaterialCraftApp, id: u64) {
|
||||
|
||||
pub(super) fn begin_frame(app: &mut MaterialCraftApp, id: u64, resize: bool) {
|
||||
let contents = app
|
||||
.session
|
||||
.graph()
|
||||
.graph
|
||||
.annotation_target
|
||||
.items(&app.session)
|
||||
.ok()
|
||||
.and_then(|graph| graph.frames.iter().find(|frame| frame.id == id).map(|frame| materialcraft_engine::FrameContents::capture(graph, frame)))
|
||||
.and_then(|items| {
|
||||
items.frames.iter().find(|frame| frame.id == id).and_then(|frame| app.graph.annotation_target.capture_frame(&app.session, frame).ok())
|
||||
})
|
||||
.unwrap_or_default();
|
||||
app.run("graph.annotation.select", json!({"kind": "frame", "id": id}));
|
||||
app.graph.drag = Some(GraphDrag::Frame { id, delta: Vec2::ZERO, resize, contents });
|
||||
@@ -53,7 +63,9 @@ pub(super) fn finish(app: &mut MaterialCraftApp, drag: GraphDrag) {
|
||||
match drag {
|
||||
GraphDrag::Frame { id, delta, resize, .. } if delta.length() > 0.5 => {
|
||||
if resize {
|
||||
if let Some(frame) = app.session.graph().ok().and_then(|graph| graph.frames.iter().find(|frame| frame.id == id)) {
|
||||
if let Some(frame) =
|
||||
app.graph.annotation_target.items(&app.session).ok().and_then(|items| items.frames.into_iter().find(|frame| frame.id == id))
|
||||
{
|
||||
let rect = [frame.rect[0], frame.rect[1], frame.rect[2] + delta.x, frame.rect[3] + delta.y];
|
||||
app.run("graph.frame.edit", json!({"id": id, "rect": rect}));
|
||||
}
|
||||
@@ -62,11 +74,26 @@ pub(super) fn finish(app: &mut MaterialCraftApp, drag: GraphDrag) {
|
||||
}
|
||||
}
|
||||
GraphDrag::Comment { id, delta } if delta.length() > 0.5 => {
|
||||
if let Some(comment) = app.session.graph().ok().and_then(|graph| graph.comments.iter().find(|comment| comment.id == id)) {
|
||||
if let Some(comment) =
|
||||
app.graph.annotation_target.items(&app.session).ok().and_then(|items| items.comments.into_iter().find(|comment| comment.id == id))
|
||||
{
|
||||
let position = [comment.pos[0] + delta.x, comment.pos[1] + delta.y];
|
||||
app.run("graph.comment.edit", json!({"id": id, "at": position}));
|
||||
}
|
||||
}
|
||||
GraphDrag::Pin { id, delta } if delta.length() > 0.5 => {
|
||||
if let Some(pin) = app.graph.annotation_target.items(&app.session).ok().and_then(|items| items.pins.into_iter().find(|pin| pin.id == id)) {
|
||||
app.run("graph.pin.edit", json!({"id": id, "at": [pin.pos[0] + delta.x, pin.pos[1] + delta.y]}));
|
||||
app.session.finish_edit();
|
||||
}
|
||||
}
|
||||
_ => {}
|
||||
}
|
||||
}
|
||||
|
||||
pub(super) fn begin_pin(app: &mut MaterialCraftApp, id: u64) {
|
||||
app.run("graph.annotation.select", json!({"kind": "pin", "id": id}));
|
||||
app.inspected_folder = None;
|
||||
app.inspected_graph = None;
|
||||
app.graph.drag = Some(GraphDrag::Pin { id, delta: Vec2::ZERO });
|
||||
}
|
||||
@@ -33,6 +33,7 @@ pub fn show(app: &mut MaterialCraftApp, ui: &mut Ui) {
|
||||
}
|
||||
}
|
||||
|
||||
crate::annotation::activate(app, crate::annotation::target(app));
|
||||
super::toolbar::show(app, ui);
|
||||
if app.function_editor.is_some() {
|
||||
crate::function::show_graph(app, ui);
|
||||
@@ -278,7 +279,8 @@ fn canvas(app: &mut MaterialCraftApp, ui: &mut Ui) {
|
||||
|
||||
let comment_hits = super::annotation_canvas::comments(app, ui, &graph.comments, &camera);
|
||||
app.graph.comments = comment_hits.clone();
|
||||
super::annotation_canvas::pins(app, ui, &graph.pins, &camera);
|
||||
let pin_hits = super::annotation_canvas::pins(app, ui, &graph.pins, &camera);
|
||||
app.graph.pins = pin_hits.clone();
|
||||
|
||||
// Ports (drawn last, interactable over the node cards)
|
||||
// except on a dot's body: its port hit circles would otherwise cover it and it could never be moved
|
||||
@@ -311,7 +313,7 @@ fn canvas(app: &mut MaterialCraftApp, ui: &mut Ui) {
|
||||
ctx.set_cursor_icon(egui::CursorIcon::PointingHand);
|
||||
}
|
||||
app.graph.inspected_node = super::node_selection::inspected(&app.session.selection, app.graph.inspected_node);
|
||||
super::input::handle(app, ui, &resp, rect, &camera, &node_responses, &frame_hits, &comment_hits, port_hover, wire_hover);
|
||||
super::input::handle(app, ui, &resp, rect, &camera, &node_responses, &frame_hits, &comment_hits, &pin_hits, port_hover, wire_hover);
|
||||
app.graph.inspected_node = super::node_selection::inspected(&app.session.selection, app.graph.inspected_node);
|
||||
|
||||
// GraphDrag previews
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
use crate::{MaterialCraftApp, function::FunctionTarget};
|
||||
use crate::MaterialCraftApp;
|
||||
|
||||
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
|
||||
pub(crate) enum EditorTarget {
|
||||
@@ -9,12 +9,7 @@ pub(crate) enum EditorTarget {
|
||||
|
||||
impl EditorTarget {
|
||||
pub(crate) fn annotation_active(app: &MaterialCraftApp) -> bool {
|
||||
app.session.annotation_selection.is_some()
|
||||
&& match Self::resolve(app) {
|
||||
Self::Material => true,
|
||||
Self::Function => app.function_editor.as_ref().is_some_and(|editor| matches!(editor.target, FunctionTarget::Graph)),
|
||||
Self::Pattern => false,
|
||||
}
|
||||
app.session.annotation_selection.is_some() && app.session.annotation_target == app.graph.annotation_target
|
||||
}
|
||||
|
||||
pub(crate) fn resolve(app: &MaterialCraftApp) -> Self {
|
||||
|
||||
@@ -0,0 +1,225 @@
|
||||
//! The node search of Function canvases: keys, double-click and wires dropped on empty canvas
|
||||
|
||||
use egui::{Event, Key, Modifiers, PointerButton, Pos2, vec2};
|
||||
use materialcraft_engine::core::{FunctionGraph, Value};
|
||||
use materialcraft_engine::new_session;
|
||||
use serde_json::json;
|
||||
|
||||
use super::frames::Frames;
|
||||
use crate::function::search::{FunctionSearch, SearchWire};
|
||||
|
||||
fn press(key: Key) -> Event {
|
||||
Event::Key { key, physical_key: None, pressed: true, repeat: false, modifiers: Modifiers::NONE }
|
||||
}
|
||||
|
||||
/// A Function Graph holding one constant, framed in the canvas
|
||||
fn function_canvas() -> (Frames, u32) {
|
||||
let mut frames = Frames::new(new_session());
|
||||
frames.app.run("file.new", json!({"kind": "function"})).unwrap();
|
||||
let mut graph = FunctionGraph::default();
|
||||
let constant = graph.add_constant(Value::Float(2.0));
|
||||
graph.output = Some(constant);
|
||||
frames.app.run("graph.function.set", json!({"function": graph})).unwrap();
|
||||
frames.app.ui.frame_all = true;
|
||||
for _ in 0..4 {
|
||||
frames.run(Vec::new(), Modifiers::NONE);
|
||||
}
|
||||
(frames, constant)
|
||||
}
|
||||
|
||||
fn search(frames: &Frames) -> Option<FunctionSearch> {
|
||||
frames.app.function_editor.as_ref().and_then(|editor| editor.search.clone())
|
||||
}
|
||||
|
||||
fn empty(frames: &Frames) -> Pos2 {
|
||||
frames.app.graph.view.min + vec2(40.0, 40.0)
|
||||
}
|
||||
|
||||
fn port(frames: &Frames, node: u32, port: &str) -> Pos2 {
|
||||
frames
|
||||
.app
|
||||
.graph
|
||||
.ports
|
||||
.iter()
|
||||
.find(|hit| hit.node.0 == u64::from(node) && hit.port == port)
|
||||
.map(|hit| hit.pos)
|
||||
.unwrap_or_else(|| panic!("no port {node}:{port}"))
|
||||
}
|
||||
|
||||
fn drag(frames: &mut Frames, from: Pos2, to: Pos2) {
|
||||
frames.run(vec![Event::PointerMoved(from)], Modifiers::NONE);
|
||||
frames.run(vec![Event::PointerButton { pos: from, button: PointerButton::Primary, pressed: true, modifiers: Modifiers::NONE }], Modifiers::NONE);
|
||||
for step in 1..=8 {
|
||||
frames.run(vec![Event::PointerMoved(from.lerp(to, step as f32 / 8.0))], Modifiers::NONE);
|
||||
}
|
||||
frames.run(vec![Event::PointerButton { pos: to, button: PointerButton::Primary, pressed: false, modifiers: Modifiers::NONE }], Modifiers::NONE);
|
||||
frames.run(Vec::new(), Modifiers::NONE);
|
||||
}
|
||||
|
||||
/// Type `text` into the open search and pick the first result with Enter
|
||||
fn choose(frames: &mut Frames, text: &str) {
|
||||
frames.run(Vec::new(), Modifiers::NONE);
|
||||
frames.run(vec![Event::Text(text.into())], Modifiers::NONE);
|
||||
frames.run(Vec::new(), Modifiers::NONE);
|
||||
frames.run(vec![press(Key::Enter)], Modifiers::NONE);
|
||||
frames.run(Vec::new(), Modifiers::NONE);
|
||||
}
|
||||
|
||||
fn nodes(frames: &Frames) -> Vec<(u32, String, Vec<Option<u32>>)> {
|
||||
let function = frames.app.session.graph().unwrap().function.as_ref().unwrap();
|
||||
function.nodes.iter().map(|node| (node.id, node.op.clone(), node.inputs.clone())).collect()
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn space_tab_and_double_click_open_the_search_and_enter_adds() {
|
||||
let (mut frames, _) = function_canvas();
|
||||
for key in [Key::Space, Key::Tab] {
|
||||
frames.run(vec![Event::PointerMoved(empty(&frames))], Modifiers::NONE);
|
||||
frames.run(vec![press(key)], Modifiers::NONE);
|
||||
let opened = search(&frames).unwrap_or_else(|| panic!("{key:?} opens the search"));
|
||||
assert_eq!(opened.wire, None);
|
||||
frames.run(vec![press(Key::Escape)], Modifiers::NONE);
|
||||
assert!(search(&frames).is_none(), "Escape closes it");
|
||||
}
|
||||
|
||||
// Away from the canvas, the keys open nothing
|
||||
frames.run(vec![Event::PointerMoved(Pos2::new(5.0, 5.0))], Modifiers::NONE);
|
||||
frames.run(vec![press(Key::Space)], Modifiers::NONE);
|
||||
assert!(search(&frames).is_none());
|
||||
|
||||
let at = empty(&frames);
|
||||
frames.time += 1.0;
|
||||
frames.run(vec![Event::PointerMoved(at)], Modifiers::NONE);
|
||||
for pressed in [true, false, true, false] {
|
||||
frames.run(vec![Event::PointerButton { pos: at, button: PointerButton::Primary, pressed, modifiers: Modifiers::NONE }], Modifiers::NONE);
|
||||
}
|
||||
assert!(search(&frames).is_some(), "a double-click on empty canvas opens the search");
|
||||
|
||||
let before = nodes(&frames).len();
|
||||
choose(&mut frames, "add");
|
||||
assert!(search(&frames).is_none());
|
||||
let nodes = nodes(&frames);
|
||||
assert_eq!(nodes.len(), before + 1);
|
||||
assert!(nodes.iter().any(|(_, op, _)| op == "add"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn wires_dropped_on_empty_canvas_search_and_connect_the_new_node() {
|
||||
let (mut frames, constant) = function_canvas();
|
||||
|
||||
// From an output: the new node takes the wire on its first input
|
||||
let from = port(&frames, constant, "output");
|
||||
drag(&mut frames, from, from + vec2(260.0, -60.0));
|
||||
assert_eq!(search(&frames).unwrap().wire, Some(SearchWire::From(constant)));
|
||||
choose(&mut frames, "add");
|
||||
let (add, _, inputs) = nodes(&frames).into_iter().find(|(_, op, _)| op == "add").unwrap();
|
||||
assert_eq!(inputs, [Some(constant), None]);
|
||||
|
||||
// From an unconnected input: the new node's output feeds it
|
||||
frames.run(Vec::new(), Modifiers::NONE);
|
||||
let input = port(&frames, add, "1");
|
||||
let drop = input + vec2(-40.0, 110.0);
|
||||
assert!(frames.app.graph.view.contains(input) && frames.app.graph.view.contains(drop));
|
||||
drag(&mut frames, input, drop);
|
||||
assert_eq!(search(&frames).unwrap().wire, Some(SearchWire::To(add, 1)));
|
||||
choose(&mut frames, "Float");
|
||||
let nodes = nodes(&frames);
|
||||
let (_, _, inputs) = nodes.iter().find(|(id, _, _)| *id == add).unwrap();
|
||||
let fed = inputs[1].unwrap();
|
||||
assert_eq!(nodes.iter().find(|(id, _, _)| *id == fed).unwrap().1, "const_float1");
|
||||
|
||||
// A click on a port is not a drop on empty canvas
|
||||
frames.click(port(&frames, constant, "output"), Modifiers::NONE);
|
||||
assert!(search(&frames).is_none());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_toolbar_adds_common_function_nodes_wired_from_the_selection() {
|
||||
let (mut frames, constant) = function_canvas();
|
||||
let editor = frames.app.function_editor.as_mut().unwrap();
|
||||
editor.selection = vec![constant];
|
||||
crate::function::library::add_near_selection(&mut frames.app, "add");
|
||||
let (_, _, inputs) = nodes(&frames).into_iter().find(|(_, op, _)| op == "add").unwrap();
|
||||
assert_eq!(inputs, [Some(constant), None]);
|
||||
|
||||
// With nothing selected, a constant goes in the middle of the view, unwired
|
||||
frames.app.function_editor.as_mut().unwrap().selection.clear();
|
||||
crate::function::library::add_near_selection(&mut frames.app, "const_float2");
|
||||
assert!(nodes(&frames).iter().any(|(_, op, _)| op == "const_float2"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn function_search_lists_each_tagged_library_function_once() {
|
||||
use materialcraft_engine::core::{Graph, Package};
|
||||
use std::collections::BTreeSet;
|
||||
use std::sync::Arc;
|
||||
|
||||
let (mut frames, _) = function_canvas();
|
||||
let mut graph = Graph::new("TaggedSearchFixture");
|
||||
graph.function = Some(FunctionGraph::constant(Value::Float(0.5)));
|
||||
graph.attributes.tags = "Maths;Constant".into();
|
||||
let mut package = Package::new("Search fixture");
|
||||
package.graphs.push(graph);
|
||||
for path in ["sbs://search-first.sbs", "sbs://search-second.sbs"] {
|
||||
frames.app.session.pkg.dependencies.insert(path.into(), Arc::new(package.clone()));
|
||||
}
|
||||
let editor = frames.app.function_editor.as_ref().unwrap();
|
||||
|
||||
for text in ["TaggedSearchFixture", "TaggedSearchFixture maths", "TaggedSearchFixture constant"] {
|
||||
let candidates = crate::function::search::candidates(&frames.app, editor, text);
|
||||
|
||||
assert_eq!(candidates.len(), 2, "one result per package, matching every category: {text}");
|
||||
let sources: BTreeSet<_> = candidates
|
||||
.iter()
|
||||
.map(|candidate| match &candidate.entry {
|
||||
crate::function::library::FunctionLibraryDrag::Instance { package, .. } => package.as_str(),
|
||||
_ => panic!("the fixture must be a library function"),
|
||||
})
|
||||
.collect();
|
||||
assert_eq!(sources, BTreeSet::from(["sbs://search-first.sbs", "sbs://search-second.sbs"]));
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn function_search_uses_text_typed_in_the_enter_frame() {
|
||||
let (mut frames, _) = function_canvas();
|
||||
frames.run(vec![Event::PointerMoved(empty(&frames))], Modifiers::NONE);
|
||||
frames.run(vec![press(Key::Space)], Modifiers::NONE);
|
||||
frames.run(Vec::new(), Modifiers::NONE);
|
||||
assert!(search(&frames).is_some());
|
||||
|
||||
frames.run(vec![Event::Text("sample color".into()), press(Key::Enter)], Modifiers::NONE);
|
||||
|
||||
assert!(search(&frames).is_none());
|
||||
let nodes = nodes(&frames);
|
||||
assert_eq!(nodes.len(), 2);
|
||||
assert!(nodes.iter().any(|(_, operation, _)| operation == "samplecol"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn processor_search_and_toolbar_keep_both_samplers_available() {
|
||||
use materialcraft_engine::{FunctionGraphTarget, core::NodeId};
|
||||
|
||||
for definition in ["pixel_processor", "value_processor"] {
|
||||
let mut frames = Frames::new(new_session());
|
||||
let owner = NodeId(frames.app.run("graph.node.add", json!({"def": definition})).unwrap()["id"].as_u64().unwrap());
|
||||
crate::menus::invoke(&mut frames.app, &frames.ctx, "graph.node.edit");
|
||||
frames.run(Vec::new(), Modifiers::NONE);
|
||||
let target = FunctionGraphTarget::Parameter { node: owner, parameter: "function".into() };
|
||||
let parent_count = frames.app.session.graph().unwrap().nodes.len();
|
||||
let editor = frames.app.function_editor.as_ref().unwrap();
|
||||
let candidates = crate::function::search::candidates(&frames.app, editor, "sample");
|
||||
for operation in ["samplelum", "samplecol"] {
|
||||
assert!(
|
||||
candidates.iter().any(|candidate| matches!(&candidate.entry,
|
||||
crate::function::library::FunctionLibraryDrag::Operation(found) if found == operation)),
|
||||
"{definition}: {operation}"
|
||||
);
|
||||
|
||||
crate::function::library::add_near_selection(&mut frames.app, operation);
|
||||
|
||||
assert!(target.current(&frames.app.session).unwrap().nodes.iter().any(|node| node.op == operation));
|
||||
}
|
||||
assert_eq!(frames.app.session.graph().unwrap().nodes.len(), parent_count);
|
||||
}
|
||||
}
|
||||
@@ -30,6 +30,10 @@ pub(super) enum GraphDrag {
|
||||
resize: bool,
|
||||
contents: materialcraft_engine::FrameContents,
|
||||
},
|
||||
Pin {
|
||||
id: u64,
|
||||
delta: Vec2,
|
||||
},
|
||||
Comment {
|
||||
id: u64,
|
||||
delta: Vec2,
|
||||
|
||||
@@ -13,6 +13,9 @@ pub struct GraphView {
|
||||
pub ports: Vec<PortHit>,
|
||||
pub frames: Vec<(u64, Rect)>,
|
||||
pub comments: Vec<(u64, Rect)>,
|
||||
pub pins: Vec<(u64, Rect)>,
|
||||
pub(crate) annotation_target: materialcraft_engine::AnnotationTarget,
|
||||
pub(crate) pin_description_focus: Option<u64>,
|
||||
/// The canvas rectangle last frame
|
||||
pub view: Rect,
|
||||
/// Graph point of the last right-click (context menu actions add things there)
|
||||
@@ -28,10 +31,14 @@ pub struct GraphView {
|
||||
}
|
||||
|
||||
impl GraphView {
|
||||
pub(crate) fn cancel_gesture(&mut self) {
|
||||
pub(crate) fn cancel_drag(&mut self) {
|
||||
self.drag = None;
|
||||
self.search = None;
|
||||
self.menu_wire = None;
|
||||
}
|
||||
|
||||
pub(crate) fn cancel_gesture(&mut self) {
|
||||
self.cancel_drag();
|
||||
self.framed_graph = None;
|
||||
}
|
||||
pub(crate) fn is_dragging(&self) -> bool {
|
||||
@@ -51,6 +58,9 @@ impl Default for GraphView {
|
||||
ports: Vec::new(),
|
||||
frames: Vec::new(),
|
||||
comments: Vec::new(),
|
||||
pins: Vec::new(),
|
||||
annotation_target: Default::default(),
|
||||
pin_description_focus: None,
|
||||
view: Rect::NOTHING,
|
||||
menu_at: Pos2::ZERO,
|
||||
framed_graph: None,
|
||||
|
||||
@@ -1,5 +1,10 @@
|
||||
use super::{GraphCamera, GraphDrag, LibraryDrag, NODE_W, PortHit, WireRef};
|
||||
use super::{navigation::frame, port_hit::nearest as nearest_port, search::open_search, wire_actions::wire_menu};
|
||||
use super::{
|
||||
navigation::frame,
|
||||
port_hit::nearest as nearest_port,
|
||||
search::{open_search, open_search_to},
|
||||
wire_actions::wire_menu,
|
||||
};
|
||||
use crate::MaterialCraftApp;
|
||||
use egui::{Rect, Ui, Vec2};
|
||||
use materialcraft_engine::core::NodeId;
|
||||
@@ -15,6 +20,7 @@ pub(super) fn handle(
|
||||
nodes: &[(NodeId, egui::Response)],
|
||||
frames: &[super::frame_hit::FrameHit],
|
||||
comments: &[(u64, Rect)],
|
||||
pins: &[(u64, Rect)],
|
||||
port_hover: Option<PortHit>,
|
||||
wire_hover: Option<WireRef>,
|
||||
) {
|
||||
@@ -42,7 +48,9 @@ pub(super) fn handle(
|
||||
app.run("graph.annotation.select", json!({}));
|
||||
}
|
||||
|
||||
let on_card = nodes.iter().any(|(_, response)| response.rect.contains(position)) || comments.iter().any(|(_, bounds)| bounds.contains(position));
|
||||
let on_card = nodes.iter().any(|(_, response)| response.rect.contains(position))
|
||||
|| comments.iter().any(|(_, bounds)| bounds.contains(position))
|
||||
|| pins.iter().any(|(_, bounds)| bounds.contains(position));
|
||||
let wire = wire_hover.as_ref().filter(|_| port_hover.is_none() && !on_card);
|
||||
if wire.is_none() {
|
||||
super::node_selection::select(&mut app.graph.selected_wires, None, modifiers);
|
||||
@@ -59,6 +67,8 @@ pub(super) fn handle(
|
||||
} else {
|
||||
app.graph.drag = Some(GraphDrag::InputWire { to: (port.node, port.port.clone()) });
|
||||
}
|
||||
} else if let Some((id, _)) = pins.iter().rev().find(|(_, bounds)| bounds.contains(position)) {
|
||||
super::annotation_input::begin_pin(app, *id);
|
||||
} else if let Some((id, _)) = comments.iter().rev().find(|(_, bounds)| bounds.contains(position)) {
|
||||
super::annotation_input::begin_comment(app, *id);
|
||||
} else if let Some((id, _)) = nodes.iter().rev().find(|(_, response)| response.rect.contains(position)) {
|
||||
@@ -78,7 +88,10 @@ pub(super) fn handle(
|
||||
let delta = context.input(|input| input.pointer.delta()) / zoom;
|
||||
app.ui.graph_camera.pan = [app.ui.graph_camera.pan[0] - delta.x, app.ui.graph_camera.pan[1] - delta.y];
|
||||
}
|
||||
Some(GraphDrag::Nodes { delta }) | Some(GraphDrag::Frame { delta, .. }) | Some(GraphDrag::Comment { delta, .. }) => *delta += motion,
|
||||
Some(GraphDrag::Nodes { delta })
|
||||
| Some(GraphDrag::Frame { delta, .. })
|
||||
| Some(GraphDrag::Comment { delta, .. })
|
||||
| Some(GraphDrag::Pin { delta, .. }) => *delta += motion,
|
||||
Some(GraphDrag::WirePress { wire, start }) => {
|
||||
// Dragged far enough: a reroute dot where the press was, carried by the pointer
|
||||
if let Some(position) = pointer
|
||||
@@ -140,12 +153,17 @@ pub(super) fn handle(
|
||||
}
|
||||
}
|
||||
GraphDrag::InputWire { to } => {
|
||||
// Dropped anywhere but on another node's output, the input stays unconnected
|
||||
if let Some(source) = drop_target(&app.graph.ports, pointer, true).filter(|source| source.node != to.0) {
|
||||
app.run("graph.connect", json!({"from": source.node.0, "fromPort": source.port, "to": to.0.0, "toPort": to.1}));
|
||||
} else if let Some(position) = pointer
|
||||
&& rect.contains(position)
|
||||
&& nearest_port(&app.graph.ports, position, 12.0).is_none()
|
||||
{
|
||||
// Dropped on empty canvas: search for a node whose output feeds the input
|
||||
open_search_to(app, &context, camera.to_graph(position), to);
|
||||
}
|
||||
}
|
||||
GraphDrag::Frame { .. } | GraphDrag::Comment { .. } => super::annotation_input::finish(app, drag),
|
||||
GraphDrag::Frame { .. } | GraphDrag::Comment { .. } | GraphDrag::Pin { .. } => super::annotation_input::finish(app, drag),
|
||||
}
|
||||
}
|
||||
|
||||
@@ -183,6 +201,7 @@ pub(super) fn handle(
|
||||
let on_node = pointer.is_some_and(|position| {
|
||||
nodes.iter().any(|(_, response)| response.rect.contains(position))
|
||||
|| comments.iter().any(|(_, bounds)| bounds.contains(position))
|
||||
|| pins.iter().any(|(_, bounds)| bounds.contains(position))
|
||||
|| frames.iter().any(|frame| frame.contains(position))
|
||||
});
|
||||
if canvas.double_clicked()
|
||||
@@ -204,7 +223,9 @@ pub(super) fn handle(
|
||||
&& let Some(position) = pointer
|
||||
{
|
||||
app.graph.menu_at = camera.to_graph(position);
|
||||
if let Some((id, _)) = comments.iter().rev().find(|(_, rect)| rect.contains(position)) {
|
||||
if let Some((id, _)) = pins.iter().rev().find(|(_, rect)| rect.contains(position)) {
|
||||
app.run("graph.annotation.select", json!({"kind": "pin", "id": id}));
|
||||
} else if let Some((id, _)) = comments.iter().rev().find(|(_, rect)| rect.contains(position)) {
|
||||
app.run("graph.annotation.select", json!({"kind": "comment", "id": id}));
|
||||
} else if let Some(hit) = frames.iter().rev().find(|frame| frame.contains(position)) {
|
||||
app.run("graph.annotation.select", json!({"kind": "frame", "id": hit.id}));
|
||||
@@ -247,7 +268,7 @@ pub(super) fn handle(
|
||||
{
|
||||
let graph_position = camera.to_graph(position);
|
||||
let at = [graph_position.x - NODE_W * 0.5, graph_position.y - 20.0];
|
||||
app.run("graph.node.add", json!({"def": payload.0, "at": at}));
|
||||
app.run("library.add", json!({"entry": payload.0, "at": at, "snapToGrid": app.ui.prefs.snap_to_grid}));
|
||||
}
|
||||
|
||||
// Keys over the canvas
|
||||
|
||||
@@ -838,15 +838,20 @@ fn wires_pulled_from_an_unconnected_input_connect_on_an_output() {
|
||||
let empty = frames.app.graph.view.left_bottom() + vec2(24.0, -24.0);
|
||||
assert!(!frames.app.graph.rects.iter().any(|(_, rect)| rect.expand(12.0).contains(empty)), "the drop point must be empty canvas");
|
||||
|
||||
// A click, and drops on empty canvas, on another input and on the node's own output leave the input unconnected
|
||||
// A click, and drops on another input and on the node's own output leave the input unconnected
|
||||
let history = frames.app.session.history();
|
||||
frames.click(inputs[0].pos, Modifiers::NONE);
|
||||
frames.time += 1.0;
|
||||
for end in [empty, inputs[1].pos, ports(&frames, target, true)[0].pos] {
|
||||
assert!(frames.app.graph.search.is_none(), "a click on an input opens nothing");
|
||||
for end in [inputs[1].pos, ports(&frames, target, true)[0].pos] {
|
||||
drag(&mut frames, inputs[0].pos, end);
|
||||
}
|
||||
assert!(frames.app.graph.search.is_none());
|
||||
// Dropped on empty canvas, it searches for a node to feed the input, as an output wire does
|
||||
drag(&mut frames, inputs[0].pos, empty);
|
||||
assert!(frames.app.graph.search.as_ref().is_some_and(|search| search.connect_to == Some((target, inputs[0].port.clone()))));
|
||||
frames.app.graph.search = None;
|
||||
assert!(wires(&frames).is_empty());
|
||||
assert!(frames.app.graph.search.is_none(), "an input wire dropped on empty canvas does not open the node search");
|
||||
assert_eq!(frames.app.session.history(), history, "a missed wire must not add an undo step");
|
||||
|
||||
// While dragging, the wire is pulled from the input; dropped on the output, it connects
|
||||
@@ -867,3 +872,58 @@ fn wires_pulled_from_an_unconnected_input_connect_on_an_output() {
|
||||
frames.app.session.undo().unwrap();
|
||||
assert_eq!(wires(&frames).len(), 2);
|
||||
}
|
||||
|
||||
/// A library drop uses the same snapping preference as other node additions.
|
||||
#[test]
|
||||
fn review_library_drop_respects_grid_preference() {
|
||||
for snapping in [true, false] {
|
||||
let mut frames = Frames::new(new_session());
|
||||
frames.app.ui.prefs.snap_to_grid = snapping;
|
||||
let position = frames.app.graph.view.center() + vec2(113.0, 77.0);
|
||||
frames.run(vec![Event::PointerMoved(position)], Modifiers::NONE);
|
||||
frames.run(vec![Event::PointerButton { pos: position, button: PointerButton::Primary, pressed: true, modifiers: Modifiers::NONE }], Modifiers::NONE);
|
||||
egui::DragAndDrop::set_payload(&frames.ctx, super::LibraryDrag("node:blur".into()));
|
||||
let camera =
|
||||
super::GraphCamera { origin: frames.app.graph.view.min, pan: frames.app.ui.graph_camera.pan.into(), zoom: frames.app.ui.graph_camera.zoom };
|
||||
let graph_position = camera.to_graph(position);
|
||||
let expected = materialcraft_engine::graph_grid::snap_position([graph_position.x - super::NODE_W * 0.5, graph_position.y - 20.0], snapping);
|
||||
let before = frames.app.session.graph().unwrap().nodes.len();
|
||||
|
||||
frames.run(vec![Event::PointerButton { pos: position, button: PointerButton::Primary, pressed: false, modifiers: Modifiers::NONE }], Modifiers::NONE);
|
||||
|
||||
let graph = frames.app.session.graph().unwrap();
|
||||
assert_eq!(graph.nodes.len(), before + 1);
|
||||
assert_eq!(graph.nodes.last().unwrap().pos, expected, "snapping: {snapping}");
|
||||
}
|
||||
}
|
||||
|
||||
/// Both standalone canvases hit the pin marker and description and preserve drag undo.
|
||||
#[test]
|
||||
fn navigation_pins_can_be_selected_dragged_and_deleted() {
|
||||
for function in [false, true] {
|
||||
let mut session = new_session();
|
||||
if function {
|
||||
materialcraft_engine::execute(&mut session, "file.new", &json!({"kind": "function"})).unwrap();
|
||||
}
|
||||
let mut frames = Frames::new(session);
|
||||
let camera = &frames.app.ui.graph_camera;
|
||||
let position = egui::Pos2::from(camera.pan) + frames.app.graph.view.size() * 0.5 / camera.zoom;
|
||||
let id = frames.app.run("graph.pin.add", json!({"at": [position.x, position.y], "name": "Review checkpoint"})).unwrap()["id"].as_u64().unwrap();
|
||||
frames.app.run("graph.annotation.select", json!({}));
|
||||
frames.run(Vec::new(), Modifiers::NONE);
|
||||
let from = frames.app.graph.view.center() + vec2(30.0, -10.0);
|
||||
frames.click(from, Modifiers::NONE);
|
||||
assert_eq!(serde_json::to_value(frames.app.session.annotation_selection).unwrap(), json!({"kind": "pin", "id": id}));
|
||||
assert_eq!(crate::properties::title(&frames.app), "Navigation Pin - Properties");
|
||||
let before = frames.app.session.graph().unwrap().pins[0].pos;
|
||||
let zoom = frames.app.ui.graph_camera.zoom;
|
||||
drag(&mut frames, from, from + vec2(64.0, 32.0) * zoom);
|
||||
let after = frames.app.session.graph().unwrap().pins[0].pos;
|
||||
assert!((after[0] - before[0] - 64.0).abs() < 0.01);
|
||||
assert!((after[1] - before[1] - 32.0).abs() < 0.01);
|
||||
frames.app.session.undo().unwrap();
|
||||
assert_eq!(frames.app.session.graph().unwrap().pins[0].pos, before);
|
||||
menus::invoke(&mut frames.app, &frames.ctx, "edit.delete");
|
||||
assert!(frames.app.session.graph().unwrap().pins.is_empty());
|
||||
}
|
||||
}
|
||||
@@ -1,3 +1,3 @@
|
||||
/// A library item being dragged onto the canvas
|
||||
/// A library entry (its `library.tree` id) being dragged onto the canvas
|
||||
#[derive(Clone, Debug)]
|
||||
pub struct LibraryDrag(pub String);
|
||||
@@ -7,6 +7,8 @@ mod context_menu;
|
||||
pub(crate) mod frame_hit;
|
||||
#[cfg(test)]
|
||||
mod frames;
|
||||
#[cfg(test)]
|
||||
mod function_search_tests;
|
||||
mod graph_camera;
|
||||
mod graph_drag;
|
||||
pub(crate) mod graph_parent;
|
||||
@@ -30,7 +32,7 @@ pub(crate) use graph_camera::GraphCamera;
|
||||
use graph_drag::GraphDrag;
|
||||
pub use graph_view::GraphView;
|
||||
pub use library_drag::LibraryDrag;
|
||||
pub use navigation::add_node_near_selection;
|
||||
pub use navigation::{add_entry_in_view, add_node_near_selection};
|
||||
use node_search::NodeSearch;
|
||||
pub use node_style::{NODE_W, header_color, node_label, node_rect, port_color};
|
||||
pub use port_hit::PortHit;
|
||||
|
||||
@@ -46,7 +46,9 @@ fn corner(frames: &Frames) -> Pos2 {
|
||||
}
|
||||
|
||||
fn add_menu_open(frames: &Frames) -> bool {
|
||||
frames.app.graph.search.is_some() || egui::Popup::is_any_open(&frames.ctx)
|
||||
frames.app.graph.search.is_some()
|
||||
|| frames.app.function_editor.as_ref().is_some_and(|editor| editor.search.is_some())
|
||||
|| egui::Popup::is_any_open(&frames.ctx)
|
||||
}
|
||||
|
||||
#[test]
|
||||
|
||||
@@ -9,6 +9,12 @@ pub(super) fn view_center(app: &MaterialCraftApp) -> Pos2 {
|
||||
pos2(c.pan[0] + v.width() * 0.5 / c.zoom, c.pan[1] + v.height() * 0.5 / c.zoom)
|
||||
}
|
||||
|
||||
/// Add library entry `id` (a comment, frame, pin or graph instance) in the middle of the view
|
||||
pub fn add_entry_in_view(app: &mut MaterialCraftApp, id: &str) {
|
||||
let c = view_center(app);
|
||||
app.run("library.add", json!({"entry": id, "at": [c.x - NODE_W * 0.5, c.y - 60.0], "snapToGrid": app.ui.prefs.snap_to_grid}));
|
||||
}
|
||||
|
||||
/// Add `def` right of the last selected node (wired from it when it fits), else mid-view
|
||||
pub fn add_node_near_selection(app: &mut MaterialCraftApp, def: &str) {
|
||||
let sel = app.session.selection.last().copied();
|
||||
|
||||
@@ -8,5 +8,7 @@ pub(super) struct NodeSearch {
|
||||
pub(super) text: String,
|
||||
pub(super) sel: usize,
|
||||
pub(super) connect: Option<(NodeId, String)>,
|
||||
/// Opened from this input (a wire dragged off it): the new node's output feeds it
|
||||
pub(super) connect_to: Option<(NodeId, String)>,
|
||||
pub(super) focus: bool,
|
||||
}
|
||||
@@ -9,7 +9,15 @@ pub(super) fn open_search(app: &mut MaterialCraftApp, ctx: &egui::Context, at: P
|
||||
if crate::shell::modality::Modality::capture(app, ctx).is_blocked() {
|
||||
return;
|
||||
}
|
||||
app.graph.search = Some(NodeSearch { at, text: String::new(), sel: 0, connect, focus: true });
|
||||
app.graph.search = Some(NodeSearch { at, text: String::new(), sel: 0, connect, connect_to: None, focus: true });
|
||||
}
|
||||
|
||||
/// The search for a node whose output feeds input `to` (a wire dragged off it onto empty canvas)
|
||||
pub(super) fn open_search_to(app: &mut MaterialCraftApp, ctx: &egui::Context, at: Pos2, to: (NodeId, String)) {
|
||||
open_search(app, ctx, at, None);
|
||||
if let Some(search) = app.graph.search.as_mut() {
|
||||
search.connect_to = Some(to);
|
||||
}
|
||||
}
|
||||
|
||||
/// Catalog entries matching `text` (label or id contains every word)
|
||||
@@ -58,7 +66,11 @@ pub(super) fn show(app: &mut MaterialCraftApp, ui: &mut Ui, cam: &GraphCamera) {
|
||||
reveal_selection = true;
|
||||
}
|
||||
});
|
||||
let list = matches(&s.text);
|
||||
// Feeding an input needs a node with an output
|
||||
let mut list = matches(&s.text);
|
||||
if s.connect_to.is_some() {
|
||||
list.retain(|definition| !definition.outputs.is_empty());
|
||||
}
|
||||
let (up, down, enter, esc) = ui.input(|i| {
|
||||
let pressed = |key| !blocked && i.key_pressed(key);
|
||||
(pressed(egui::Key::ArrowUp), pressed(egui::Key::ArrowDown), pressed(egui::Key::Enter), pressed(egui::Key::Escape))
|
||||
@@ -105,7 +117,12 @@ pub(super) fn show(app: &mut MaterialCraftApp, ui: &mut Ui, cam: &GraphCamera) {
|
||||
if let Some((n, port)) = s.connect {
|
||||
p["connectFrom"] = json!({"node": n.0, "port": port});
|
||||
}
|
||||
app.run("graph.node.add", p);
|
||||
let added = app.run("graph.node.add", p).and_then(|result| result.get("id").and_then(serde_json::Value::as_u64)).map(NodeId);
|
||||
if let (Some(id), Some((to, port))) = (added, s.connect_to)
|
||||
&& let Some(output) = app.session.output_ports(id).first().cloned()
|
||||
{
|
||||
app.run("graph.connect", json!({"from": id.0, "fromPort": output, "to": to.0, "toPort": port}));
|
||||
}
|
||||
}
|
||||
} else if close || clicked_out {
|
||||
app.graph.search = None;
|
||||
|
||||
@@ -7,7 +7,6 @@ use serde_json::json;
|
||||
pub(super) fn show(app: &mut MaterialCraftApp, ui: &mut Ui) {
|
||||
let function = app.function_editor.is_some();
|
||||
let pattern = !function && crate::pattern::active(app);
|
||||
let embedded_function = app.function_editor.as_ref().is_some_and(|editor| editor.target != crate::function::FunctionTarget::Graph);
|
||||
let function_target = app.function_editor.as_ref().and_then(|editor| editor.command_target());
|
||||
let selection: Vec<u64> = if pattern {
|
||||
app.pattern_editor.as_ref().map(|editor| editor.selection.iter().copied().map(u64::from).collect()).unwrap_or_default()
|
||||
@@ -32,10 +31,10 @@ pub(super) fn show(app: &mut MaterialCraftApp, ui: &mut Ui) {
|
||||
}) {
|
||||
app.ui.frame_all = true;
|
||||
}
|
||||
if !pattern && !embedded_function {
|
||||
{
|
||||
ui.separator();
|
||||
if b(ui, icon::SELECTION, tr("Add frame around the selection")) {
|
||||
let parameters = if function { function_frame(app, &selection) } else { json!({}) };
|
||||
let parameters = annotation_frame(app, &selection);
|
||||
app.run("graph.frame.add", parameters);
|
||||
}
|
||||
if b(ui, icon::NOTE, tr("Add comment")) {
|
||||
@@ -47,37 +46,6 @@ pub(super) fn show(app: &mut MaterialCraftApp, ui: &mut Ui) {
|
||||
}
|
||||
}
|
||||
|
||||
if !pattern && !function {
|
||||
// Quick insert of the atomic nodes
|
||||
for (ic, def) in [
|
||||
(icon::IMAGE, "bitmap"),
|
||||
(icon::PALETTE, "uniform"),
|
||||
(icon::STACK, "blend"),
|
||||
(icon::DROP, "blur"),
|
||||
(icon::SHUFFLE, "channels_shuffle"),
|
||||
(icon::CHART_LINE, "curve"),
|
||||
(icon::WIND, "directional_blur"),
|
||||
(icon::ARROWS_OUT_LINE_HORIZONTAL, "directional_warp"),
|
||||
(icon::RULER, "distance"),
|
||||
(icon::MOUNTAINS, "emboss"),
|
||||
(icon::GRADIENT, "gradient_map"),
|
||||
(icon::CIRCLE_HALF, "grayscale_conversion"),
|
||||
(icon::SWATCHES, "hsl"),
|
||||
(icon::SLIDERS_HORIZONTAL, "levels"),
|
||||
(icon::CUBE, "normal"),
|
||||
(icon::CODE, "pixel_processor"),
|
||||
(icon::DIAMOND, "sharpen"),
|
||||
(icon::ARROWS_CLOCKWISE, "transformation"),
|
||||
(icon::WAVES, "warp"),
|
||||
(icon::SIGN_IN, "input_grayscale"),
|
||||
(icon::SIGN_OUT, "output"),
|
||||
] {
|
||||
let label = materialcraft_engine::nodes::find(def).map_or(def, |d| d.label);
|
||||
if b(ui, ic, label) {
|
||||
add_node_near_selection(app, def);
|
||||
}
|
||||
}
|
||||
}
|
||||
ui.with_layout(egui::Layout::right_to_left(egui::Align::Center), |ui| {
|
||||
if super::subgraph_navigation::can_return(app) {
|
||||
if b(ui, icon::ARROW_BEND_UP_LEFT, tr("Return to parent graph")) {
|
||||
@@ -97,8 +65,83 @@ pub(super) fn show(app: &mut MaterialCraftApp, ui: &mut Ui) {
|
||||
}
|
||||
});
|
||||
});
|
||||
|
||||
// A second row inserts nodes with one click, like the Library's most common entries
|
||||
if !pattern {
|
||||
row(ui, |ui| quick_nodes(app, ui, function));
|
||||
}
|
||||
}
|
||||
|
||||
/// The atomic nodes of a graph, or the common nodes of a Function canvas, as one-click buttons
|
||||
fn quick_nodes(app: &mut MaterialCraftApp, ui: &mut Ui, function: bool) {
|
||||
if function {
|
||||
let available = crate::function::library::available_operations(app);
|
||||
for (index, group) in crate::function::library::QUICK.iter().enumerate() {
|
||||
if index > 0 {
|
||||
ui.separator();
|
||||
}
|
||||
for (operation, glyph) in *group {
|
||||
let label = materialcraft_engine::nodes::function::definition(operation).map_or(*operation, |definition| definition.label);
|
||||
// "New … node" keeps the button apart from the canvas nodes of the same name
|
||||
let tooltip = crate::i18n::trf("New {node} node", &[("node", &tr(label))]);
|
||||
if ui.add_enabled_ui(available.contains(operation), |ui| button(ui, glyph, &tooltip)).inner {
|
||||
crate::function::library::add_near_selection(app, operation);
|
||||
}
|
||||
}
|
||||
}
|
||||
return;
|
||||
}
|
||||
|
||||
for (index, group) in ATOMIC_QUICK.iter().enumerate() {
|
||||
if index > 0 {
|
||||
ui.separator();
|
||||
}
|
||||
for (ic, def) in *group {
|
||||
let label = materialcraft_engine::nodes::find(def).map_or(*def, |d| d.label);
|
||||
if button(ui, ic, tr(label)) {
|
||||
add_node_near_selection(app, def);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// The atomic nodes on the graph toolbar, in groups
|
||||
const ATOMIC_QUICK: &[&[(&str, &str)]] = &[
|
||||
&[
|
||||
(icon::IMAGE, "bitmap"),
|
||||
(icon::STACK, "blend"),
|
||||
(icon::DROP, "blur"),
|
||||
(icon::SHUFFLE, "channels_shuffle"),
|
||||
(icon::CHART_LINE, "curve"),
|
||||
(icon::WIND, "directional_blur"),
|
||||
(icon::ARROWS_OUT_LINE_HORIZONTAL, "directional_warp"),
|
||||
(icon::RULER, "distance"),
|
||||
(icon::MOUNTAINS, "emboss"),
|
||||
(icon::SQUARES_FOUR, "fx_map"),
|
||||
(icon::ARROWS_DOWN_UP, "gradient_dynamic"),
|
||||
(icon::GRADIENT, "gradient_map"),
|
||||
(icon::CIRCLE_HALF, "grayscale_conversion"),
|
||||
(icon::SWATCHES, "hsl"),
|
||||
(icon::SLIDERS_HORIZONTAL, "levels"),
|
||||
(icon::CUBE, "normal"),
|
||||
(icon::CODE, "pixel_processor"),
|
||||
(icon::BEZIER_CURVE, "svg"),
|
||||
(icon::DIAMOND, "sharpen"),
|
||||
(icon::TEXT_T, "text"),
|
||||
(icon::ARROWS_CLOCKWISE, "transformation"),
|
||||
(icon::PALETTE, "uniform"),
|
||||
(icon::FUNCTION, "value_processor"),
|
||||
(icon::WAVES, "warp"),
|
||||
],
|
||||
&[
|
||||
(icon::PAINT_BUCKET, "input_color"),
|
||||
(icon::SIGN_IN, "input_grayscale"),
|
||||
(icon::HASH, "input_value"),
|
||||
(icon::SIGN_OUT, "output"),
|
||||
(icon::DOT_OUTLINE, "dot"),
|
||||
],
|
||||
];
|
||||
|
||||
fn row(ui: &mut Ui, draw: impl FnOnce(&mut Ui)) {
|
||||
let tokens = Tokens::get(ui.ctx());
|
||||
egui::Frame::NONE.fill(tokens.panel).inner_margin(egui::Margin::symmetric(6, 3)).show(ui, |ui| {
|
||||
@@ -169,8 +212,9 @@ fn parent_size(app: &mut MaterialCraftApp, ui: &mut Ui) {
|
||||
}
|
||||
}
|
||||
|
||||
fn function_frame(app: &MaterialCraftApp, selection: &[u64]) -> serde_json::Value {
|
||||
let camera = super::GraphCamera { origin: app.graph.view.min, pan: app.ui.graph_camera.pan.into(), zoom: app.ui.graph_camera.zoom };
|
||||
fn annotation_frame(app: &MaterialCraftApp, selection: &[u64]) -> serde_json::Value {
|
||||
let camera = crate::annotation::camera(app);
|
||||
let camera = super::GraphCamera { origin: app.graph.view.min, pan: camera.pan.into(), zoom: camera.zoom };
|
||||
let bounds = app.graph.rects.iter().filter(|(id, _)| selection.contains(&id.0)).fold(egui::Rect::NOTHING, |bounds, (_, rect)| bounds.union(*rect));
|
||||
if !bounds.is_finite() {
|
||||
return json!({});
|
||||
|
||||
+403
-148
@@ -1,214 +1,469 @@
|
||||
//! The library: a category tree on the left, the matching nodes as preview tiles (or a list) on
|
||||
//! the right, with search. Drag a tile into the graph, or double-click it to add it next to the
|
||||
//! selection.
|
||||
//! The library: a category tree on the left (Favorites, then the library's categories and
|
||||
//! sub-categories), the matching entries as preview tiles (or a list) on the right, with search and
|
||||
//! filters. Drag an entry into the graph, or double-click it to add it. Entries the open graph
|
||||
//! can't take, and library nodes MaterialCraft doesn't have yet, are dimmed.
|
||||
|
||||
use std::sync::Arc;
|
||||
|
||||
use egui::{Color32, Rect, RichText, Sense, Ui, vec2};
|
||||
use egui_phosphor::regular as icon;
|
||||
use materialcraft_engine::node_library::CATEGORIES;
|
||||
use materialcraft_engine::{LibraryCanvas, LibraryEntry, LibraryItem};
|
||||
|
||||
use crate::MaterialCraftApp;
|
||||
use crate::function::library::FunctionLibraryDrag;
|
||||
mod library_target;
|
||||
use crate::graph::{LibraryDrag, header_color};
|
||||
use crate::i18n::tr;
|
||||
use crate::theme::Tokens;
|
||||
pub(crate) use library_target::LibraryTarget;
|
||||
|
||||
/// The tree: (top level, its sub-categories as full category paths).
|
||||
fn tree() -> Vec<(&'static str, Vec<&'static str>)> {
|
||||
let mut out: Vec<(&'static str, Vec<&'static str>)> = Vec::new();
|
||||
for (cat, _) in materialcraft_engine::nodes::categories() {
|
||||
let top = cat.split('/').next().unwrap_or(cat);
|
||||
match out.iter_mut().find(|(t, _)| *t == top) {
|
||||
Some((_, subs)) => {
|
||||
if cat != top {
|
||||
subs.push(cat);
|
||||
}
|
||||
}
|
||||
None => out.push((top, if cat != top { vec![cat] } else { Vec::new() })),
|
||||
}
|
||||
}
|
||||
out
|
||||
}
|
||||
/// The category key of the Favorites row
|
||||
pub(crate) const FAVORITES: &str = "@favorites";
|
||||
/// Function entries that need more nodes than MaterialCraft has are shown in this color
|
||||
const WARNING: Color32 = Color32::from_rgb(255, 90, 180);
|
||||
|
||||
fn category_icon(top: &str) -> &'static str {
|
||||
match top {
|
||||
"Atomic nodes" => icon::CUBE,
|
||||
/// Choose the icon for a known category or fall back to a folder.
|
||||
fn category_icon(category: &str) -> &'static str {
|
||||
match category {
|
||||
FAVORITES => icon::STAR,
|
||||
"Graph items" => icon::FLOW_ARROW,
|
||||
"Atomic nodes" => icon::CUBE,
|
||||
"FxMap nodes" => icon::SPARKLE,
|
||||
"Function nodes" => icon::FUNCTION,
|
||||
"Texture generators" => icon::DICE_FIVE,
|
||||
"Texture generators/Noises" => icon::CLOUD,
|
||||
"Texture generators/Patterns" => icon::CHECKERBOARD,
|
||||
"Filters" => icon::FADERS,
|
||||
"Filters/Adjustments" => icon::CIRCLE_HALF_TILT,
|
||||
"Filters/Blending" | "Material filters/Blending" => icon::INTERSECT,
|
||||
"Filters/Blurs" => icon::DROP,
|
||||
"Filters/Channels" => icon::STACK,
|
||||
"Filters/Effects" => icon::MAGIC_WAND,
|
||||
"Filters/Normal map" => icon::COMPASS,
|
||||
"Filters/Tiling" => icon::SQUARES_FOUR,
|
||||
"Filters/Transforms" | "Material filters/Transforms" => icon::BOUNDING_BOX,
|
||||
"Material filters" => icon::SPHERE,
|
||||
_ => icon::FOLDER_OPEN,
|
||||
"Material filters/1-click" => icon::CURSOR_CLICK,
|
||||
"Material filters/Effects" => icon::SPARKLE,
|
||||
"Material filters/PBR utilities" => icon::WRENCH,
|
||||
"Material filters/Scan processing" => icon::SCAN,
|
||||
"Mesh-based generators" => icon::POLYGON,
|
||||
"Mesh-based generators/Mask generators" => icon::CUBE_TRANSPARENT,
|
||||
"Mesh-based generators/Weathering" => icon::CLOUD_RAIN,
|
||||
"Mesh-based generators/Utilities" => icon::TOOLBOX,
|
||||
"Spline & Path tools" | "Spline & Path tools/Spline tools" => icon::BEZIER_CURVE,
|
||||
"Spline & Path tools/Path tools" => icon::PATH,
|
||||
"MCF functions" => icon::MATH_OPERATIONS,
|
||||
"Functions" => icon::WAVE_SINE,
|
||||
"3D view" => icon::GLOBE,
|
||||
"3D view/HDRI environments" => icon::GLOBE_HEMISPHERE_WEST,
|
||||
"3D view/HDRI tools" => icon::SUN,
|
||||
"PBR materials" => icon::CIRCLE_HALF,
|
||||
"Values" => icon::HASH,
|
||||
_ => match category.split('/').next().unwrap_or("") {
|
||||
"Function nodes" | "MCF functions" | "Values" => icon::ARROW_SQUARE_OUT,
|
||||
"Functions" => icon::WAVE_SINE,
|
||||
"PBR materials" => icon::CIRCLE,
|
||||
_ => icon::FOLDER_SIMPLE,
|
||||
},
|
||||
}
|
||||
}
|
||||
|
||||
pub fn show(app: &mut MaterialCraftApp, ui: &mut Ui) {
|
||||
match crate::graph::editor_target::EditorTarget::resolve(app) {
|
||||
crate::graph::editor_target::EditorTarget::Function => {
|
||||
crate::function::library::show(app, ui);
|
||||
return;
|
||||
}
|
||||
crate::graph::editor_target::EditorTarget::Pattern => {
|
||||
crate::pattern::library::show(app, ui);
|
||||
return;
|
||||
}
|
||||
crate::graph::editor_target::EditorTarget::Material => {}
|
||||
/// The library's entries for the open session, rebuilt when its packages change
|
||||
fn entries(app: &MaterialCraftApp, ctx: &egui::Context) -> Arc<Vec<LibraryEntry>> {
|
||||
type Cached = (Vec<(String, usize)>, Arc<Vec<LibraryEntry>>);
|
||||
let mut key: Vec<(String, usize)> = vec![(String::new(), Arc::as_ptr(&app.session.library) as usize)];
|
||||
key.extend(
|
||||
app.session.pkg.dependencies.iter().filter(|(path, _)| path.starts_with("sbs://")).map(|(path, package)| (path.clone(), Arc::as_ptr(package) as usize)),
|
||||
);
|
||||
let id = egui::Id::unique("library-entries");
|
||||
if let Some((cached, list)) = ctx.data(|data| data.get_temp::<Arc<Cached>>(id)).as_deref()
|
||||
&& *cached == key
|
||||
{
|
||||
return list.clone();
|
||||
}
|
||||
|
||||
let tk = Tokens::get(ui.ctx());
|
||||
let list = Arc::new(app.session.library_entries());
|
||||
ctx.data_mut(|data| data.insert_temp(id, Arc::new((key, list.clone()))));
|
||||
list
|
||||
}
|
||||
|
||||
/// Draw the shared library tree and search results for the active editor.
|
||||
pub fn show(app: &mut MaterialCraftApp, ui: &mut Ui) {
|
||||
let tokens = Tokens::get(ui.ctx());
|
||||
let target = LibraryTarget::of(app);
|
||||
let all = entries(app, ui.ctx());
|
||||
ui.horizontal(|ui| {
|
||||
ui.label(RichText::new(icon::MAGNIFYING_GLASS).color(tk.text_dim));
|
||||
let r = ui.add(egui::TextEdit::singleline(&mut app.ui.library_search).hint_text(tr("Search")).desired_width((ui.available_width() - 56.0).max(40.0)));
|
||||
crate::widgets::name(&r, egui::Role::SearchInput, "Search the library");
|
||||
if crate::widgets::icon_button(ui, icon::SQUARES_FOUR, tr("Icons"), !app.ui.prefs.library_list, 20.0).clicked() {
|
||||
ui.spacing_mut().item_spacing.x = 2.0;
|
||||
ui.label(RichText::new(icon::MAGNIFYING_GLASS).color(tokens.text_dim));
|
||||
let hint = match target.canvas {
|
||||
LibraryCanvas::Function => tr("Search functions"),
|
||||
LibraryCanvas::Pattern => tr("Search FX-Map nodes"),
|
||||
LibraryCanvas::Any | LibraryCanvas::Material => tr("Search"),
|
||||
};
|
||||
let width = (ui.available_width() - 5.0 * 24.0).max(40.0);
|
||||
let response = ui.add(egui::TextEdit::singleline(&mut app.ui.library_search).hint_text(hint).desired_width(width));
|
||||
crate::widgets::name(&response, egui::Role::SearchInput, "Search the library");
|
||||
filter_menu(app, ui);
|
||||
let selected = app.ui.library_selected.clone();
|
||||
let favorite = selected.as_ref().is_some_and(|id| app.ui.library_favorites.contains(id));
|
||||
let tooltip = if favorite { tr("Remove from Favorites") } else { tr("Add to Favorites") };
|
||||
let star = ui.add_enabled_ui(selected.is_some(), |ui| crate::widgets::icon_button(ui, icon::STAR, tooltip, favorite, 22.0)).inner;
|
||||
if star.clicked()
|
||||
&& let Some(id) = selected
|
||||
{
|
||||
toggle_favorite(app, &id);
|
||||
}
|
||||
if crate::widgets::icon_button(ui, icon::ARROWS_CLOCKWISE, tr("Reload library"), false, 22.0).clicked() {
|
||||
app.run("library.reload", serde_json::json!({}));
|
||||
}
|
||||
if crate::widgets::icon_button(ui, icon::SQUARES_FOUR, tr("Icons"), !app.ui.prefs.library_list, 22.0).clicked() {
|
||||
app.ui.prefs.library_list = false;
|
||||
}
|
||||
if crate::widgets::icon_button(ui, icon::LIST, tr("List"), app.ui.prefs.library_list, 20.0).clicked() {
|
||||
if crate::widgets::icon_button(ui, icon::LIST, tr("List"), app.ui.prefs.library_list, 22.0).clicked() {
|
||||
app.ui.prefs.library_list = true;
|
||||
}
|
||||
});
|
||||
ui.add_space(2.0);
|
||||
let avail = ui.available_size();
|
||||
let tree_w = (avail.x * 0.36).clamp(90.0, 170.0);
|
||||
let available_size = ui.available_size();
|
||||
|
||||
// The tree takes what the tiles leave: one column of tiles in a narrow panel
|
||||
let tree_width = (available_size.x * 0.6).clamp(120.0, 230.0).min(available_size.x - 92.0).max(80.0);
|
||||
let top_down = egui::Layout::top_down(egui::Align::Min);
|
||||
ui.horizontal_top(|ui| {
|
||||
ui.allocate_ui_with_layout(vec2(tree_w, avail.y), top_down, |ui| {
|
||||
egui::ScrollArea::vertical().id_salt("lib-tree").auto_shrink([false, false]).show(ui, |ui| category_tree(app, ui));
|
||||
ui.allocate_ui_with_layout(vec2(tree_width, available_size.y), top_down, |ui| {
|
||||
egui::ScrollArea::vertical().id_salt("lib-tree").auto_shrink([false, false]).show(ui, |ui| category_tree(app, ui, &all));
|
||||
});
|
||||
ui.separator();
|
||||
ui.allocate_ui_with_layout(vec2(ui.available_width(), avail.y), top_down, |ui| {
|
||||
egui::ScrollArea::vertical().id_salt("lib-items").auto_shrink([false, false]).show(ui, |ui| items(app, ui));
|
||||
ui.allocate_ui_with_layout(vec2(ui.available_width(), available_size.y), top_down, |ui| {
|
||||
egui::ScrollArea::vertical().id_salt("lib-items").auto_shrink([false, false]).show(ui, |ui| items(app, ui, &all, &target));
|
||||
});
|
||||
});
|
||||
}
|
||||
|
||||
fn category_tree(app: &mut MaterialCraftApp, ui: &mut Ui) {
|
||||
let tk = Tokens::get(ui.ctx());
|
||||
let mut row = |ui: &mut Ui, text: String, path: &str, indent: f32| {
|
||||
let on = app.ui.library_category == path;
|
||||
let (r, resp) = ui.allocate_exact_size(vec2(ui.available_width(), 20.0), Sense::click());
|
||||
crate::widgets::name(&resp, egui::Role::TreeItem, &text);
|
||||
if on {
|
||||
ui.painter().rect_filled(r, 4.0, tk.row_selected);
|
||||
} else if resp.hovered() {
|
||||
ui.painter().rect_filled(r, 4.0, tk.row_hover);
|
||||
/// Expose availability and canvas filters without changing the selected category.
|
||||
fn filter_menu(app: &mut MaterialCraftApp, ui: &mut Ui) {
|
||||
let filtered = !app.ui.library_show_missing || !app.ui.library_show_other;
|
||||
let response = crate::widgets::icon_button(ui, icon::FUNNEL, tr("Filter"), filtered, 22.0);
|
||||
egui::Popup::menu(&response).show(|ui| {
|
||||
ui.set_min_width(240.0);
|
||||
ui.checkbox(&mut app.ui.library_show_missing, tr("Show nodes not in MaterialCraft yet"));
|
||||
ui.checkbox(&mut app.ui.library_show_other, tr("Show nodes for other graph types"));
|
||||
});
|
||||
}
|
||||
|
||||
/// Toggle an entry while bounding the saved favorites list.
|
||||
fn toggle_favorite(app: &mut MaterialCraftApp, id: &str) {
|
||||
if let Some(index) = app.ui.library_favorites.iter().position(|favorite| favorite == id) {
|
||||
app.ui.library_favorites.remove(index);
|
||||
} else if app.ui.library_favorites.len() < 512 {
|
||||
app.ui.library_favorites.push(id.to_string());
|
||||
}
|
||||
}
|
||||
|
||||
/// One tree row: an optional disclosure triangle, the category icon and its name
|
||||
fn tree_row(app: &mut MaterialCraftApp, ui: &mut Ui, label: &str, category: &str, depth: usize, open: Option<bool>, count: usize) {
|
||||
let tokens = Tokens::get(ui.ctx());
|
||||
let selected = app.ui.library_category == category;
|
||||
let (rect, response) = ui.allocate_exact_size(vec2(ui.available_width(), 20.0), Sense::click());
|
||||
crate::widgets::name(&response, egui::Role::TreeItem, label);
|
||||
let response = response.on_hover_text(crate::i18n::trf("{name}: {count} entries", &[("name", &label), ("count", &count)]));
|
||||
if selected {
|
||||
ui.painter().rect_filled(rect, 4.0, tokens.row_selected);
|
||||
} else if response.hovered() {
|
||||
ui.painter().rect_filled(rect, 4.0, tokens.row_hover);
|
||||
}
|
||||
let indent = 4.0 + depth as f32 * 14.0;
|
||||
let chevron = Rect::from_min_size(rect.min + vec2(indent, 0.0), vec2(14.0, rect.height()));
|
||||
if let Some(open) = open {
|
||||
let symbol = if open { icon::CARET_DOWN } else { icon::CARET_RIGHT };
|
||||
ui.painter().text(chevron.center(), egui::Align2::CENTER_CENTER, symbol, egui::FontId::proportional(11.0), tokens.text_dim);
|
||||
}
|
||||
let x = chevron.right() + 2.0;
|
||||
let color = if selected { tokens.text_strong } else { tokens.text };
|
||||
ui.painter().text(egui::pos2(x + 7.0, rect.center().y), egui::Align2::CENTER_CENTER, category_icon(category), egui::FontId::proportional(13.0), color);
|
||||
let font = if depth == 0 { 12.0 } else { 11.5 };
|
||||
let galley = crate::widgets::elided(ui.painter(), label.to_string(), font, color, rect.right() - x - 22.0);
|
||||
ui.painter().galley(egui::pos2(x + 18.0, rect.center().y - galley.size().y * 0.5), galley, color);
|
||||
if response.clicked() {
|
||||
let on_chevron = response.interact_pointer_pos().is_some_and(|pointer| chevron.contains(pointer));
|
||||
if let Some(open) = open
|
||||
&& (on_chevron || !open || selected)
|
||||
{
|
||||
set_open(app, category, !open);
|
||||
}
|
||||
let g = crate::widgets::elided(ui.painter(), text, 11.5, if on { tk.text_strong } else { tk.text }, r.width() - indent - 4.0);
|
||||
ui.painter().galley(r.left_center() + vec2(indent, -g.size().y * 0.5), g, tk.text);
|
||||
if resp.clicked() {
|
||||
app.ui.library_category = path.to_string();
|
||||
}
|
||||
};
|
||||
row(ui, format!("{} {}", icon::SQUARES_FOUR, tr("All nodes")), "", 4.0);
|
||||
for (top, subs) in tree() {
|
||||
row(ui, format!("{} {}", category_icon(top), tr(top)), top, 4.0);
|
||||
for sub in subs {
|
||||
let name = sub.rsplit('/').next().unwrap_or(sub);
|
||||
row(ui, tr(name).to_string(), sub, 22.0);
|
||||
if !on_chevron {
|
||||
app.ui.library_category = category.to_string();
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Atomic library entries matching the current filter
|
||||
fn entries(app: &MaterialCraftApp) -> Vec<(String, String, &'static str)> {
|
||||
let search = app.ui.library_search.to_ascii_lowercase();
|
||||
/// Persist the expansion state of one category.
|
||||
fn set_open(app: &mut MaterialCraftApp, category: &str, open: bool) {
|
||||
if open {
|
||||
app.ui.library_expanded.insert(category.to_string());
|
||||
} else {
|
||||
app.ui.library_expanded.remove(category);
|
||||
}
|
||||
}
|
||||
|
||||
/// How many entries a category holds, its sub-categories included
|
||||
fn count(entries: &[LibraryEntry], category: &str) -> usize {
|
||||
entries.iter().filter(|entry| entry.category == category || entry.category.strip_prefix(category).is_some_and(|rest| rest.starts_with('/'))).count()
|
||||
}
|
||||
|
||||
/// Draw known categories first, followed by categories supplied by packages.
|
||||
fn category_tree(app: &mut MaterialCraftApp, ui: &mut Ui, entries: &[LibraryEntry]) {
|
||||
ui.spacing_mut().item_spacing.y = 1.0;
|
||||
let favorites = app.ui.library_favorites.len();
|
||||
tree_row(app, ui, tr("Favorites"), FAVORITES, 0, None, favorites);
|
||||
for (top, subs) in CATEGORIES {
|
||||
let open = (!subs.is_empty()).then(|| app.ui.library_expanded.contains(*top));
|
||||
tree_row(app, ui, tr(top), top, 0, open, count(entries, top));
|
||||
if open == Some(true) {
|
||||
for sub in *subs {
|
||||
let category = format!("{top}/{sub}");
|
||||
tree_row(app, ui, tr(sub), &category, 1, None, count(entries, &category));
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// Packages can name categories the tree doesn't have; they go last
|
||||
let mut extra: Vec<&str> = Vec::new();
|
||||
for entry in entries {
|
||||
let top = entry.category.split('/').next().unwrap_or("");
|
||||
if !top.is_empty() && !CATEGORIES.iter().any(|(name, _)| *name == top) && !extra.contains(&top) {
|
||||
extra.push(top);
|
||||
}
|
||||
}
|
||||
for top in extra {
|
||||
tree_row(app, ui, tr(top), top, 0, None, count(entries, top));
|
||||
}
|
||||
}
|
||||
|
||||
/// Matching entries ordered by their displayed names in tiles and list views.
|
||||
pub(crate) fn visible<'a>(app: &MaterialCraftApp, entries: &'a [LibraryEntry], target: &LibraryTarget) -> Vec<&'a LibraryEntry> {
|
||||
let search = app.ui.library_search.trim().to_lowercase();
|
||||
let category = app.ui.library_category.as_str();
|
||||
let cat = if category == "@package" { "" } else { category };
|
||||
let mut out = Vec::new();
|
||||
for d in materialcraft_engine::nodes::catalog() {
|
||||
if d.id == "graph_instance" {
|
||||
continue;
|
||||
}
|
||||
if !(cat.is_empty() || d.category == cat || d.category.starts_with(&format!("{cat}/"))) {
|
||||
continue;
|
||||
}
|
||||
if !(search.is_empty() || d.label.to_ascii_lowercase().contains(&search) || d.id.contains(&search)) {
|
||||
continue;
|
||||
}
|
||||
out.push((d.id.to_string(), d.label.to_string(), d.category));
|
||||
}
|
||||
out
|
||||
let mut visible: Vec<_> = entries
|
||||
.iter()
|
||||
.filter(|entry| app.ui.library_show_missing || entry.missing.is_none())
|
||||
.filter(|entry| app.ui.library_show_other || entry.canvas == LibraryCanvas::Any || entry.canvas == target.canvas)
|
||||
.filter(|entry| {
|
||||
if !search.is_empty() {
|
||||
return tr(&entry.label).to_lowercase().contains(&search) || entry.id.to_lowercase().contains(&search);
|
||||
}
|
||||
|
||||
match category {
|
||||
"" => true,
|
||||
FAVORITES => app.ui.library_favorites.contains(&entry.id),
|
||||
category => entry.category == category || entry.category.strip_prefix(category).is_some_and(|rest| rest.starts_with('/')),
|
||||
}
|
||||
})
|
||||
.collect();
|
||||
visible.sort_by_cached_key(|entry| (tr(&entry.label).to_lowercase(), entry.id.as_str()));
|
||||
visible
|
||||
}
|
||||
|
||||
fn items(app: &mut MaterialCraftApp, ui: &mut Ui) {
|
||||
let tk = Tokens::get(ui.ctx());
|
||||
/// Draw matching entries and dispatch compatible additions or favorite changes.
|
||||
fn items(app: &mut MaterialCraftApp, ui: &mut Ui, entries: &[LibraryEntry], target: &LibraryTarget) {
|
||||
let tokens = Tokens::get(ui.ctx());
|
||||
let ctx = ui.ctx().clone();
|
||||
let list = entries(app);
|
||||
let list = visible(app, entries, target);
|
||||
if list.is_empty() {
|
||||
ui.label(RichText::new(tr("Nothing matches")).color(tk.text_dim));
|
||||
let text = match app.ui.library_category.as_str() {
|
||||
FAVORITES if app.ui.library_search.trim().is_empty() => tr("Select an entry and click the star to add it to Favorites"),
|
||||
category if app.ui.library_search.trim().is_empty() && !category.is_empty() => tr("Nothing in this category yet"),
|
||||
_ => tr("Nothing matches"),
|
||||
};
|
||||
ui.label(RichText::new(text).color(tokens.text_dim));
|
||||
return;
|
||||
}
|
||||
|
||||
let as_list = app.ui.prefs.library_list;
|
||||
let tile = vec2(78.0, 98.0);
|
||||
let cols = if as_list { 1 } else { ((ui.available_width() + 4.0) / (tile.x + 4.0)).floor().max(1.0) as usize };
|
||||
let tile = vec2(78.0, 100.0);
|
||||
let columns = if as_list { 1 } else { ((ui.available_width() + 4.0) / (tile.x + 4.0)).floor().max(1.0) as usize };
|
||||
let mut add = None;
|
||||
for chunk in list.chunks(cols) {
|
||||
let mut favorite = None;
|
||||
for chunk in list.chunks(columns) {
|
||||
ui.horizontal(|ui| {
|
||||
ui.spacing_mut().item_spacing = vec2(4.0, 4.0);
|
||||
for (id, label, cat) in chunk {
|
||||
for entry in chunk {
|
||||
let size = if as_list { vec2(ui.available_width(), 26.0) } else { tile };
|
||||
let (r, resp) = ui.allocate_exact_size(size, Sense::click_and_drag());
|
||||
crate::widgets::name(&resp, egui::Role::ListItem, label);
|
||||
if resp.hovered() {
|
||||
ui.painter().rect_filled(r, 6.0, tk.row_hover);
|
||||
let (rect, response) = ui.allocate_exact_size(size, Sense::click_and_drag());
|
||||
crate::widgets::name(&response, egui::Role::ListItem, &entry.label);
|
||||
let takes = target.takes(entry);
|
||||
let selected = app.ui.library_selected.as_deref() == Some(entry.id.as_str());
|
||||
if selected {
|
||||
ui.painter().rect_filled(rect, 6.0, tokens.row_selected);
|
||||
} else if response.hovered() {
|
||||
ui.painter().rect_filled(rect, 6.0, tokens.row_hover);
|
||||
}
|
||||
let tex = app.thumbs.library(&ctx, id);
|
||||
let img_rect = if as_list {
|
||||
Rect::from_min_size(r.min + vec2(2.0, 2.0), vec2(22.0, 22.0))
|
||||
let fade = if takes { 1.0 } else { 0.4 };
|
||||
let image = if as_list {
|
||||
Rect::from_min_size(rect.min + vec2(2.0, 2.0), vec2(22.0, 22.0))
|
||||
} else {
|
||||
Rect::from_min_size(r.min + vec2(5.0, 4.0), vec2(68.0, 68.0))
|
||||
Rect::from_min_size(rect.min + vec2(5.0, 4.0), vec2(68.0, 68.0))
|
||||
};
|
||||
match tex {
|
||||
Some(t) => {
|
||||
ui.painter().image(t, img_rect, Rect::from_min_max(egui::Pos2::ZERO, egui::pos2(1.0, 1.0)), Color32::WHITE);
|
||||
}
|
||||
None => {
|
||||
ui.painter().rect_filled(img_rect, 4.0, header_color(id).gamma_multiply(0.7));
|
||||
ui.painter().text(
|
||||
img_rect.center(),
|
||||
egui::Align2::CENTER_CENTER,
|
||||
icon::CUBE,
|
||||
egui::FontId::proportional(img_rect.height() * 0.4),
|
||||
Color32::WHITE,
|
||||
);
|
||||
}
|
||||
}
|
||||
// The category color as a strip, like the node headers.
|
||||
let strip = Rect::from_min_size(img_rect.left_bottom() - vec2(0.0, 3.0), vec2(img_rect.width(), 3.0));
|
||||
ui.painter().rect_filled(strip, 0.0, header_color(id));
|
||||
preview(app, ui, &ctx, entry, image, fade);
|
||||
let color = if entry.warning.is_some() { WARNING } else { tokens.text };
|
||||
let color = color.gamma_multiply(if takes { 1.0 } else { 0.55 });
|
||||
if as_list {
|
||||
let g = crate::widgets::elided(ui.painter(), label.clone(), 11.5, tk.text, r.width() - 34.0);
|
||||
ui.painter().galley(r.left_center() + vec2(30.0, -g.size().y * 0.5), g, tk.text);
|
||||
let galley = crate::widgets::elided(ui.painter(), entry.label.clone(), 11.5, color, rect.width() - 34.0);
|
||||
ui.painter().galley(rect.left_center() + vec2(30.0, -galley.size().y * 0.5), galley, color);
|
||||
} else {
|
||||
let galley = ui.painter().layout(label.clone(), egui::FontId::proportional(10.5), tk.text, tile.x - 4.0);
|
||||
let pos = egui::pos2(r.center().x - galley.size().x * 0.5, img_rect.bottom() + 3.0);
|
||||
ui.painter().galley(pos, galley, tk.text);
|
||||
let galley = ui.painter().layout(entry.label.clone(), egui::FontId::proportional(10.5), color, tile.x - 4.0);
|
||||
let pos = egui::pos2(rect.center().x - galley.size().x * 0.5, image.bottom() + 3.0);
|
||||
ui.painter().with_clip_rect(rect).galley(pos, galley, color);
|
||||
}
|
||||
let resp = resp.on_hover_text(format!("{label}\n{cat}"));
|
||||
if resp.drag_started() {
|
||||
egui::DragAndDrop::set_payload(&ctx, LibraryDrag(id.clone()));
|
||||
if app.ui.library_favorites.contains(&entry.id) {
|
||||
ui.painter().text(
|
||||
rect.right_top() + vec2(-8.0, 9.0),
|
||||
egui::Align2::CENTER_CENTER,
|
||||
icon::STAR,
|
||||
egui::FontId::proportional(10.0),
|
||||
tokens.accent,
|
||||
);
|
||||
}
|
||||
if resp.double_clicked() {
|
||||
add = Some(id.clone());
|
||||
|
||||
let mut tip = format!("{}\n{}", entry.label, tr(&entry.category));
|
||||
if !entry.description.is_empty() {
|
||||
tip.push_str(&format!("\n\n{}", entry.description));
|
||||
}
|
||||
if let Some(reason) = target.refusal(entry).or_else(|| entry.warning.clone()) {
|
||||
tip.push_str(&format!("\n\n{reason}"));
|
||||
}
|
||||
let response = response.on_hover_text(tip);
|
||||
if response.clicked() || response.secondary_clicked() {
|
||||
app.ui.library_selected = Some(entry.id.clone());
|
||||
}
|
||||
if takes && response.drag_started() {
|
||||
drag(&ctx, entry);
|
||||
}
|
||||
if takes && response.double_clicked() {
|
||||
add = Some((*entry).clone());
|
||||
}
|
||||
response.context_menu(|ui| {
|
||||
if ui.add_enabled(takes, egui::Button::new(tr("Add to graph"))).clicked() {
|
||||
add = Some((*entry).clone());
|
||||
ui.close();
|
||||
}
|
||||
let label = if app.ui.library_favorites.contains(&entry.id) { tr("Remove from Favorites") } else { tr("Add to Favorites") };
|
||||
if ui.button(label).clicked() {
|
||||
favorite = Some(entry.id.clone());
|
||||
ui.close();
|
||||
}
|
||||
});
|
||||
}
|
||||
});
|
||||
}
|
||||
if let Some(id) = add {
|
||||
crate::graph::add_node_near_selection(app, &id);
|
||||
if let Some(id) = favorite {
|
||||
toggle_favorite(app, &id);
|
||||
}
|
||||
if let Some(entry) = add {
|
||||
add_entry(app, &entry);
|
||||
}
|
||||
}
|
||||
|
||||
/// The entry's thumbnail: a cooked preview for native nodes, its category's icon otherwise
|
||||
fn preview(app: &mut MaterialCraftApp, ui: &Ui, ctx: &egui::Context, entry: &LibraryEntry, rect: Rect, fade: f32) {
|
||||
let painter = ui.painter();
|
||||
let (texture, color) = match &entry.item {
|
||||
LibraryItem::Node { def } if entry.missing.is_none() && def != "dot" => (app.thumbs.library(ctx, def), header_color(def)),
|
||||
_ => (None, category_color(&entry.category)),
|
||||
};
|
||||
match texture {
|
||||
Some(texture) => {
|
||||
painter.image(texture, rect, Rect::from_min_max(egui::Pos2::ZERO, egui::pos2(1.0, 1.0)), Color32::WHITE.gamma_multiply(fade));
|
||||
}
|
||||
None => {
|
||||
painter.rect_filled(rect, 4.0, color.gamma_multiply(0.7 * fade));
|
||||
let symbol = match &entry.item {
|
||||
LibraryItem::Comment => icon::CHAT_TEXT,
|
||||
LibraryItem::Frame => icon::FRAME_CORNERS,
|
||||
LibraryItem::Pin => icon::PUSH_PIN,
|
||||
LibraryItem::Node { def } if def == "dot" => icon::DOT_OUTLINE,
|
||||
_ => category_icon(&entry.category),
|
||||
};
|
||||
painter.text(
|
||||
rect.center(),
|
||||
egui::Align2::CENTER_CENTER,
|
||||
symbol,
|
||||
egui::FontId::proportional(rect.height() * 0.42),
|
||||
Color32::WHITE.gamma_multiply(fade),
|
||||
);
|
||||
}
|
||||
}
|
||||
let strip = Rect::from_min_size(rect.left_bottom() - vec2(0.0, 3.0), vec2(rect.width(), 3.0));
|
||||
painter.rect_filled(strip, 0.0, color.gamma_multiply(fade));
|
||||
if entry.missing.is_some() && rect.height() > 30.0 {
|
||||
let badge = Rect::from_center_size(rect.right_top() + vec2(-9.0, 9.0), vec2(14.0, 14.0));
|
||||
painter.circle_filled(badge.center(), 7.0, Color32::from_black_alpha(160));
|
||||
painter.text(badge.center(), egui::Align2::CENTER_CENTER, icon::CLOCK, egui::FontId::proportional(10.0), Color32::WHITE);
|
||||
}
|
||||
}
|
||||
|
||||
/// Choose the preview accent for an entry category.
|
||||
fn category_color(category: &str) -> Color32 {
|
||||
match category.split('/').next().unwrap_or("") {
|
||||
"Graph items" | "Atomic nodes" | "FxMap nodes" => Color32::from_rgb(0x5c, 0x62, 0x6e),
|
||||
"Function nodes" | "Functions" | "MCF functions" | "Values" => Color32::from_rgb(0x4a, 0x5a, 0x8a),
|
||||
"Texture generators" if category.ends_with("Patterns") => Color32::from_rgb(0xb3, 0x5a, 0x2c),
|
||||
"Texture generators" => Color32::from_rgb(0xa8, 0x3c, 0x34),
|
||||
"Filters" => Color32::from_rgb(0x3b, 0x7f, 0x4c),
|
||||
"Material filters" | "PBR materials" => Color32::from_rgb(0x3a, 0x66, 0xb0),
|
||||
"Mesh-based generators" => Color32::from_rgb(0x7a, 0x4f, 0x9e),
|
||||
"Spline & Path tools" => Color32::from_rgb(0x2f, 0x86, 0x8a),
|
||||
"3D view" => Color32::from_rgb(0x8a, 0x76, 0x2f),
|
||||
_ => Color32::from_rgb(0x5c, 0x62, 0x6e),
|
||||
}
|
||||
}
|
||||
|
||||
/// Create the payload accepted by the destination canvas.
|
||||
fn drag(ctx: &egui::Context, entry: &LibraryEntry) {
|
||||
match &entry.item {
|
||||
LibraryItem::Operation { operation } => egui::DragAndDrop::set_payload(ctx, FunctionLibraryDrag::Operation(operation.clone())),
|
||||
LibraryItem::FunctionInstance { package, graph } => {
|
||||
egui::DragAndDrop::set_payload(ctx, FunctionLibraryDrag::Instance { package: package.clone(), graph: graph.clone() })
|
||||
}
|
||||
LibraryItem::Pattern { .. } => {}
|
||||
_ => egui::DragAndDrop::set_payload(ctx, LibraryDrag(entry.id.clone())),
|
||||
}
|
||||
}
|
||||
|
||||
/// Add `entry` to the open graph: native nodes next to the selection, the rest in the view
|
||||
pub(crate) fn add_entry(app: &mut MaterialCraftApp, entry: &LibraryEntry) {
|
||||
if entry.canvas == LibraryCanvas::Any {
|
||||
let target = crate::annotation::target(app);
|
||||
crate::annotation::activate(app, target);
|
||||
let camera = crate::annotation::camera(app);
|
||||
let at = [camera.pan[0] + app.graph.view.width() * 0.5 / camera.zoom, camera.pan[1] + app.graph.view.height() * 0.5 / camera.zoom];
|
||||
if let Some(result) = app.run("library.add", serde_json::json!({"entry": entry.id, "at": at, "snapToGrid": app.ui.prefs.snap_to_grid})) {
|
||||
let id = result["result"]["id"].as_u64().and_then(|id| u32::try_from(id).ok());
|
||||
let selection = if app.session.annotation_selection.is_some() { Vec::new() } else { id.into_iter().collect() };
|
||||
if let Some(editor) = &mut app.function_editor {
|
||||
editor.selection = selection.clone();
|
||||
editor.selected_wires.clear();
|
||||
}
|
||||
if let Some(editor) = &mut app.pattern_editor {
|
||||
editor.selection = selection;
|
||||
editor.selected_wires.clear();
|
||||
}
|
||||
}
|
||||
return;
|
||||
}
|
||||
match &entry.item {
|
||||
LibraryItem::Operation { operation } => crate::function::library::add(app, &FunctionLibraryDrag::Operation(operation.clone())),
|
||||
LibraryItem::FunctionInstance { package, graph } => {
|
||||
crate::function::library::add(app, &FunctionLibraryDrag::Instance { package: package.clone(), graph: graph.clone() })
|
||||
}
|
||||
LibraryItem::Pattern { kind } => crate::pattern::library::add(app, *kind),
|
||||
LibraryItem::Node { def } => crate::graph::add_node_near_selection(app, def),
|
||||
_ => crate::graph::add_entry_in_view(app, &entry.id),
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn open_package_graphs_are_explorer_resources_not_library_entries() {
|
||||
let mut app = MaterialCraftApp::headless(materialcraft_engine::new_session(), crate::UiState::default());
|
||||
let mut graph = materialcraft_engine::core::Graph::new("Reusable source");
|
||||
graph.add_node("output", [0.0; 2]);
|
||||
app.session.pkg.graphs.push(graph);
|
||||
app.ui.library_search = "Reusable source".into();
|
||||
assert!(entries(&app).is_empty());
|
||||
app.ui.library_search.clear();
|
||||
app.ui.library_category = "@package".into();
|
||||
assert!(entries(&app).iter().any(|entry| entry.0 == "uniform"));
|
||||
}
|
||||
}
|
||||
#[path = "library.test.rs"]
|
||||
mod tests;
|
||||
@@ -0,0 +1,167 @@
|
||||
use super::*;
|
||||
use materialcraft_engine::core::NodeId;
|
||||
use serde_json::json;
|
||||
|
||||
/// Create a headless material editor for library interactions.
|
||||
fn app() -> MaterialCraftApp {
|
||||
MaterialCraftApp::headless(materialcraft_engine::new_session(), crate::UiState::default())
|
||||
}
|
||||
|
||||
/// Collect labels visible under the current library filter.
|
||||
fn labels(app: &MaterialCraftApp) -> Vec<String> {
|
||||
let entries = app.session.library_entries();
|
||||
visible(app, &entries, &LibraryTarget::of(app)).into_iter().map(|entry| entry.label.clone()).collect()
|
||||
}
|
||||
|
||||
/// Open project graphs remain separate from reusable library entries.
|
||||
#[test]
|
||||
fn open_package_graphs_are_explorer_resources_not_library_entries() {
|
||||
let mut app = app();
|
||||
let mut graph = materialcraft_engine::core::Graph::new("Reusable source");
|
||||
graph.add_node("output", [0.0; 2]);
|
||||
app.session.pkg.graphs.push(graph);
|
||||
app.ui.library_search = "Reusable source".into();
|
||||
assert!(labels(&app).is_empty());
|
||||
app.ui.library_search.clear();
|
||||
app.ui.library_category = "@package".into();
|
||||
assert!(labels(&app).is_empty(), "an unknown category lists nothing");
|
||||
app.ui.library_category.clear();
|
||||
assert!(labels(&app).iter().any(|label| label == "Uniform color"));
|
||||
}
|
||||
|
||||
/// Category filtering includes descendants and favorite toggles update membership.
|
||||
#[test]
|
||||
fn categories_include_their_sub_categories_and_favorites_follow_the_star() {
|
||||
let mut app = app();
|
||||
app.ui.library_category = "Functions".into();
|
||||
let functions = labels(&app);
|
||||
app.ui.library_category = "Functions/Constant".into();
|
||||
let constants = labels(&app);
|
||||
assert!(!constants.is_empty() && constants.len() < functions.len());
|
||||
assert!(constants.iter().all(|label| functions.contains(label)));
|
||||
|
||||
app.ui.library_category = FAVORITES.into();
|
||||
assert!(labels(&app).is_empty());
|
||||
toggle_favorite(&mut app, "node:blur");
|
||||
toggle_favorite(&mut app, "sbs://functions.sbs#Functions/Math/Pi");
|
||||
assert_eq!(labels(&app), ["Blur", "Pi"]);
|
||||
toggle_favorite(&mut app, "node:blur");
|
||||
assert_eq!(labels(&app), ["Pi"]);
|
||||
}
|
||||
|
||||
/// Tiles and list rows stay alphabetical across categories, favorites and search.
|
||||
#[test]
|
||||
fn library_previews_are_alphabetical_in_every_view() {
|
||||
let mut app = app();
|
||||
for (category, search) in [("", ""), ("Graph items", ""), ("Atomic nodes", ""), ("Functions", ""), ("", "uniform")] {
|
||||
app.ui.library_category = category.into();
|
||||
app.ui.library_search = search.into();
|
||||
let found = labels(&app);
|
||||
assert!(found.len() > 1);
|
||||
let keys: Vec<_> = found.iter().map(|label| tr(label).to_lowercase()).collect();
|
||||
assert!(keys.windows(2).all(|pair| pair[0] <= pair[1]), "{category}/{search}: {found:?}");
|
||||
}
|
||||
|
||||
app.ui.library_show_missing = false;
|
||||
app.ui.library_show_other = false;
|
||||
let entries = app.session.library_entries();
|
||||
let target = LibraryTarget::of(&app);
|
||||
assert!(visible(&app, &entries, &target).iter().all(|entry| target.takes(entry)));
|
||||
}
|
||||
|
||||
/// The FX-Map category contains its three processing nodes, without a Dot tile.
|
||||
#[test]
|
||||
fn fx_map_library_does_not_list_dot() {
|
||||
let mut app = app();
|
||||
app.ui.library_category = "FxMap nodes".into();
|
||||
let mut found = labels(&app);
|
||||
found.sort();
|
||||
assert_eq!(found, ["Iterate", "Quadrant", "Switch"]);
|
||||
}
|
||||
|
||||
/// Both processor canvases accept samplers and keep material operations separate.
|
||||
#[test]
|
||||
fn processor_functions_take_operations_their_canvas_allows() {
|
||||
for definition in ["pixel_processor", "value_processor"] {
|
||||
let mut app = app();
|
||||
let owner = NodeId(app.run("graph.node.add", json!({"def": definition})).unwrap()["id"].as_u64().unwrap());
|
||||
app.function_editor =
|
||||
Some(crate::function::FunctionEditor::new(app.session.graph, owner, crate::function::FunctionTarget::Parameter("function".into())));
|
||||
let target = LibraryTarget::of(&app);
|
||||
let entries = app.session.library_entries();
|
||||
let find = |id: &str| entries.iter().find(|entry| entry.id == id).unwrap();
|
||||
|
||||
for id in ["function:add", "function:samplelum", "function:samplecol", "sbs://functions.sbs#Functions/Math/Pi"] {
|
||||
assert!(target.takes(find(id)), "{definition}: {id}");
|
||||
}
|
||||
assert!(!target.takes(find("node:blur")));
|
||||
assert!(target.refusal(find("node:blur")).is_some());
|
||||
}
|
||||
}
|
||||
|
||||
/// Known categories have icons and compatible entries can be inserted.
|
||||
#[test]
|
||||
fn every_tree_category_has_an_icon_and_double_click_adds() {
|
||||
for (top, subs) in CATEGORIES {
|
||||
assert_ne!(category_icon(top), icon::FOLDER_SIMPLE, "{top}");
|
||||
for sub in *subs {
|
||||
assert_ne!(category_icon(&format!("{top}/{sub}")), icon::FOLDER_SIMPLE, "{top}/{sub}");
|
||||
}
|
||||
}
|
||||
|
||||
let mut app = app();
|
||||
let before = app.session.graph().unwrap().nodes.len();
|
||||
let entries = app.session.library_entries();
|
||||
|
||||
// A material graph takes the Blur node, not a function
|
||||
for id in ["node:blur", "sbs://functions.sbs#Functions/Math/Pi"] {
|
||||
let entry = entries.iter().find(|entry| entry.id == id).unwrap();
|
||||
if LibraryTarget::of(&app).takes(entry) {
|
||||
add_entry(&mut app, entry);
|
||||
}
|
||||
}
|
||||
assert_eq!(app.session.graph().unwrap().nodes.len(), before + 1, "only the entry the graph takes is added");
|
||||
let comments = app.session.graph().unwrap().comments.len();
|
||||
add_entry(&mut app, entries.iter().find(|entry| entry.id == "item:comment").unwrap());
|
||||
assert_eq!(app.session.graph().unwrap().comments.len(), comments + 1);
|
||||
}
|
||||
|
||||
/// Dot is a graph item rather than a second entry among function operations.
|
||||
#[test]
|
||||
fn function_control_library_does_not_list_dot() {
|
||||
let mut app = app();
|
||||
app.ui.library_category = "Function nodes/Control".into();
|
||||
assert!(!labels(&app).iter().any(|label| label.to_lowercase().contains("dot")));
|
||||
}
|
||||
|
||||
/// The shared Graph items remain available when hiding entries for other canvas types.
|
||||
#[test]
|
||||
fn graph_items_are_available_and_insertable_in_every_editor() {
|
||||
for kind in ["material", "function", "pixel_processor", "value_processor", "fx_map"] {
|
||||
let mut app = app();
|
||||
if kind == "function" {
|
||||
app.run("file.new", json!({"kind": "function"})).unwrap();
|
||||
app.function_editor = Some(crate::function::FunctionEditor::standalone(app.session.graph));
|
||||
} else if kind != "material" {
|
||||
let owner = NodeId(app.run("graph.node.add", json!({"def": kind})).unwrap()["id"].as_u64().unwrap());
|
||||
if kind == "fx_map" {
|
||||
app.pattern_editor = Some(crate::pattern::PatternEditor::new(app.session.graph, owner));
|
||||
} else {
|
||||
app.function_editor =
|
||||
Some(crate::function::FunctionEditor::new(app.session.graph, owner, crate::function::FunctionTarget::Parameter("function".into())));
|
||||
}
|
||||
}
|
||||
app.graph.view = egui::Rect::from_min_size(egui::Pos2::ZERO, egui::vec2(800.0, 600.0));
|
||||
app.ui.library_category = "Graph items".into();
|
||||
app.ui.library_show_other = false;
|
||||
assert_eq!(labels(&app), ["Comment", "Dot node", "Frame", "Pin"], "{kind}");
|
||||
let entries = app.session.library_entries();
|
||||
let target = LibraryTarget::of(&app);
|
||||
for entry in entries.iter().filter(|entry| entry.category == "Graph items") {
|
||||
assert!(target.takes(entry), "{kind}: {}", entry.label);
|
||||
add_entry(&mut app, entry);
|
||||
}
|
||||
let items = crate::annotation::target(&app).items(&app.session).unwrap();
|
||||
assert_eq!((items.comments.len(), items.frames.len(), items.pins.len()), (1, 1, 1), "{kind}");
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,48 @@
|
||||
use crate::{MaterialCraftApp, graph::editor_target::EditorTarget, i18n::tr};
|
||||
use materialcraft_engine::{LibraryCanvas, LibraryEntry, LibraryItem};
|
||||
|
||||
/// The graph the library adds to, and which native function operations it can take
|
||||
pub(crate) struct LibraryTarget {
|
||||
pub(super) canvas: LibraryCanvas,
|
||||
operations: Vec<&'static str>,
|
||||
}
|
||||
|
||||
impl LibraryTarget {
|
||||
/// Resolve the active editor and its permitted operations.
|
||||
pub(crate) fn of(app: &MaterialCraftApp) -> LibraryTarget {
|
||||
match EditorTarget::resolve(app) {
|
||||
EditorTarget::Material => LibraryTarget { canvas: LibraryCanvas::Material, operations: Vec::new() },
|
||||
EditorTarget::Pattern => LibraryTarget { canvas: LibraryCanvas::Pattern, operations: Vec::new() },
|
||||
EditorTarget::Function => LibraryTarget { canvas: LibraryCanvas::Function, operations: crate::function::library::available_operations(app) },
|
||||
}
|
||||
}
|
||||
|
||||
/// Whether `entry` can go into the open graph now
|
||||
pub(crate) fn takes(&self, entry: &LibraryEntry) -> bool {
|
||||
entry.missing.is_none()
|
||||
&& (entry.canvas == LibraryCanvas::Any || entry.canvas == self.canvas)
|
||||
&& match &entry.item {
|
||||
LibraryItem::Operation { operation } => self.operations.contains(&operation.as_str()),
|
||||
_ => true,
|
||||
}
|
||||
}
|
||||
|
||||
/// Why `entry` can't go into the open graph, when it can't
|
||||
pub(super) fn refusal(&self, entry: &LibraryEntry) -> Option<String> {
|
||||
if let Some(missing) = &entry.missing {
|
||||
return Some(missing.clone());
|
||||
}
|
||||
|
||||
if entry.canvas != LibraryCanvas::Any && entry.canvas != self.canvas {
|
||||
return Some(
|
||||
match entry.canvas {
|
||||
LibraryCanvas::Any | LibraryCanvas::Material => tr("Open a graph to add this"),
|
||||
LibraryCanvas::Function => tr("Open a function graph or a processor's function to add this"),
|
||||
LibraryCanvas::Pattern => tr("Open an FX-Map to add this"),
|
||||
}
|
||||
.to_string(),
|
||||
);
|
||||
}
|
||||
(!self.takes(entry)).then(|| tr("This function can't use this node").to_string())
|
||||
}
|
||||
}
|
||||
@@ -147,6 +147,21 @@ impl MaterialCraftApp {
|
||||
|
||||
/// Run an engine command, reporting errors as toasts. Returns the result on success
|
||||
pub fn run(&mut self, id: &str, mut params: Value) -> Option<Value> {
|
||||
if id.starts_with("graph.annotation.")
|
||||
|| id.starts_with("graph.frame.")
|
||||
|| id.starts_with("graph.comment.")
|
||||
|| id.starts_with("graph.pin.")
|
||||
|| id == "library.add"
|
||||
{
|
||||
if params.is_null() {
|
||||
params = serde_json::json!({});
|
||||
}
|
||||
if let (Some(parameters), Some(target)) = (params.as_object_mut(), self.graph.annotation_target.parameters().as_object()) {
|
||||
for (name, value) in target {
|
||||
parameters.entry(name).or_insert_with(|| value.clone());
|
||||
}
|
||||
}
|
||||
}
|
||||
if id.starts_with("file.")
|
||||
|| id.starts_with("package.")
|
||||
|| matches!(id, "graph.open" | "graph.delete" | "graph.duplicate" | "folder.remove" | "explorer.paste" | "edit.undo" | "edit.redo")
|
||||
@@ -186,6 +201,14 @@ impl MaterialCraftApp {
|
||||
|
||||
match cook::execute_guarded(&mut self.session, id, ¶ms) {
|
||||
Ok(v) => {
|
||||
if matches!(id, "graph.pin.add" | "library.add")
|
||||
&& let Some(materialcraft_engine::AnnotationSelection::Pin(pin)) = self.session.annotation_selection
|
||||
{
|
||||
self.graph.pin_description_focus = Some(pin);
|
||||
self.inspected_folder = None;
|
||||
self.inspected_graph = None;
|
||||
self.ui.dock.focus(docking::Panel::Properties);
|
||||
}
|
||||
if id == "view.previewSize" {
|
||||
self.ui.prefs.preview_size = self.session.preview_size.unwrap_or(0);
|
||||
}
|
||||
@@ -384,6 +407,7 @@ impl MaterialCraftApp {
|
||||
|
||||
/// Draw the whole window into `ui`
|
||||
pub fn draw(&mut self, ui: &mut egui::Ui) {
|
||||
crate::annotation::activate(self, crate::annotation::target(self));
|
||||
if !self.fonts_ready {
|
||||
self.fonts_ready = true;
|
||||
return;
|
||||
@@ -395,6 +419,7 @@ impl MaterialCraftApp {
|
||||
menus::menu_bar(self, ui);
|
||||
toolbar::main_toolbar(self, ui);
|
||||
toolbar::status_bar(self, ui);
|
||||
self.ui.explorer.hovered = false;
|
||||
egui::CentralPanel::default().frame(egui::Frame::NONE.fill(theme::Tokens::get(&ctx).chrome)).show(ui, |ui| docking::show(self, ui));
|
||||
windows::show(self, &ctx);
|
||||
#[cfg(not(target_arch = "wasm32"))]
|
||||
|
||||
@@ -5,6 +5,20 @@ mod lib_tests {
|
||||
use materialcraft_engine::sample_session;
|
||||
use serde_json::json;
|
||||
|
||||
/// A frame which does not draw Explorer clears hover state left by its previous frame.
|
||||
#[test]
|
||||
fn review_hidden_explorer_drawing_clears_hover() {
|
||||
let mut app = MaterialCraftApp::headless(sample_session(), UiState::default());
|
||||
app.fonts_ready = true;
|
||||
app.ui.explorer.hovered = true;
|
||||
app.ui.dock.close(crate::docking::Panel::Explorer);
|
||||
let context = egui::Context::default();
|
||||
|
||||
context.run_ui(egui::RawInput::default(), |ui| app.draw(ui)).textures_delta.clear();
|
||||
|
||||
assert!(!app.ui.explorer.hovered);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn run_reports_errors_as_toasts_and_keeps_the_session() {
|
||||
let mut app = MaterialCraftApp::headless(sample_session(), UiState::default());
|
||||
|
||||
+175
-42
@@ -1,6 +1,7 @@
|
||||
//! Menu actions and shortcuts share stable command ids
|
||||
|
||||
use craft_keymap::{Active, Bindable, Binding, Chord, Keymap, Platform, Scope, Scopes};
|
||||
use egui::class::HasClasses as _;
|
||||
use serde_json::Value;
|
||||
|
||||
use crate::MaterialCraftApp;
|
||||
@@ -27,19 +28,59 @@ pub const TOP: [&str; 5] = ["File", "Edit", "Tools", "Windows", "Help"];
|
||||
pub(crate) const EXPLORER_NEW: &[(&str, &str)] = &[("Graph", "ui.newGraph"), ("Function Graph", "ui.newFunctionGraph"), ("Folder", "folder.create")];
|
||||
pub(crate) const EXPLORER_IMPORT: &[(&str, &str)] = &[("Bitmap", "file.importBitmap"), ("Vector graphics", "file.importVector")];
|
||||
pub(crate) const EXPLORER_RESOURCE: &[(&str, &str)] = &[("Add to graph", "graph.resource.add")];
|
||||
pub(crate) const EXPLORER_PACKAGE: &[(&str, &str)] = &[
|
||||
("Reload", "file.reload"),
|
||||
("Save", "file.save"),
|
||||
("Save As", "file.saveAs"),
|
||||
("Save A Copy As", "file.saveCopyAs"),
|
||||
("Copy", "explorer.copy"),
|
||||
("Paste", "explorer.paste"),
|
||||
("Close", "package.close"),
|
||||
pub(crate) use crate::explorer::explorer_row::ExplorerRow;
|
||||
use ExplorerRow::{Item, Separator, Sub};
|
||||
|
||||
/// Linking keeps a resource outside the package; MaterialCraft only embeds resources so far
|
||||
pub(crate) const EXPLORER_LINK: &[(&str, &str)] = &[("Bitmap", ""), ("Vector graphics", "")];
|
||||
pub(crate) const EXPLORER_SEND_TO: &[(&str, &str)] = &[("TextureCraft", "file.sendToTextureCraft")];
|
||||
/// Explorer actions that wrap engine commands or the operating system: computing every output,
|
||||
/// showing the package file and opening the packages it depends on
|
||||
pub(crate) const EXPLORER_COMPUTE: &str = "ui.explorer.computeOutputs";
|
||||
pub(crate) const EXPLORER_SHOW_IN_FOLDER: &str = "ui.explorer.showInFolder";
|
||||
pub(crate) const EXPLORER_OPEN_DEPENDENCIES: &str = "ui.explorer.openDependencies";
|
||||
pub(crate) const EXPLORER_VIEW_OUTPUTS: &str = "ui.explorer.viewOutputs";
|
||||
pub(crate) const EXPLORER_EXPORT_OUTPUTS: &str = "ui.explorer.exportOutputs";
|
||||
pub(crate) const EXPLORER_PACKAGE: &[ExplorerRow] = &[
|
||||
Sub("New", EXPLORER_NEW),
|
||||
Sub("Import", EXPLORER_IMPORT),
|
||||
Sub("Link", EXPLORER_LINK),
|
||||
Separator,
|
||||
Item("Reload", "file.reload", None),
|
||||
Item("Save", "file.save", Some("Ctrl+S")),
|
||||
Item("Save as...", "file.saveAs", Some("Ctrl+Shift+S")),
|
||||
Item("Save a copy as...", "file.saveCopyAs", None),
|
||||
Separator,
|
||||
Item("Export material...", "file.exportMaterial", None),
|
||||
Item("Export with dependencies...", "", None),
|
||||
Sub("Send to", EXPLORER_SEND_TO),
|
||||
Separator,
|
||||
Item("Copy", "explorer.copy", None),
|
||||
Item("Paste", "explorer.paste", None),
|
||||
Item("Close package", "package.close", None),
|
||||
Separator,
|
||||
Item("Compute outputs", EXPLORER_COMPUTE, None),
|
||||
Item("Show in folder...", EXPLORER_SHOW_IN_FOLDER, None),
|
||||
Item("Dependency manager...", "", None),
|
||||
Item("Open dependencies", EXPLORER_OPEN_DEPENDENCIES, None),
|
||||
];
|
||||
pub(crate) const EXPLORER_FOLDER: &[ExplorerRow] = &[
|
||||
Item("Copy", "explorer.copy", None),
|
||||
Item("Paste", "explorer.paste", None),
|
||||
Item("Remove", "folder.remove", Some("Delete")),
|
||||
Item("Rename", "folder.rename", Some("F2")),
|
||||
];
|
||||
pub(crate) const EXPLORER_GRAPH: &[ExplorerRow] = &[
|
||||
Item("Open", "graph.open", Some("Enter")),
|
||||
Item("Copy", "explorer.copy", None),
|
||||
Item("Paste", "explorer.paste", None),
|
||||
Item("Remove", "graph.delete", Some("Delete")),
|
||||
Item("Rename", "graph.rename", Some("F2")),
|
||||
Separator,
|
||||
Item("View outputs in 3D view", EXPLORER_VIEW_OUTPUTS, None),
|
||||
Item("Compute outputs", EXPLORER_COMPUTE, None),
|
||||
Item("Export outputs...", EXPLORER_EXPORT_OUTPUTS, None),
|
||||
];
|
||||
pub(crate) const EXPLORER_FOLDER: &[(&str, &str)] =
|
||||
&[("Copy", "explorer.copy"), ("Paste", "explorer.paste"), ("Rename", "folder.rename"), ("Remove", "folder.remove")];
|
||||
pub(crate) const EXPLORER_GRAPH: &[(&str, &str)] =
|
||||
&[("Open", "graph.open"), ("Copy", "explorer.copy"), ("Paste", "explorer.paste"), ("Remove", "graph.delete"), ("Rename", "graph.rename")];
|
||||
|
||||
/// The menu catalog (the target menu tree with our ids)
|
||||
pub const CATALOG: &[MenuItem] = &[
|
||||
@@ -246,44 +287,49 @@ pub fn shortcut_of(id: &str) -> Option<&'static str> {
|
||||
CATALOG.iter().find(|i| i.id == id).and_then(|i| i.shortcut).or_else(|| materialcraft_engine::find(id).and_then(|c| c.shortcut))
|
||||
}
|
||||
|
||||
/// Draw menu bars with aligned labels and a separate gutter for checkmarks.
|
||||
pub fn menu_bar(app: &mut MaterialCraftApp, ui: &mut egui::Ui) {
|
||||
let tk = Tokens::get(ui.ctx());
|
||||
egui::Panel::top("menu_bar").exact_size(24.0).frame(egui::Frame::NONE.fill(tk.chrome).inner_margin(egui::Margin::symmetric(6, 0))).show(ui, |ui| {
|
||||
let tokens = Tokens::get(ui.ctx());
|
||||
egui::Panel::top("menu_bar").exact_size(24.0).frame(egui::Frame::NONE.fill(tokens.chrome).inner_margin(egui::Margin::symmetric(6, 0))).show(ui, |ui| {
|
||||
#[cfg(not(target_arch = "wasm32"))]
|
||||
let window_layout = app.window_layout.clone();
|
||||
#[cfg(not(target_arch = "wasm32"))]
|
||||
if window_layout.is_some() {
|
||||
craft_window::title_bar::empty_area(ui, ui.max_rect());
|
||||
}
|
||||
|
||||
egui::MenuBar::new().ui(ui, |ui| {
|
||||
let ctx = ui.ctx().clone();
|
||||
let context = ui.ctx().clone();
|
||||
#[cfg(not(target_arch = "wasm32"))]
|
||||
if let Some(layout) = &window_layout {
|
||||
crate::window_controls::buttons(ui, &ctx, &layout.left);
|
||||
crate::window_controls::buttons(ui, &context, &layout.left);
|
||||
}
|
||||
for top in TOP {
|
||||
ui.menu_button(tr(top), |ui| {
|
||||
ui.set_min_width(220.0);
|
||||
let mut current_sub: Option<&str> = None;
|
||||
let items: Vec<MenuItem> = CATALOG.iter().filter(|i| i.menu == top).copied().collect();
|
||||
let mut current_submenu: Option<&str> = None;
|
||||
let items: Vec<MenuItem> = CATALOG.iter().filter(|item| item.menu == top).copied().collect();
|
||||
for item in &items {
|
||||
if let Some(s) = item.sub {
|
||||
if current_sub == Some(s) {
|
||||
if let Some(submenu) = item.sub {
|
||||
if current_submenu == Some(submenu) {
|
||||
continue;
|
||||
}
|
||||
current_sub = Some(s);
|
||||
ui.menu_button(tr(s), |ui| {
|
||||
for x in items.iter().filter(|x| x.sub == Some(s)) {
|
||||
menu_item(app, &ctx, ui, x);
|
||||
|
||||
current_submenu = Some(submenu);
|
||||
ui.menu_button(menu_label(tr(submenu)), |ui| {
|
||||
for entry in items.iter().filter(|entry| entry.sub == Some(submenu)) {
|
||||
menu_item(app, &context, ui, entry);
|
||||
}
|
||||
});
|
||||
continue;
|
||||
}
|
||||
|
||||
if item.label == "-" {
|
||||
ui.separator();
|
||||
continue;
|
||||
}
|
||||
menu_item(app, &ctx, ui, item);
|
||||
|
||||
menu_item(app, &context, ui, item);
|
||||
}
|
||||
});
|
||||
}
|
||||
@@ -292,46 +338,71 @@ pub fn menu_bar(app: &mut MaterialCraftApp, ui: &mut egui::Ui) {
|
||||
ui.with_layout(egui::Layout::right_to_left(egui::Align::Center), |ui| {
|
||||
let mut right = layout.right.clone();
|
||||
right.reverse();
|
||||
crate::window_controls::buttons(ui, &ctx, &right);
|
||||
crate::window_controls::buttons(ui, &context, &right);
|
||||
});
|
||||
}
|
||||
});
|
||||
});
|
||||
}
|
||||
|
||||
fn menu_item(app: &mut MaterialCraftApp, ctx: &egui::Context, ui: &mut egui::Ui, item: &MenuItem) {
|
||||
let modality = Modality::capture(app, ctx);
|
||||
let on = modality.allows(item.id) && enabled(app, item.id);
|
||||
let mut b = egui::Button::new(tr(item.label));
|
||||
if let Some(sc) = item.shortcut {
|
||||
b = b.shortcut_text(shortcut_label(ctx, sc));
|
||||
/// Reserve the same checkmark gutter for commands, toggles and submenus.
|
||||
fn menu_label(label: &str) -> (egui::Atom<'_>, &str) {
|
||||
(egui::Atom::custom(egui::IdSalt::new("menu-checkmark"), egui::vec2(12.0, 12.0)), label)
|
||||
}
|
||||
|
||||
/// Draw a command with an optional checkmark and dispatch it when activated.
|
||||
fn menu_item(app: &mut MaterialCraftApp, context: &egui::Context, ui: &mut egui::Ui, item: &MenuItem) {
|
||||
let modality = Modality::capture(app, context);
|
||||
let is_enabled = modality.allows(item.id) && enabled(app, item.id);
|
||||
let mut button = egui::Button::new(menu_label(tr(item.label)));
|
||||
if let Some(shortcut) = item.shortcut {
|
||||
button = button.shortcut_text(shortcut_label(context, shortcut));
|
||||
}
|
||||
let checked = match item.id {
|
||||
"ui.view.graph" => Some(true),
|
||||
"ui.graph.snapToGrid" => Some(app.ui.prefs.snap_to_grid),
|
||||
id if id.starts_with("ui.preview.") => id.strip_prefix("ui.preview.").and_then(|s| s.parse::<u32>().ok()).map(|s| s == app.ui.prefs.preview_size),
|
||||
id => crate::docking::view_panel(id).map(|p| app.ui.dock.is_open(p)),
|
||||
id if id.starts_with("ui.preview.") => {
|
||||
id.strip_prefix("ui.preview.").and_then(|size| size.parse::<u32>().ok()).map(|size| size == app.ui.prefs.preview_size)
|
||||
}
|
||||
id => crate::docking::view_panel(id).map(|panel| app.ui.dock.is_open(panel)),
|
||||
};
|
||||
|
||||
if let Some(c) = checked {
|
||||
b = b.selected(c);
|
||||
if let Some(checked) = checked {
|
||||
// Keep the accessible toggle state without styling the entire row as selected
|
||||
button = button.selected(checked);
|
||||
button.remove_class(egui::Button::CLASS_SELECTED);
|
||||
}
|
||||
if ui.add_enabled(on, b).clicked() {
|
||||
invoke(app, ctx, item.id);
|
||||
|
||||
let response = ui.add_enabled(is_enabled, |ui: &mut egui::Ui| {
|
||||
let response = button.atom_ui(ui);
|
||||
if checked == Some(true)
|
||||
&& let Some(rect) = response.rect(egui::IdSalt::new("menu-checkmark"))
|
||||
{
|
||||
let center = rect.center();
|
||||
let color = ui.style().interact(&response).fg_stroke.color;
|
||||
ui.painter().add(egui::Shape::line(
|
||||
vec![center + egui::vec2(-4.0, 0.0), center + egui::vec2(-1.0, 3.0), center + egui::vec2(4.0, -3.0)],
|
||||
egui::Stroke::new(1.5, color),
|
||||
));
|
||||
}
|
||||
response.response
|
||||
});
|
||||
if response.clicked() {
|
||||
invoke(app, context, item.id);
|
||||
ui.close();
|
||||
}
|
||||
|
||||
#[cfg(not(target_arch = "wasm32"))]
|
||||
if item.id == "file.open" {
|
||||
ui.add_enabled_ui(!modality.is_blocked() && !app.ui.recent.is_empty(), |ui| {
|
||||
ui.menu_button(tr("Recent packages"), |ui| {
|
||||
ui.menu_button(menu_label(tr("Recent packages")), |ui| {
|
||||
for path in app.ui.recent.clone() {
|
||||
if ui.button(&path).clicked() {
|
||||
if ui.button(menu_label(&path)).clicked() {
|
||||
crate::windows::open_path(app, &path);
|
||||
ui.close();
|
||||
}
|
||||
}
|
||||
ui.separator();
|
||||
if ui.button(tr("Clear recent packages")).clicked() {
|
||||
if ui.button(menu_label(tr("Clear recent packages"))).clicked() {
|
||||
app.ui.recent.clear();
|
||||
ui.close();
|
||||
}
|
||||
@@ -350,6 +421,9 @@ pub fn shortcuts(app: &mut MaterialCraftApp, ctx: &egui::Context) {
|
||||
}
|
||||
|
||||
let modality = Modality::capture(app, ctx);
|
||||
if !modality.is_blocked() && crate::explorer::shortcuts(app, ctx) {
|
||||
return;
|
||||
}
|
||||
if !modality.is_blocked() {
|
||||
crate::graph::wire_actions::shortcuts(app, ctx);
|
||||
}
|
||||
@@ -590,6 +664,52 @@ mod tests {
|
||||
assert!(app.ui.windows.export);
|
||||
}
|
||||
|
||||
/// Explorer shortcuts affect the hovered selection and leave graph shortcuts elsewhere.
|
||||
#[test]
|
||||
fn explorer_keys_act_on_its_selection_only_while_hovered() {
|
||||
use crate::explorer::ExplorerTarget;
|
||||
let mut app = app();
|
||||
app.run("file.new", serde_json::json!({"template": "empty", "name": "Second"})).unwrap();
|
||||
let graphs = app.session.pkg.graphs.len();
|
||||
let document = app.session.document_id;
|
||||
app.ui.explorer.selected = Some(ExplorerTarget::Graph { document, index: 0 });
|
||||
|
||||
// Away from the Explorer, F2 and Delete keep their graph shortcuts
|
||||
dispatched(egui::Key::F2, egui::Modifiers::NONE, &mut app);
|
||||
assert!(app.ui.explorer.rename.is_none());
|
||||
|
||||
app.ui.explorer.hovered = true;
|
||||
dispatched(egui::Key::Enter, egui::Modifiers::NONE, &mut app);
|
||||
assert_eq!(app.session.graph, 0);
|
||||
dispatched(egui::Key::F2, egui::Modifiers::NONE, &mut app);
|
||||
assert!(matches!(app.ui.explorer.rename, Some((ExplorerTarget::Graph { index: 0, .. }, _))));
|
||||
app.ui.explorer.rename = None;
|
||||
dispatched(egui::Key::Delete, egui::Modifiers::NONE, &mut app);
|
||||
assert_eq!(app.session.pkg.graphs.len(), graphs - 1);
|
||||
dispatched(egui::Key::Z, egui::Modifiers::COMMAND, &mut app);
|
||||
assert_eq!(app.session.pkg.graphs.len(), graphs, "removing a graph undoes");
|
||||
}
|
||||
|
||||
/// Explorer menu actions resolve through their documented UI or engine handler.
|
||||
#[test]
|
||||
fn explorer_menus_name_only_actions_that_exist() {
|
||||
for rows in [EXPLORER_PACKAGE, EXPLORER_FOLDER, EXPLORER_GRAPH] {
|
||||
for row in rows {
|
||||
let ids: Vec<&str> = match row {
|
||||
ExplorerRow::Item(_, id, _) => vec![id],
|
||||
ExplorerRow::Sub(_, entries) => entries.iter().map(|(_, id)| *id).collect(),
|
||||
ExplorerRow::Separator => Vec::new(),
|
||||
};
|
||||
for id in ids.into_iter().filter(|id| !id.is_empty()) {
|
||||
assert!(implemented(id) || id.starts_with("ui.explorer.") || id.starts_with("explorer."), "{id}");
|
||||
}
|
||||
if let ExplorerRow::Item(label, _, Some(shortcut)) = row {
|
||||
assert!(parse_shortcut(shortcut).is_some(), "{label}: {shortcut}");
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_shortcuts_list_leaves_shortcuts_running() {
|
||||
let mut app = app();
|
||||
@@ -728,4 +848,17 @@ mod tests {
|
||||
ctx.set_os(egui::os::OperatingSystem::Windows);
|
||||
assert_eq!(shortcut_label(&ctx, "Ctrl+Shift+E"), "Ctrl+Shift+E");
|
||||
}
|
||||
/// A hidden Explorer must not delete its selection using stale hover state.
|
||||
#[test]
|
||||
fn review_hidden_explorer_ignores_delete() {
|
||||
let mut app = app();
|
||||
let graphs = app.session.pkg.graphs.len();
|
||||
app.ui.explorer.selected = Some(crate::explorer::ExplorerTarget::Graph { document: app.session.document_id, index: 0 });
|
||||
app.ui.explorer.hovered = true;
|
||||
app.ui.dock.close(crate::docking::Panel::Explorer);
|
||||
|
||||
dispatched(egui::Key::Delete, egui::Modifiers::NONE, &mut app);
|
||||
|
||||
assert_eq!(app.session.pkg.graphs.len(), graphs);
|
||||
}
|
||||
}
|
||||
Loaded 100 of 122 files, more files were not shown because too many files have changed in this diff.
Show more
Reference in new issue
Block a user