Merge latest SBS branch improvements

Preserve resource and rendering fixes alongside updated library previews, node UI, and function input support. Reconcile evaluator state and loop caching while retaining both sets of regression tests.
This commit is contained in:
chasse20 committed 2026-11-12 18:52:32 -05:00
commit 46802a44fc
38 files changed
+1162 -96

No files matched your search

+1
View File
@@ -77,6 +77,7 @@ mod color_space;
mod connection_commands;
mod export_request;
mod export_size;
mod library_preview;
pub use clip::Clip;
pub use color_space::ColorSpace;
pub use export_request::ExportRequest;
+82
View File
@@ -0,0 +1,82 @@
//! Library previews: a small image of what a library graph makes from sample inputs
use std::collections::BTreeMap;
use std::sync::Arc;
use materialcraft_core::Package;
use materialcraft_image::{Image, Kind};
use crate::{NodeLibrary, Session};
/// Smallest spread between an image's darkest and brightest sample that still shows something
const FLAT_SPREAD: f32 = 0.01;
/// Side in pixels a graph is cooked at before it is scaled down to the preview
const COOKED_SIZE: u32 = 128;
impl NodeLibrary {
/// What graph `graph` of package `package` makes at `size` pixels, from a wave height, its
/// colors and its normal map on the graph's inputs. `None` when the graph has no output that
/// cooks or its image is one flat value
pub fn preview(library: &Arc<NodeLibrary>, package: &str, graph: &str, size: u32) -> Option<Image> {
let source = library.packages.get(package)?;
let index = source.graphs.iter().position(|candidate| candidate.function.is_none() && candidate.sbs_path() == graph)?;
// A session links the graph's instances and functions to the library, as an opened package gets
let session = Session::with_library(Package::clone(source), library.clone());
let graph = session.pkg.graphs.get(index)?;
let decode = session.resource_decoder();
let mut options = materialcraft_eval::Options::new(&decode);
// Thin lines and fine grain vanish when cooked at thumbnail size, so the graph cooks larger and is scaled down
let cooked_size = size.max(COOKED_SIZE);
options.max_size = Some(cooked_size);
options.inputs = sample_inputs(graph, cooked_size);
let cooked = materialcraft_eval::cook(&session.pkg, index, &options, &session.cache);
let outputs = materialcraft_eval::outputs(graph, &cooked);
let base_color = outputs.iter().find(|(_, usage, _, image)| *usage == "baseColor" && image.is_some());
let image = base_color.or_else(|| outputs.iter().find(|output| output.3.is_some()))?.3?;
(!is_flat(image)).then(|| image.resize(size.min(image.w), size.min(image.h), false))
}
}
/// An image for every input node of `graph`, by identifier: normals for normal inputs, colors for color inputs, the height for the rest
fn sample_inputs(graph: &materialcraft_core::Graph, size: u32) -> BTreeMap<String, Image> {
let height = Image::generate_uv(size, size, Kind::Gray, |u, v| {
[0.5 + 0.25 * (u * std::f32::consts::TAU).sin() + 0.25 * (v * std::f32::consts::TAU).cos(), 0.0, 0.0, 0.0]
});
let color = height.map(Kind::Color, |pixel| [0.15 + 0.7 * pixel[0], 0.35 + 0.3 * pixel[0], 0.8 - 0.5 * pixel[0], 1.0]);
let normal = materialcraft_nodes::atomic::height_to_normal(&height, 4.0, false, true, false);
graph
.nodes
.iter()
.filter(|node| matches!(node.def.as_str(), "input_color" | "input_grayscale"))
.map(|node| {
let identifier = materialcraft_eval::identifier(node);
let image = if identifier.to_ascii_lowercase().contains("normal") {
&normal
} else if node.def == "input_color" {
&color
} else {
&height
};
(identifier, image.clone())
})
.collect()
}
/// Whether every pixel of `image` has nearly the same value
fn is_flat(image: &Image) -> bool {
let mut low = [f32::INFINITY; 3];
let mut high = [f32::NEG_INFINITY; 3];
for y in 0..i64::from(image.h) {
for x in 0..i64::from(image.w) {
let pixel = image.get(x, y, false);
for channel in 0..3 {
low[channel] = low[channel].min(pixel[channel]);
high[channel] = high[channel].max(pixel[channel]);
}
}
}
(0..3).all(|channel| high[channel] - low[channel] < FLAT_SPREAD)
}
+14
View File
@@ -291,3 +291,17 @@ fn function_tags_choose_library_filters_before_path_fallbacks() {
assert_eq!(categories("Tagged"), ["Functions/Comparison", "Functions/Easings"]);
assert_eq!(categories("Fallback"), ["Functions/Maths"]);
}
/// Library graphs render a preview from sample inputs; graphs that make no image give none.
#[test]
fn library_graphs_cook_previews_from_sample_inputs() {
let library = Arc::new(NodeLibrary::load(&library::files()));
let preview = |package: &str, graph: &str| NodeLibrary::preview(&library, package, graph, 32);
let filter = preview("sbs://blur_hq.sbs", "blur_hq").unwrap();
assert_eq!((filter.w, filter.h), (32, 32));
assert!(preview("sbs://materials/pbr/bricks_001.sbs", "bricks_001").is_some());
assert!(preview("sbs://noise_bnw_spots_1.sbs", "bnw_spots_1").is_some(), "an FX-Map noise reads the variables its size function sets");
assert!(preview("sbs://blur_hq.sbs", "no_such_graph").is_none());
assert!(preview("sbs://functions.sbs", "Functions/Math/Pi").is_none(), "a function has no image");
}
+15 -5
View File
@@ -86,7 +86,7 @@ fn function_expansion_allows_several_bounded_bodies_but_still_caps_total_work()
let mut allowed = caller(3);
function::resolve_instances(&mut allowed, &package, &BTreeMap::new());
assert_eq!(evaluate(&allowed), Value::Float(3.0));
let mut oversized = caller(4);
let mut oversized = caller(32);
function::resolve_instances(&mut oversized, &package, &BTreeMap::new());
assert!(function::compile(&oversized, 0).err().unwrap().contains("limit"));
// Compiling a pre-resolved tree must enforce its own budget too.
@@ -251,7 +251,7 @@ fn function_calls_reject_wrong_canvas_cycles_and_outputless_sources() {
}
#[test]
fn calls_publish_assignments_and_evaluate_arguments_once() {
fn calls_evaluate_arguments_once_and_share_the_variables_they_set() {
let mut package = source();
let mut source = FunctionGraph::default();
let input = source.add("get_float1", &[], Some(Value::Text("amount".into())));
@@ -275,11 +275,21 @@ fn calls_publish_assignments_and_evaluate_arguments_once() {
inputs: vec![GraphPort { identifier: "amount".into(), type_code: 256 }],
outputs: vec![GraphPort { identifier: "output".into(), type_code: 256 }],
});
let after = caller.add("get_float1", &[], Some(Value::Text("private".into())));
let total = caller.add("add", &[call, after], None);
let total = caller.add("add", &[call, get], None);
caller.output = Some(caller.add("sequence", &[init, total], None));
function::resolve_instances(&mut caller, &package, &BTreeMap::new());
// The argument is evaluated once (2 + 2), and Set publishes 99 to the caller's node scope.
// The Get node ran once, before the argument's Set: 1; the call doubles its argument 2
assert_eq!(evaluate(&caller), Value::Float(5.0));
// A Get node that runs after the call reads what the called graph set, as the library's size helpers rely on
let after = caller.add("get_float1", &[], Some(Value::Text("private".into())));
let read_after = caller.add("sequence", &[call, after], None);
caller.output = Some(caller.add("sequence", &[init, read_after], None));
assert_eq!(evaluate(&caller), Value::Float(99.0));
// A separate Get after the call sees the assignment while the call result stays cached.
let total = caller.add("add", &[call, after], None);
caller.output = Some(caller.add("sequence", &[init, total], None));
assert_eq!(evaluate(&caller), Value::Float(103.0));
}
@@ -296,6 +296,13 @@ fn color_boolean_enum_and_text_parameters_use_typed_function_outputs() {
let owner = node(&mut session, "uniform");
command(&mut session, "graph.node.function", json!({"id": owner, "param": "color", "function": FunctionGraph::constant(Value::Float(0.5))}));
// A gray level fills the color channels, as the library's uniform colors rely on
let result = &session.cook().nodes[&owner];
assert_eq!(result.error, None);
assert_eq!(result.parameters["color"].as_vec4(), Some([0.5, 0.5, 0.5, 1.0]));
let owner = node(&mut session, "uniform");
command(&mut session, "graph.node.function", json!({"id": owner, "param": "color", "function": FunctionGraph::constant(Value::Int(1))}));
assert!(session.cook().nodes[&owner].error.as_ref().unwrap().contains("Float4"));
let bitmap = node(&mut session, "bitmap");
assert!(execute(&mut session, "graph.node.function", &json!({"id": bitmap, "param": "resource"})).is_err());
+9 -1
View File
@@ -12,7 +12,9 @@ pub(crate) fn evaluate(
) -> Result<Value, String> {
let program = compile(function, seed)?;
let scalar_channel = allow_scalar && expected == ValueType::Float4 && program.output_type() == ValueType::Float as u32;
if program.output_type() != expected as u32 && !scalar_channel {
// A color parameter also takes a gray level or an opaque RGB triple.
let widened = expected == ValueType::Float4 && [ValueType::Float as u32, ValueType::Float3 as u32].contains(&program.output_type());
if program.output_type() != expected as u32 && !scalar_channel && !widened {
return Err(format!("output must be {}", expected.label()));
}
@@ -30,6 +32,12 @@ pub(crate) fn evaluate(
return Err("function returned a non-finite value".into());
}
let value = match value {
Value::Float(level) if !scalar_channel && widened => Value::Float4([level, level, level, 1.0]),
Value::Float3([red, green, blue]) if widened => Value::Float4([red, green, blue, 1.0]),
value => value,
};
variables.extend(state.assignments().clone());
Ok(value)
+47
View File
@@ -604,3 +604,50 @@ fn enabled_generators_use_parent_size_and_inherit_other_input_base_parameters()
}
}
}
#[test]
fn variables_set_by_a_base_parameter_function_reach_the_nodes_other_functions() {
use materialcraft_core::{BaseParameter, FunctionGraph};
let mut size = FunctionGraph::default();
let grid = size.add_constant(Value::Int(2));
let store = size.add("set", &[grid], Some(Value::Text("grid".into())));
let unchanged = size.add_constant(Value::Int2([0, 0]));
size.output = Some(size.add("sequence", &[store, unchanged], None));
let mut roughness = FunctionGraph::default();
let read = roughness.add("get_integer1", &[], Some(Value::Text("grid".into())));
roughness.output = Some(roughness.add("tofloat", &[read], None));
let mut graph = Graph::new("Shared variables");
let generator = graph.add_node("fx_map", [0.0; 2]);
let node = graph.node_mut(generator).unwrap();
node.base.functions.insert(BaseParameter::OutputSize, size);
node.functions.insert("roughness".into(), roughness);
let mut package = Package::new("Shared variables");
package.graphs.push(graph);
let cooked = cook(&package, 0, &Options::new(&no_res), &Mutex::new(Cache::default()));
let result = &cooked.nodes[&generator];
assert_eq!(result.error, None);
assert_eq!(result.parameters.get("roughness"), Some(&Value::Float(2.0)));
}
#[test]
fn a_color_parameter_function_may_return_a_gray_level_or_an_rgb_triple() {
use materialcraft_core::FunctionGraph;
for (value, expected) in [(Value::Float(0.25), [0.25, 0.25, 0.25, 1.0]), (Value::Float3([0.1, 0.2, 0.3]), [0.1, 0.2, 0.3, 1.0])] {
let mut graph = Graph::new("Color function");
let uniform = graph.add_node("uniform", [0.0; 2]);
graph.node_mut(uniform).unwrap().functions.insert("color".into(), FunctionGraph::constant(value));
let mut package = Package::new("Color function");
package.graphs.push(graph);
let cooked = cook(&package, 0, &Options::new(&no_res), &Mutex::new(Cache::default()));
let result = &cooked.nodes[&uniform];
assert_eq!(result.error, None);
assert_eq!(result.parameters.get("color").and_then(Value::as_vec4), Some(expected));
}
}
+1 -1
View File
@@ -14,7 +14,7 @@ pub(super) fn definition() -> NodeDefinition {
.float("opacity", "Opacity", 1.0, 0.0, 10.0)
.boolean("color_mode", "Color output", false)
.color("background", "Background color", [0.0, 0.0, 0.0, 1.0])
.float4("render_region", "Render region", [0.0, 1.0, 0.0, 1.0], 0.0, 1.0)
.float4("render_region", "Render region", [0.0, 1.0, 0.0, 1.0], -65536.0, 65536.0)
.float4("tiling_region", "Tiling region", [0.0, 1.0, 0.0, 1.0], 0.0, 1.0)
.any_out()
.cook(crate::pattern::cook)
+87 -13
View File
@@ -11,8 +11,8 @@ fn compile_nested(graph: &FunctionGraph, seed: u32, depth: usize, remaining: &mu
if graph.nodes.len() > 4096 {
return Err("function exceeds the 4096-node graph limit".into());
}
if depth > 8 || graph.nodes.len() > *remaining {
return Err("function exceeds the 8-level or 8192-node expanded execution limit".into());
if depth > super::MAX_CALL_DEPTH || graph.nodes.len() > *remaining {
return Err("function exceeds the 16-level or 65536-node expanded execution limit".into());
}
*remaining -= graph.nodes.len();
let output = super::output_node(graph).ok_or("function has no result node")?.id;
@@ -42,10 +42,11 @@ fn compile_nested(graph: &FunctionGraph, seed: u32, depth: usize, remaining: &mu
catalog::definition(&node.op).ok_or_else(|| format!("unknown function `{}`", node.op))?
};
let names: Vec<_> = super::input_identifiers(node).collect();
let missing_input = names
.iter()
.zip(&node.inputs)
.any(|(name, input)| input.is_none() && !node.instance.as_ref().is_some_and(|instance| instance.defaults.contains_key(*name)));
// An operation computes with zero on an input nothing is connected to; a call needs a source default instead
let missing_input = node
.instance
.as_ref()
.is_some_and(|instance| names.iter().zip(&node.inputs).any(|(name, input)| input.is_none() && !instance.defaults.contains_key(*name)));
if node.inputs.len() != names.len() || missing_input {
return Err(format!("{} ({id}) requires connected inputs: {}", super::node_label(node), names.join(", ")));
}
@@ -68,8 +69,36 @@ fn compile_nested(graph: &FunctionGraph, seed: u32, depth: usize, remaining: &mu
}
active.remove(&id);
let inputs: Vec<usize> =
let connected: Vec<usize> =
sources.iter().map(|input| indices.get(input).copied().ok_or("unresolved function input".to_string())).collect::<Result<_, _>>()?;
let inputs = if node.instance.is_some() || ports.iter().all(|(_, input)| input.is_some()) {
connected
} else {
let sibling = connected.first().and_then(|index| instructions.get(*index)).map(|instruction| instruction.type_code);
let mut connected = connected.into_iter();
let mut inputs = Vec::with_capacity(ports.len());
for (name, input) in &ports {
let index = match input {
Some(_) => connected.next().ok_or("unresolved function input")?,
None => {
let (definition, value) = unconnected(name, sibling.unwrap_or(node.type_code))?;
let type_code = super::value_type::type_code(&value);
instructions.push(Instruction {
id: 0,
definition,
inputs: Vec::new(),
value: Some(value),
type_code,
repeated: Vec::new(),
call: None,
});
instructions.len() - 1
}
};
inputs.push(index);
}
inputs
};
let call = if let Some(instance) = &node.instance {
let source = node.source.as_ref().ok_or_else(|| format!("unresolved Function Graph `{}`", instance.graph))?.as_ref().map_err(Clone::clone)?;
let program = compile_nested(source, seed, depth + 1, remaining)?;
@@ -86,7 +115,9 @@ fn compile_nested(graph: &FunctionGraph, seed: u32, depth: usize, remaining: &mu
}
}
let inputs = ports.iter().filter(|(_, input)| input.is_some()).map(|(name, _)| (*name).to_string()).collect();
Some(super::function_call::FunctionCall { program, inputs, defaults: instance.defaults.clone() })
let exports =
program.instructions.iter().any(|instruction| instruction.definition.id == "set" || instruction.call.as_ref().is_some_and(|call| call.exports));
Some(super::function_call::FunctionCall { program, inputs, defaults: instance.defaults.clone(), exports })
} else {
None
};
@@ -94,14 +125,57 @@ fn compile_nested(graph: &FunctionGraph, seed: u32, depth: usize, remaining: &mu
let input_type = |index: usize| inputs.get(index).and_then(|index| instructions.get(*index)).map_or(256, |instruction| instruction.type_code);
let inferred = super::inferred_type::inferred_type(&node.op, value.as_ref(), input_type);
let type_code = call.as_ref().map_or_else(|| if node.type_code == 0 { inferred } else { node.type_code }, |call| call.program.output_type());
let pure = call.is_none()
&& !matches!(node.op.as_str(), "set" | "sequence" | "while" | "rand" | "isdefined")
&& !node.op.starts_with("get_")
&& inputs.iter().all(|index| instructions.get(*index).is_some_and(|instruction| instruction.pure));
indices.insert(id, instructions.len());
instructions.push(Instruction { id, definition, inputs, value, type_code, pure, call });
instructions.push(Instruction { id, definition, inputs, value, type_code, repeated: Vec::new(), call });
}
// Instructions come after their inputs, so walking back from a loop reaches its whole condition and body
for index in 0..instructions.len() {
if instructions.get(index).is_some_and(|instruction| instruction.definition.id == "while") {
let repeated = loop_members(&instructions, index);
if let Some(instruction) = instructions.get_mut(index) {
instruction.repeated = repeated;
}
}
}
let output = indices.get(&output).copied().ok_or("missing result instruction")?;
Ok(Program { instructions, output, seed })
}
/// The instructions the condition and the body of loop `index` evaluate again on every iteration
fn loop_members(instructions: &[Instruction], index: usize) -> Vec<usize> {
let mut member = vec![false; instructions.len()];
let mut pending: Vec<usize> = instructions.get(index).map(|instruction| instruction.inputs.iter().skip(1).copied().collect()).unwrap_or_default();
while let Some(next) = pending.pop() {
if let Some(seen) = member.get_mut(next)
&& !*seen
{
*seen = true;
pending.extend(instructions.get(next).map(|instruction| instruction.inputs.as_slice()).unwrap_or_default());
}
}
member.iter().enumerate().filter(|(_, member)| **member).map(|(index, _)| index).collect()
}
/// The constant an unconnected input `name` reads: false for a condition, otherwise zero of the type its node works with
fn unconnected(name: &str, type_code: u32) -> Result<(&'static super::FunctionDefinition, materialcraft_core::Value), String> {
use materialcraft_core::ValueType;
let value_type = if matches!(name, "cond" | "condition") { ValueType::Boolean } else { ValueType::from_code(type_code).unwrap_or(ValueType::Float) };
let operation = match value_type {
ValueType::Boolean => "const_bool",
ValueType::Integer => "const_int1",
ValueType::Integer2 => "const_int2",
ValueType::Integer3 => "const_int3",
ValueType::Integer4 => "const_int4",
ValueType::Float => "const_float1",
ValueType::Float2 => "const_float2",
ValueType::Float3 => "const_float3",
ValueType::Float4 => "const_float4",
ValueType::String => "const_string",
};
let definition = catalog::definition(operation).ok_or("missing constant operation")?;
Ok((definition, value_type.default_value()))
}
@@ -6,4 +6,6 @@ pub(crate) struct FunctionCall {
pub program: Program,
pub inputs: Vec<String>,
pub defaults: std::collections::BTreeMap<String, materialcraft_core::Value>,
/// The called graph sets variables, directly or in a graph it calls; the caller reads them after the call
pub exports: bool,
}
+2 -1
View File
@@ -7,6 +7,7 @@ pub(crate) struct Instruction {
pub inputs: Vec<usize>,
pub value: Option<Value>,
pub type_code: u32,
pub pure: bool,
/// For a loop: the instructions of its condition and body, evaluated again on every iteration
pub repeated: Vec<usize>,
pub call: Option<super::function_call::FunctionCall>,
}
+2 -1
View File
@@ -2,7 +2,8 @@
// Individual graphs stay capped at 4096 nodes. Shared calls can expand beyond that size
// (the bundled noise/render functions use 4426/6997), but must not grow without a ceiling.
const MAX_EXPANDED_NODES: usize = 8192;
const MAX_EXPANDED_NODES: usize = 65_536;
const MAX_CALL_DEPTH: usize = 16;
mod arithmetic;
mod catalog;
+1
View File
@@ -79,6 +79,7 @@ pub(crate) fn evaluate(
let ordering = match (left, right) {
(Value::Int(a), Value::Int(b)) => a.partial_cmp(b),
(Value::Float(a), Value::Float(b)) => a.partial_cmp(b),
(Value::Bool(a), Value::Bool(b)) => a.partial_cmp(b),
_ => return Err("comparison requires numeric inputs".into()),
}
.ok_or("cannot compare non-finite values")?;
+9 -8
View File
@@ -117,7 +117,7 @@ impl Program {
storage.random = state.random;
let result = call.program.run(context, storage, remaining_steps);
state.random = storage.random;
if result.is_ok() {
if call.exports && result.is_ok() {
// Set publishes into the caller's scope; arguments and defaults stay local.
state.variables.extend(storage.assignments.clone());
state.assignments.extend(storage.assignments.clone());
@@ -154,7 +154,7 @@ impl Program {
}
LoopStart(index) => {
let last = state.values.pop().ok_or("missing loop initialization")?;
self.clear_dynamic_results(state);
self.clear_loop_results(index, state)?;
state.steps.push(LoopCondition { instruction: index, iteration: 0, last });
state.steps.push(Enter(self.input(index, 1)?));
}
@@ -164,14 +164,14 @@ impl Program {
if exit || (maximum >= 0 && iteration >= maximum as u32) {
state.values.push(last);
} else {
self.clear_dynamic_results(state);
self.clear_loop_results(index, state)?;
state.steps.push(LoopBody { instruction: index, iteration: iteration.saturating_add(1) });
state.steps.push(Enter(self.input(index, 2)?));
}
}
LoopBody { instruction: index, iteration } => {
let last = state.values.pop().ok_or("missing loop body result")?;
self.clear_dynamic_results(state);
self.clear_loop_results(index, state)?;
state.steps.push(LoopCondition { instruction: index, iteration, last });
state.steps.push(Enter(self.input(index, 1)?));
}
@@ -187,13 +187,14 @@ impl Program {
Ok(result)
}
fn clear_dynamic_results(&self, state: &mut EvaluationState) {
fn clear_loop_results(&self, index: usize, state: &mut EvaluationState) -> Result<(), String> {
// A node's outgoing wires share its computed value, including reads, branches and side effects.
// Loop phases evaluate variable-dependent nodes anew; constants remain reusable.
for (instruction, register) in self.instructions.iter().zip(&mut state.registers) {
if !instruction.pure {
// Only the current loop's condition and body run again; unrelated cached values stay intact.
for repeated in &self.instruction(index)?.repeated {
if let Some(register) = state.registers.get_mut(*repeated) {
*register = None;
}
}
Ok(())
}
}
@@ -29,8 +29,8 @@ fn resolve(function: &mut FunctionGraph, local: &Package, sources: &BTreeMap<Str
if body.nodes.len() > 4096 {
return Err("Function Graph exceeds the 4096-node graph limit".into());
}
if stack.len() >= 8 || body.nodes.len() > *remaining {
return Err("Function instances exceed the 8-level or 8192-node expanded limit".into());
if stack.len() >= super::MAX_CALL_DEPTH || body.nodes.len() > *remaining {
return Err("Function instances exceed the 16-level or 65536-node expanded limit".into());
}
if graph.exposed.len() > 4096
+116
View File
@@ -420,3 +420,119 @@ fn loops_refresh_random_samples_but_keep_each_iterations_fanout_equal() {
graph.output = Some(graph.add("while", &[init, exit, body], Some(Value::Int(3))));
assert_eq!(evaluate(&graph, &BTreeMap::new()).unwrap(), Value::Float2([expected[2]; 2]));
}
#[test]
fn a_node_runs_once_so_readers_before_and_after_a_set_share_its_value() {
let mut graph = FunctionGraph::default();
let read = graph.add("get_integer1", &[], Some(Value::Text("count".into())));
let one = graph.add_constant(Value::Int(1));
let next = graph.add("add", &[read, one], None);
let store = graph.add("set", &[next], Some(Value::Text("count".into())));
graph.output = Some(graph.add("sequence", &[store, read], None));
let variables = BTreeMap::from([("count".to_string(), Value::Int(4))]);
assert_eq!(evaluate(&graph, &variables).unwrap(), Value::Int(4), "the Get node read 4 before the Set and keeps it");
// A second Get node reads the variable when it runs, after the Set
let later = graph.add("get_integer1", &[], Some(Value::Text("count".into())));
graph.output = Some(graph.add("sequence", &[store, later], None));
assert_eq!(evaluate(&graph, &variables).unwrap(), Value::Int(5));
}
#[test]
fn a_loop_evaluates_its_condition_and_body_again_on_every_iteration() {
let mut graph = FunctionGraph::default();
let zero = graph.add_constant(Value::Int(0));
let start = graph.add("set", &[zero], Some(Value::Text("count".into())));
let read = graph.add("get_integer1", &[], Some(Value::Text("count".into())));
let limit = graph.add_constant(Value::Int(3));
let reached = graph.add("gteq", &[read, limit], None);
let one = graph.add_constant(Value::Int(1));
let next = graph.add("add", &[read, one], None);
let step = graph.add("set", &[next], Some(Value::Text("count".into())));
graph.output = Some(graph.add("while", &[start, reached, step], Some(Value::Int(100))));
assert_eq!(evaluate(&graph, &BTreeMap::new()).unwrap(), Value::Int(3));
}
#[test]
fn variables_a_called_graph_sets_reach_its_caller_but_its_inputs_do_not() {
let mut called = FunctionGraph::default();
let input = called.add("get_integer1", &[], Some(Value::Text("amount".into())));
called.output = Some(called.add("set", &[input], Some(Value::Text("shared".into()))));
let mut caller = FunctionGraph::default();
let call = caller.add("instance", &[], None);
let node = caller.nodes.last_mut().unwrap();
node.instance = Some(materialcraft_core::GraphInstance {
label: String::new(),
package: String::new(),
graph: "called".into(),
inputs: vec![materialcraft_core::GraphPort { identifier: "amount".into(), type_code: 16 }],
outputs: vec![materialcraft_core::GraphPort { identifier: "output".into(), type_code: 16 }],
defaults: BTreeMap::from([("amount".to_string(), Value::Int(9))]),
});
node.inputs = vec![None];
node.source = Some(Ok(std::sync::Arc::new(called)));
let shared = caller.add("get_integer1", &[], Some(Value::Text("shared".into())));
caller.output = Some(caller.add("sequence", &[call, shared], None));
assert_eq!(evaluate(&caller, &BTreeMap::new()).unwrap(), Value::Int(9));
let leaked = caller.add("get_integer1", &[], Some(Value::Text("amount".into())));
caller.output = Some(caller.add("sequence", &[call, leaked], None));
assert!(evaluate(&caller, &BTreeMap::new()).unwrap_err().contains("undefined variable `amount`"));
}
#[test]
fn a_drop_down_parameter_reads_as_the_integer_of_its_option() {
let mut graph = FunctionGraph::default();
let option = graph.add("get_integer1", &[], Some(Value::Text("mode".into())));
let two = graph.add_constant(Value::Int(2));
graph.output = Some(graph.add("gteq", &[option, two], None));
assert_eq!(evaluate(&graph, &BTreeMap::from([("mode".to_string(), Value::Enum(3))])).unwrap(), Value::Bool(true));
}
#[test]
fn an_unconnected_input_computes_with_zero_and_a_loop_without_a_condition_runs_its_limit() {
let mut graph = FunctionGraph::default();
let high = graph.add_constant(Value::Float(8.0));
let half = graph.add_constant(Value::Float(0.5));
graph.output = Some(graph.add("lerp", &[high, high, half], None));
graph.nodes.last_mut().unwrap().inputs = vec![None, Some(high), Some(half)];
assert_eq!(evaluate(&graph, &BTreeMap::new()).unwrap(), Value::Float(4.0), "halfway between zero and 8");
let mut graph = FunctionGraph::default();
let zero = graph.add_constant(Value::Int(0));
let start = graph.add("set", &[zero], Some(Value::Text("count".into())));
let read = graph.add("get_integer1", &[], Some(Value::Text("count".into())));
let one = graph.add_constant(Value::Int(1));
let next = graph.add("add", &[read, one], None);
let step = graph.add("set", &[next], Some(Value::Text("count".into())));
graph.output = Some(graph.add("while", &[start, start, step], Some(Value::Int(3))));
graph.nodes.last_mut().unwrap().inputs = vec![Some(start), None, Some(step)];
assert_eq!(evaluate(&graph, &BTreeMap::new()).unwrap(), Value::Int(3));
}
#[test]
fn booleans_compare_in_order() {
assert_eq!(operation("gt", &[Value::Bool(true), Value::Bool(false)], None).unwrap(), Value::Bool(true));
assert_eq!(operation("lreq", &[Value::Bool(true), Value::Bool(false)], None).unwrap(), Value::Bool(false));
}
#[test]
fn every_pixel_of_a_processor_draws_its_own_random_numbers() {
let mut function = FunctionGraph::default();
let range = function.add_constant(Value::Float(1.0));
function.output = Some(function.add("rand", &[range], None));
let definition = crate::find("pixel_processor").unwrap();
let parameters = crate::resolve_params(definition, &BTreeMap::from([("function".into(), Value::Function(Box::new(function)))]));
let variables = BTreeMap::new();
let context = crate::CookContext { w: 8, h: 8, seed: 3, tile: true, inputs: &[], params: &parameters, resource: &|_| None, vars: &variables };
let image = (definition.cook)(&context).unwrap().remove(0);
let first = image.get(0, 0, false)[0];
let different = (0..8).flat_map(|y| (0..8).map(move |x| (x, y))).filter(|(x, y)| (image.get(*x, *y, false)[0] - first).abs() > 1e-4).count();
assert!(different > 56, "{different} of 64 pixels differ from the first");
}
+90
View File
@@ -194,3 +194,93 @@ fn a_full_nine_level_quadtree_renders_one_pattern_per_pixel() {
let images = (definition.cook)(&context).unwrap();
assert!(images[0].data.iter().all(|value| (*value - 1.0).abs() < 1e-6));
}
fn square(graph: &mut PatternGraph, node: usize) {
graph.nodes[node].parameters.insert("patterntype".into(), Value::Int(2));
}
#[test]
fn an_iteration_reads_the_variables_the_previous_iteration_set() {
let mut graph = PatternGraph::default();
let iterate = graph.add(PatternNodeKind::Iterate).unwrap();
let quadrant = graph.add(PatternNodeKind::Quadrant).unwrap();
graph.root = Some(iterate);
graph.nodes[0].parameters.insert("numberadded".into(), Value::Int(3));
graph.nodes[0].children[1] = Some(quadrant);
square(&mut graph, 1);
let mut function = FunctionGraph::default();
let total = function.add("get_float1", &[], Some(Value::Text("total".into())));
let step = function.add_constant(Value::Float(0.25));
let next = function.add("add", &[total, step], None);
function.output = Some(function.add("set", &[next], Some(Value::Text("total".into()))));
graph.nodes[1].parameters.insert("opacity".into(), Value::Function(Box::new(function)));
let image = cook_with_variables(graph, &BTreeMap::from([("total".into(), Value::Float(0.0))])).unwrap().remove(0);
// 0.25, 0.5 and 0.75 add up; three separate copies of the variable would add 0.25 three times
assert!((image.mean()[0] - 1.5).abs() < 1e-5, "{}", image.mean()[0]);
}
#[test]
fn the_render_region_is_the_part_of_pattern_space_the_image_shows() {
let mut graph = PatternGraph::with_root(PatternNodeKind::Quadrant);
square(&mut graph, 0);
let definition = find("fx_map").unwrap();
let parameters = resolve_params(
definition,
&BTreeMap::from([("pattern".into(), Value::PatternGraph(Box::new(graph))), ("render_region".into(), Value::Float4([0.0, 2.0, 0.0, 2.0]))]),
);
let context = CookContext { w: 16, h: 16, seed: 7, tile: false, inputs: &[], params: &parameters, resource: &|_| None, vars: &BTreeMap::new() };
let image = (definition.cook)(&context).unwrap().remove(0);
// The unit square fills the top-left quarter of a region twice as wide and tall
assert!((image.mean()[0] - 0.25).abs() < 1e-5, "{}", image.mean()[0]);
assert_eq!(image.get(3, 3, false)[0], 1.0);
assert_eq!(image.get(12, 12, false)[0], 0.0);
}
#[test]
fn every_visit_draws_its_own_random_numbers() {
let mut graph = PatternGraph::with_root(PatternNodeKind::Quadrant);
graph.nodes[0].parameters.insert("patterntype".into(), Value::Int(0));
let child = graph.add(PatternNodeKind::Quadrant).unwrap();
for slot in 0..4 {
graph.nodes[0].children[slot] = Some(child);
}
square(&mut graph, 1);
let mut function = FunctionGraph::default();
let range = function.add_constant(Value::Float(1.0));
function.output = Some(function.add("rand", &[range], None));
graph.nodes[1].parameters.insert("opacity".into(), Value::Function(Box::new(function)));
let image = cook(graph).unwrap().remove(0);
let quarters = [image.get(4, 4, false)[0], image.get(12, 4, false)[0], image.get(4, 12, false)[0], image.get(12, 12, false)[0]];
assert!(quarters.windows(2).all(|pair| (pair[0] - pair[1]).abs() > 1e-4), "{quarters:?}");
}
#[test]
fn a_pixel_on_the_seam_of_two_patterns_is_drawn_once() {
let mut graph = PatternGraph::with_root(PatternNodeKind::Quadrant);
graph.nodes[0].parameters.insert("patterntype".into(), Value::Int(0));
let child = graph.add(PatternNodeKind::Quadrant).unwrap();
let grandchild = graph.add(PatternNodeKind::Quadrant).unwrap();
for slot in 0..4 {
graph.nodes[0].children[slot] = Some(child);
graph.nodes[1].children[slot] = Some(grandchild);
}
graph.nodes[1].parameters.insert("patterntype".into(), Value::Int(0));
square(&mut graph, 2);
let definition = find("fx_map").unwrap();
let parameters = resolve_params(definition, &BTreeMap::from([("pattern".into(), Value::PatternGraph(Box::new(graph)))]));
let variables = BTreeMap::new();
// Two pixels a side put every pixel center on the corner of four of the sixteen squares
let context = CookContext { w: 2, h: 2, seed: 7, tile: true, inputs: &[], params: &parameters, resource: &|_| None, vars: &variables };
let image = (definition.cook)(&context).unwrap().remove(0);
assert_eq!(image.get(0, 0, false)[0], 1.0);
assert_eq!(image.get(1, 1, false)[0], 1.0);
}
+4 -3
View File
@@ -19,8 +19,9 @@ fn input_count(node: &FunctionNode) -> usize {
materialcraft_engine::nodes::function::input_identifiers(node).count()
}
pub(super) fn node_rect(node: &FunctionNode, previews: bool) -> Rect {
node_card::bounds(node.pos, input_count(node), 1, previews, node.op == "passthrough")
/// Function nodes show a value or a symbol, never a preview, so their body only fits that
pub(super) fn node_rect(node: &FunctionNode) -> Rect {
node_card::bounds_with_body(node.pos, input_count(node), 1, super::node_face::height(node), node.op == "passthrough")
}
pub(super) fn in_port(node: &FunctionNode, bounds: Rect, index: usize) -> Pos2 {
@@ -32,7 +33,7 @@ pub(super) fn out_port(node: &FunctionNode, bounds: Rect) -> Pos2 {
}
pub(super) fn preview_rect(app: &MaterialCraftApp, editor: &FunctionEditor, node: &FunctionNode, snap: bool, selected: bool) -> Rect {
let mut bounds = node_rect(node, app.ui.prefs.thumbnails);
let mut bounds = node_rect(node);
if let Some(FunctionDrag::Node(d, delta)) = &editor.drag
&& (*d == node.id || selected)
{
+1
View File
@@ -22,6 +22,7 @@ mod actions;
mod geometry;
mod input;
mod node_canvas;
mod node_face;
mod panel;
mod function_canvas;
+10 -3
View File
@@ -46,10 +46,17 @@ pub(super) fn paint(
}
node_card::outline(painter, bounds, zoom, Stroke::new(if selected { 2.0 } else { 1.0 }, outline));
let text_color = if output { Color32::from_gray(0x20) } else { tokens.text };
if missing {
painter.text(body.center(), Align2::CENTER_CENTER, crate::i18n::tr("MISSING"), FontId::proportional(15.0 * zoom), Color32::WHITE);
} else if node.value.is_none() {
let text_color = if output { Color32::from_gray(0x20) } else { tokens.text_dim };
painter.text(body.center(), Align2::CENTER_CENTER, egui_phosphor::regular::CODE, FontId::proportional(30.0 * zoom), text_color);
} else if let Some(value) = &node.value {
// The fields are too small to use from far away, so the value is only shown
if !super::node_face::editable(zoom) {
node_card::paint_symbol(painter, body, zoom, &crate::graph::value_text::value_text(value), text_color);
}
} else if node.instance.is_some() {
node_card::paint_symbol(painter, body, zoom, egui_phosphor::regular::FUNCTION, text_color);
} else {
node_card::paint_symbol(painter, body, zoom, super::node_face::symbol(&node.op), text_color);
}
}
+151
View File
@@ -0,0 +1,151 @@
//! What a function node shows in its body: its editable value, or the symbol of its operation
use egui::{Rect, Ui, vec2};
use egui_phosphor::regular as icon;
use materialcraft_engine::core::{FunctionNode, Value};
/// Graph-space height of one value field, and the gap between two fields
const ROW_HEIGHT: f32 = 20.0;
const ROW_GAP: f32 = 3.0;
const PADDING: f32 = 6.0;
/// Body height of a node that shows a symbol
const SYMBOL_HEIGHT: f32 = 40.0;
/// Below this zoom the fields are too small to use, so the value is drawn as text
const MIN_EDIT_ZOOM: f32 = 0.45;
const MAX_EDIT_ZOOM: f32 = 1.6;
/// The sign or short word that stands for `operation` on its node
pub(super) fn symbol(operation: &str) -> &'static str {
match operation {
"add" => "+",
"sub" => "\u{2212}",
"mul" => "\u{d7}",
"mulscalar" => "k\u{d7}",
"div" => "\u{f7}",
"neg" => "\u{2212}a",
"mod" => icon::PERCENT,
"dot" => "a\u{b7}b",
"and" => "AND",
"or" => "OR",
"not" => "NOT",
"eq" => icon::EQUALS,
"noteq" => icon::NOT_EQUALS,
"gt" => icon::GREATER_THAN,
"gteq" => icon::GREATER_THAN_OR_EQUAL,
"lr" => icon::LESS_THAN,
"lreq" => icon::LESS_THAN_OR_EQUAL,
"abs" => "|x|",
"floor" => "floor",
"ceil" => "ceil",
"cos" => "cos",
"sin" => "sin",
"tan" => "tan",
"atan2" => "atan2",
"cartesian" => "polar",
"sqrt" => icon::RADICAL,
"log" => "log",
"exp" => "exp",
"log2" => "log2",
"pow2" => "2^x",
"pow" => "a^b",
"lerp" => "lerp",
"min" => "min",
"max" => "max",
"rand" => icon::DICE_FIVE,
"sequence" => icon::LIST_NUMBERS,
"ifelse" => "if",
"while" => icon::REPEAT,
"vector2" | "ivector2" => "xy",
"vector3" | "ivector3" => "xyz",
"vector4" | "ivector4" => "xyzw",
"tofloat" => "float",
"tofloat2" => "float2",
"tofloat3" => "float3",
"tofloat4" => "float4",
"toint1" => "int",
"toint2" => "int2",
"toint3" => "int3",
"toint4" => "int4",
"samplelum" => icon::EYEDROPPER,
"samplecol" => icon::EYEDROPPER_SAMPLE,
_ => icon::FUNCTION,
}
}
/// Graph-space height the body of `node` needs for its value fields or its symbol
pub(super) fn height(node: &FunctionNode) -> f32 {
match &node.value {
Some(value) if node.missing.is_none() => {
let rows = crate::value_editor::rows(value) as f32;
rows * ROW_HEIGHT + (rows - 1.0) * ROW_GAP + PADDING * 2.0
}
_ => SYMBOL_HEIGHT,
}
}
/// Whether the value of a node is edited on its face at `zoom`; it is drawn as text otherwise
pub(super) fn editable(zoom: f32) -> bool {
zoom >= MIN_EDIT_ZOOM
}
/// The value fields of a node inside `body`, sized with the canvas zoom; true when `value` changed
pub(super) fn edit(ui: &mut Ui, body: Rect, clip: Rect, zoom: f32, value: &mut Value) -> bool {
let scale = zoom.clamp(MIN_EDIT_ZOOM, MAX_EDIT_ZOOM);
let content = body.shrink(PADDING * zoom);
let mut child = ui.new_child(egui::UiBuilder::new().max_rect(content));
child.set_clip_rect(content.expand(1.0).intersect(clip));
let style = child.style_mut();
style.override_font_id = Some(egui::FontId::proportional(12.0 * scale));
style.spacing.interact_size = vec2(24.0 * scale, ROW_HEIGHT * zoom);
style.spacing.item_spacing = vec2(4.0 * scale, ROW_GAP * zoom);
style.spacing.button_padding = vec2(4.0 * scale, 0.0);
style.spacing.icon_width = 14.0 * scale;
style.spacing.icon_width_inner = 8.0 * scale;
style.spacing.icon_spacing = 4.0 * scale;
crate::value_editor::show_stacked(&mut child, value)
}
#[cfg(test)]
mod tests {
use super::*;
use materialcraft_engine::nodes::function::{FUNCTIONS, default_value};
fn node(operation: &str) -> FunctionNode {
FunctionNode {
id: 1,
type_code: 0,
op: operation.into(),
missing: None,
missing_data: String::new(),
instance: None,
source: None,
inputs: Vec::new(),
value: default_value(operation),
pos: [0.0; 2],
}
}
#[test]
fn every_operation_without_a_value_has_its_own_symbol() {
for definition in FUNCTIONS {
if definition.id == "passthrough" || default_value(definition.id).is_some() {
continue;
}
assert_ne!(symbol(definition.id), icon::FUNCTION, "{} has no symbol", definition.id);
}
}
#[test]
fn a_body_grows_with_the_components_of_its_value() {
let single = height(&node("const_float1"));
assert_eq!(height(&node("const_float4")), single + 3.0 * (ROW_HEIGHT + ROW_GAP));
assert_eq!(height(&node("add")), SYMBOL_HEIGHT);
let mut unavailable = node("const_float4");
unavailable.missing = Some(Vec::new());
assert_eq!(height(&unavailable), SYMBOL_HEIGHT);
}
}
+8 -10
View File
@@ -41,7 +41,7 @@ pub(super) fn paint(app: &mut MaterialCraftApp, editor: &mut FunctionEditor, ui:
.nodes
.iter()
.filter(|node| !selected_only || selected.contains(&node.id))
.map(|node| node_rect(node, app.ui.prefs.thumbnails))
.map(node_rect)
.fold(Rect::NOTHING, |combined, bounds| combined.union(bounds));
if !selected_only && let Some(document) = &document {
for frame in &document.frames {
@@ -146,15 +146,13 @@ pub(super) fn paint(app: &mut MaterialCraftApp, editor: &mut FunctionEditor, ui:
let body = ui.interact(screen_rect, ui.scope_id().with(("fn-node", id)), Sense::click_and_drag());
crate::widgets::name(&body, egui::Role::Button, label);
if !dot && node.missing.is_none() && node.value.is_some() {
let content = node_card::body(screen_rect, editor.zoom).shrink(6.0 * editor.zoom);
let mut child = ui.new_child(egui::UiBuilder::new().max_rect(content));
child.set_clip_rect(content.intersect(canvas_bounds));
if let Some(mut value) = node.value.clone()
&& crate::value_editor::show(&mut child, &mut value)
{
values.push((id, value));
}
if !dot
&& node.missing.is_none()
&& super::node_face::editable(editor.zoom)
&& let Some(mut value) = node.value.clone()
&& super::node_face::edit(ui, node_card::body(screen_rect, editor.zoom), canvas_bounds, editor.zoom, &mut value)
{
values.push((id, value));
}
if (body.contains_pointer() && ui.input(|input| input.pointer.primary_pressed() && !input.modifiers.alt)) || body.secondary_clicked() {
+8 -11
View File
@@ -1,4 +1,4 @@
use super::node_style::{PORT_RADIUS, header_color, node_label, node_rect, port_color};
use super::node_style::{PORT_RADIUS, header_color, node_label, node_rect, port_color, shows_preview};
use super::{GraphCamera, GraphDrag, PortHit, WireRef};
use super::{
navigation::frame,
@@ -84,7 +84,7 @@ fn canvas(app: &mut MaterialCraftApp, ui: &mut Ui) {
let mut layouts: Vec<NodeLayout> = Vec::with_capacity(graph.nodes.len());
for node in &graph.nodes {
let (ins, outs) = materialcraft_engine::eval::ports_with_connections(&app.session.pkg, node, index.incoming(node.id).iter().copied());
let mut r = node_rect(node, ins.len(), outs.len(), show_thumbnails);
let mut r = node_rect(node, ins.len(), outs.len(), show_thumbnails && shows_preview(&outs));
if selection.contains(&node.id) && node_delta.length() > 0.5 {
let position = materialcraft_engine::graph_grid::translate(node.pos, node_delta.into(), app.ui.prefs.snap_to_grid);
r = r.translate(vec2(position[0] - node.pos[0], position[1] - node.pos[1]));
@@ -184,7 +184,6 @@ fn canvas(app: &mut MaterialCraftApp, ui: &mut Ui) {
app.graph.wires = wires;
// Nodes
let font = FontId::proportional((10.5 * camera.zoom).clamp(6.0, 16.0));
let small = FontId::proportional((9.0 * camera.zoom).clamp(5.5, 13.0));
let mut node_responses: Vec<(NodeId, egui::Response)> = Vec::new();
let mut dot_grabs: Vec<Rect> = Vec::new();
@@ -218,18 +217,16 @@ fn canvas(app: &mut MaterialCraftApp, ui: &mut Ui) {
{
let side = body.width().min(body.height()) - 6.0 * camera.zoom;
let tr_ = Rect::from_center_size(body.center(), vec2(side, side));
node_card::paint_well(&painter, tr_.expand(camera.zoom), camera.zoom);
let tex = app.thumbs.node(&ctx, r0.key, 0, img);
painter.image(tex, tr_, Rect::from_min_max(Pos2::ZERO, pos2(1.0, 1.0)), if node.disabled { Color32::from_gray(90) } else { Color32::WHITE });
} else if let Some(value) = result.and_then(|result| result.outputs.first()).and_then(materialcraft_engine::eval::NodeOutput::as_value) {
let text = match value {
materialcraft_engine::core::Value::Float(value) => value.to_string(),
_ => serde_json::to_value(value).ok().and_then(|value| value.get("v").map(ToString::to_string)).unwrap_or_default(),
};
let text = crate::widgets::elided(&painter, text, font.size, theme.text, body.width() - 8.0);
painter.galley(body.center() - text.size() * 0.5, text, theme.text);
node_card::paint_well(&painter, body.shrink(4.0 * camera.zoom), camera.zoom);
node_card::paint_symbol(&painter, body, camera.zoom, &super::value_text::value_text(value), theme.text_strong);
} else if error.is_some() {
node_card::paint_symbol(&painter, body, camera.zoom, icon::WARNING, theme.danger);
} else if result.is_none() {
painter.text(body.center(), Align2::CENTER_CENTER, icon::HOURGLASS_MEDIUM, small.clone(), theme.text_dim);
node_card::paint_symbol(&painter, body, camera.zoom, icon::HOURGLASS_MEDIUM, theme.text_dim);
}
// Footer: size and format
let footer = Rect::from_min_max(pos2(screen_rect.left(), body.bottom()), screen_rect.max);
@@ -406,7 +406,8 @@ fn function_dots_wire_move_and_save_with_regular_card_geometry() {
let card = frames.app.graph.rects.iter().find(|(id, _)| id.0 == u64::from(multiply)).unwrap().1;
assert!((dot_bounds.width() / zoom - 14.0).abs() < 0.01);
assert!((card.width() / zoom - 100.0).abs() < 0.01);
assert!((card.height() / zoom - 132.0).abs() < 0.01);
// An operator shows its symbol in a body that only fits its two inputs
assert!((card.height() / zoom - 76.0).abs() < 0.01);
assert!(!frames.canvas_text.iter().any(|text| text.contains("Reroute")));
let dot_ports: Vec<_> = frames.app.graph.ports.iter().filter(|port| port.node.0 == u64::from(dot)).collect();
assert_eq!(dot_ports.len(), 2);
+2 -1
View File
@@ -34,7 +34,7 @@ pub use graph_view::GraphView;
pub use library_drag::LibraryDrag;
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 node_style::{NODE_W, header_color, node_label, node_rect, port_color, shows_preview};
pub use port_hit::PortHit;
pub use wire_actions::{delete_selected_wires, swap_selected_wires};
pub type WireRef = (materialcraft_engine::core::NodeId, String);
@@ -48,6 +48,7 @@ mod node_style;
mod search;
pub(crate) mod selection_commands;
pub(crate) mod toolbar;
pub(crate) mod value_text;
pub(crate) mod wire_actions;
pub(crate) mod wire_geometry;
pub(crate) mod wire_selection;
+2 -2
View File
@@ -1,4 +1,4 @@
use super::{NODE_W, node_rect};
use super::{NODE_W, node_rect, shows_preview};
use crate::MaterialCraftApp;
use egui::{Pos2, Rect, pos2, vec2};
use serde_json::json;
@@ -42,7 +42,7 @@ pub(super) fn frame(app: &mut MaterialCraftApp, view: Rect, only_selection: bool
}
let (inputs, outputs) = materialcraft_engine::eval::ports(&app.session.pkg, g, n);
r = r.union(node_rect(n, inputs.len(), outputs.len(), thumbs));
r = r.union(node_rect(n, inputs.len(), outputs.len(), thumbs && shows_preview(&outputs)));
}
for f in &g.frames {
if !only_selection {
+33 -6
View File
@@ -7,16 +7,25 @@ const PORT_GAP: f32 = 18.0;
const DOT_RADIUS: f32 = 7.0;
/// Smallest on-screen side of a dot's grab area, in points
const DOT_MIN_GRAB: f32 = 16.0;
const CARD_COLOR: Color32 = Color32::from_rgb(0x1e, 0x20, 0x24);
const WELL_COLOR: Color32 = Color32::from_rgb(0x14, 0x15, 0x18);
/// Body height of a node that shows no preview and has at most one port a side
const BARE_BODY_HEIGHT: f32 = 26.0;
pub(crate) fn bounds(position: [f32; 2], inputs: usize, outputs: usize, previews: bool, dot: bool) -> Rect {
bounds_with_body(position, inputs, outputs, if previews { WIDTH } else { BARE_BODY_HEIGHT }, dot)
}
/// A card whose body is at least `body_height` tall and fits its ports
pub(crate) fn bounds_with_body(position: [f32; 2], inputs: usize, outputs: usize, body_height: f32, dot: bool) -> Rect {
let position = pos2(position[0], position[1]);
if dot {
return Rect::from_center_size(position, vec2(DOT_RADIUS * 2.0, DOT_RADIUS * 2.0));
}
let ports = inputs.max(outputs) as f32 * PORT_GAP + 8.0;
let body = if previews { WIDTH.max(ports) } else { ports.max(26.0) };
Rect::from_min_size(position, vec2(WIDTH, HEADER_HEIGHT + body + FOOTER_HEIGHT))
Rect::from_min_size(position, vec2(WIDTH, HEADER_HEIGHT + body_height.max(ports) + FOOTER_HEIGHT))
}
/// The on-screen area that picks up dot `bounds`: at least `DOT_MIN_GRAB` wide, so it stays easy to grab when zoomed out
@@ -46,11 +55,29 @@ pub(crate) fn body(bounds: Rect, zoom: f32) -> Rect {
pub(crate) fn paint(painter: &Painter, bounds: Rect, zoom: f32, label: &str, color: Color32) {
let radius = (5.0 * zoom).clamp(1.0, 6.0) as u8;
let header = header(bounds, zoom);
painter.rect_filled(bounds, radius, Color32::from_rgb(0x1e, 0x20, 0x24));
painter.rect_filled(bounds, radius, CARD_COLOR);
painter.rect_filled(header, CornerRadius { nw: radius, ne: radius, sw: 0, se: 0 }, color);
let font = FontId::proportional((10.5 * zoom).clamp(6.0, 16.0));
let title = crate::widgets::elided(painter, label, font.size, Color32::WHITE, header.width() - 8.0);
painter.galley(header.left_center() + vec2(4.0, -title.size().y * 0.5), title, Color32::WHITE);
painter.line_segment([header.left_bottom(), header.right_bottom()], Stroke::new(1.0, Color32::from_black_alpha(110)));
let font = FontId::proportional((11.0 * zoom).clamp(7.0, 16.0));
let title = crate::widgets::elided(painter, label, font.size, Color32::WHITE, header.width() - 10.0 * zoom);
painter.galley(header.left_center() + vec2(5.0 * zoom, -title.size().y * 0.5), title, Color32::WHITE);
}
/// The dark well a preview or a value sits in, inside `body`
pub(crate) fn paint_well(painter: &Painter, well: Rect, zoom: f32) {
painter.rect_filled(well, (3.0 * zoom).clamp(1.0, 4.0) as u8, WELL_COLOR);
}
/// A short symbol or word centered in `body`, as large as its length allows
pub(crate) fn paint_symbol(painter: &Painter, body: Rect, zoom: f32, symbol: &str, color: Color32) {
let size = match symbol.chars().count() {
0..=2 => 24.0,
3..=4 => 17.0,
_ => 13.0,
};
let text = crate::widgets::elided(painter, symbol, size * zoom, color, body.width() - 12.0 * zoom);
painter.galley(body.center() - text.size() * 0.5, text, color);
}
pub(crate) fn outline(painter: &Painter, bounds: Rect, zoom: f32, stroke: Stroke) {
+5
View File
@@ -68,6 +68,11 @@ pub fn node_label(n: &Node) -> String {
})
}
/// Whether a node with these outputs has a picture to show; a node that only outputs values shows its number in a short body
pub fn shows_preview(outputs: &[materialcraft_engine::eval::Port]) -> bool {
outputs.is_empty() || outputs.iter().any(|port| port.kind != PortKind::Value)
}
/// Graph-space rectangle of a node card
pub fn node_rect(node: &Node, inputs: usize, outputs: usize, previews: bool) -> Rect {
node_card::bounds(node.pos, inputs, outputs, previews, node.def == "dot")
+56
View File
@@ -0,0 +1,56 @@
use materialcraft_engine::core::Value;
/// `value` as a node face shows it: short numbers, vector components separated by commas
pub(crate) fn value_text(value: &Value) -> String {
match value {
Value::Float(value) => number(*value),
Value::Float2(values) => numbers(values),
Value::Float3(values) => numbers(values),
Value::Float4(values) | Value::Color(values) => numbers(values),
Value::Int(value) => value.to_string(),
Value::Int2(values) => integers(values),
Value::Int3(values) => integers(values),
Value::Int4(values) => integers(values),
Value::Bool(value) => crate::i18n::tr(if *value { "True" } else { "False" }).into(),
Value::Enum(value) => value.to_string(),
Value::Text(value) => value.clone(),
Value::Curve(_) | Value::Gradient(_) | Value::Function(_) | Value::PatternGraph(_) => String::new(),
}
}
/// At most three decimals, without trailing zeros
fn number(value: f32) -> String {
if !value.is_finite() {
return value.to_string();
}
let text = format!("{value:.3}");
let text = text.trim_end_matches('0').trim_end_matches('.');
if text == "-0" { "0".into() } else { text.into() }
}
fn numbers(values: &[f32]) -> String {
values.iter().map(|value| number(*value)).collect::<Vec<_>>().join(", ")
}
fn integers(values: &[i32]) -> String {
values.iter().map(ToString::to_string).collect::<Vec<_>>().join(", ")
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn numbers_are_short_and_vectors_list_their_components() {
assert_eq!(value_text(&Value::Float(0.5)), "0.5");
assert_eq!(value_text(&Value::Float(2.0)), "2");
assert_eq!(value_text(&Value::Float(-0.0001)), "0");
assert_eq!(value_text(&Value::Float(1.0 / 3.0)), "0.333");
assert_eq!(value_text(&Value::Float(f32::NAN)), "NaN");
assert_eq!(value_text(&Value::Float3([1.0, 0.25, -3.5])), "1, 0.25, -3.5");
assert_eq!(value_text(&Value::Int2([4, -7])), "4, -7");
assert_eq!(value_text(&Value::Bool(true)), "True");
assert_eq!(value_text(&Value::Text("size".into())), "size");
}
}
+51 -4
View File
@@ -128,20 +128,63 @@ pub fn show(app: &mut MaterialCraftApp, ui: &mut Ui) {
ui.add_space(2.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);
// Unless dragged, the tree takes what the tiles leave: one column of tiles in a narrow panel
let automatic = (available_size.x * 0.6).clamp(120.0, 230.0);
let chosen = if app.ui.library_tree_width > 0.0 { app.ui.library_tree_width } else { automatic };
let tree_width = tree_width(chosen, available_size.x);
let top_down = egui::Layout::top_down(egui::Align::Min);
ui.horizontal_top(|ui| {
ui.spacing_mut().item_spacing.x = 0.0;
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();
match divider(ui, tree_width, available_size.y) {
Some(Divider::Dragged(width)) => app.ui.library_tree_width = self::tree_width(width, available_size.x),
Some(Divider::Reset) => app.ui.library_tree_width = 0.0,
None => {}
}
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));
});
});
}
/// The tree's width in a panel `available` wide: neither the tree nor the tiles close completely
fn tree_width(chosen: f32, available: f32) -> f32 {
const NARROWEST_TREE: f32 = 60.0;
const NARROWEST_TILES: f32 = 92.0;
chosen.min(available - NARROWEST_TILES).max(NARROWEST_TREE)
}
/// What the pointer did to the Library's divider
enum Divider {
/// Dragged to this tree width
Dragged(f32),
/// Double-clicked: back to the automatic width
Reset,
}
/// The draggable bar between the tree and the tiles
fn divider(ui: &mut Ui, tree_width: f32, height: f32) -> Option<Divider> {
let tokens = Tokens::get(ui.ctx());
let (rect, response) = ui.allocate_exact_size(vec2(9.0, height), Sense::click_and_drag());
crate::widgets::name(&response, egui::Role::Splitter, "Library divider");
let response = response.on_hover_cursor(egui::CursorIcon::ResizeHorizontal);
if response.dragged() {
ui.ctx().set_cursor_icon(egui::CursorIcon::ResizeHorizontal);
}
let active = response.hovered() || response.dragged();
let line = Rect::from_center_size(rect.center(), vec2(if active { 2.0 } else { 1.0 }, height));
ui.painter().rect_filled(line, 0.0, if active { tokens.accent } else { tokens.text_dim.gamma_multiply(0.35) });
if response.double_clicked() {
return Some(Divider::Reset);
}
response.dragged().then(|| Divider::Dragged(tree_width + response.drag_delta().x))
}
/// 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;
@@ -366,11 +409,15 @@ fn items(app: &mut MaterialCraftApp, ui: &mut Ui, entries: &[LibraryEntry], targ
}
}
/// The entry's thumbnail: a cooked preview for native nodes, its category's icon otherwise
/// The entry's thumbnail: a cooked preview for native nodes and library graphs, 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)),
// Only tiles on screen ask for their graph to be cooked
LibraryItem::Instance { package, graph } if entry.missing.is_none() && ui.is_rect_visible(rect) => {
(app.thumbs.graph(ctx, &app.session.library, package, graph), category_color(&entry.category))
}
_ => (None, category_color(&entry.category)),
};
match texture {
+8
View File
@@ -165,3 +165,11 @@ fn graph_items_are_available_and_insertable_in_every_editor() {
assert_eq!((items.comments.len(), items.frames.len(), items.pins.len()), (1, 1, 1), "{kind}");
}
}
#[test]
fn the_divider_leaves_room_for_the_tree_and_the_tiles() {
assert_eq!(tree_width(150.0, 400.0), 150.0);
assert_eq!(tree_width(5.0, 400.0), 60.0, "the tree never closes");
assert_eq!(tree_width(390.0, 400.0), 308.0, "the tiles keep one column");
assert_eq!(tree_width(200.0, 100.0), 60.0, "a panel too narrow for both keeps the tree");
}
+3
View File
@@ -26,6 +26,8 @@ pub struct UiState {
/// The library entry last clicked
#[serde(skip)]
pub library_selected: Option<String>,
/// Width of the Library's category tree, set by dragging its divider; 0 = automatic
pub library_tree_width: f32,
/// Recently opened or saved packages, newest first
pub recent: Vec<String>,
/// New graph dialog fields
@@ -59,6 +61,7 @@ impl Default for UiState {
library_show_missing: true,
library_show_other: true,
library_selected: None,
library_tree_width: 0.0,
recent: Vec::new(),
new_graph_kind: materialcraft_engine::core::GraphKind::Material,
new_graph_template: "pbr".into(),
+100
View File
@@ -19,6 +19,7 @@ pub struct Thumbs {
library: HashMap<String, TextureHandle>,
library_rx: Option<Receiver<Previews>>,
library_started: bool,
graphs: GraphPreviews,
frame: u64,
}
@@ -28,6 +29,92 @@ pub fn color_image(img: &Image, side: u32) -> ColorImage {
ColorImage::from_rgba_unmultiplied([side as usize, side as usize], &small.to_rgba8_display())
}
/// Previews of library graphs: one worker cooks the requested graphs, newest request first
#[derive(Default)]
struct GraphPreviews {
/// The library the previews were cooked from; a reload starts over
library: Option<std::sync::Arc<materialcraft_engine::NodeLibrary>>,
/// Requested graphs: `None` while cooking and for graphs without an image
textures: HashMap<(String, String), Option<TextureHandle>>,
requests: GraphRequests,
results: GraphResults,
}
impl GraphPreviews {
fn get(&mut self, ctx: &egui::Context, library: &std::sync::Arc<materialcraft_engine::NodeLibrary>, package: &str, graph: &str) -> Option<egui::TextureId> {
if !self.library.as_ref().is_some_and(|current| std::sync::Arc::ptr_eq(current, library)) {
*self = GraphPreviews { library: Some(library.clone()), ..GraphPreviews::default() };
(self.requests, self.results) = spawn_graph_previews(ctx.clone(), library.clone());
}
let key = (package.to_string(), graph.to_string());
if let Some(texture) = self.textures.get(&key) {
return texture.as_ref().map(TextureHandle::id);
}
if let Some(requests) = &self.requests {
let _ = requests.send(key.clone());
}
self.textures.insert(key, None);
None
}
/// Upload the previews the worker finished since the last frame
fn collect(&mut self, ctx: &egui::Context) {
let Some(results) = &self.results else { return };
for ((package, graph), rgba) in results.try_iter() {
let texture = rgba.map(|rgba| {
let image = ColorImage::from_rgba_unmultiplied([LIBRARY_PREVIEW_SIZE as usize, LIBRARY_PREVIEW_SIZE as usize], &rgba);
ctx.load_texture(format!("library-graph-{package}#{graph}"), image, TextureOptions::LINEAR)
});
self.textures.insert((package, graph), texture);
}
}
}
type GraphRequests = Option<std::sync::mpsc::Sender<(String, String)>>;
type GraphResults = Option<Receiver<((String, String), Option<Vec<u8>>)>>;
/// Start the worker that cooks requested library graphs; it ends when the requests' sender is dropped
#[cfg(not(target_arch = "wasm32"))]
fn spawn_graph_previews(ctx: egui::Context, library: std::sync::Arc<materialcraft_engine::NodeLibrary>) -> (GraphRequests, GraphResults) {
let (request_tx, request_rx) = std::sync::mpsc::channel::<(String, String)>();
let (result_tx, result_rx) = std::sync::mpsc::channel();
let worker = std::thread::Builder::new().name("materialcraft-library-graphs".into()).spawn(move || {
let mut waiting = Vec::new();
loop {
// The tiles scrolled into view last are cooked first
waiting.extend(request_rx.try_iter());
let next = match waiting.pop() {
Some(next) => next,
None => match request_rx.recv() {
Ok(next) => next,
Err(_) => return,
},
};
let image = materialcraft_engine::NodeLibrary::preview(&library, &next.0, &next.1, LIBRARY_PREVIEW_SIZE);
let rgba = image.map(|image| image.resize(LIBRARY_PREVIEW_SIZE, LIBRARY_PREVIEW_SIZE, true).to_rgba8_display());
if result_tx.send((next, rgba)).is_err() {
return;
}
ctx.request_repaint();
}
});
match worker {
Ok(_) => (Some(request_tx), Some(result_rx)),
Err(_) => (None, None),
}
}
/// The browser build has no worker thread: library graphs keep their category icon
#[cfg(target_arch = "wasm32")]
fn spawn_graph_previews(_ctx: egui::Context, _library: std::sync::Arc<materialcraft_engine::NodeLibrary>) -> (GraphRequests, GraphResults) {
(None, None)
}
impl Thumbs {
pub fn clear_nodes(&mut self) {
self.nodes.clear();
@@ -62,6 +149,19 @@ impl Thumbs {
}
self.library_rx = None;
}
self.graphs.collect(ctx);
}
/// The preview of library graph `graph` of `package`, cooked in the background on first use;
/// `None` until it is ready and for graphs that make no image
pub fn graph(
&mut self,
ctx: &egui::Context,
library: &std::sync::Arc<materialcraft_engine::NodeLibrary>,
package: &str,
graph: &str,
) -> Option<egui::TextureId> {
self.graphs.get(ctx, library, package, graph)
}
/// The library preview of node `def` (generated in the background on first use)
+56 -23
View File
@@ -3,18 +3,44 @@ use materialcraft_engine::core::Value;
/// Edit a function value within the available width
pub(crate) fn show(ui: &mut Ui, value: &mut Value) -> bool {
ui.horizontal_wrapped(|ui| match value {
Value::Float(value) => float(ui, value, "Value"),
Value::Float2(values) => floats(ui, values, &["X", "Y"]),
Value::Float3(values) => floats(ui, values, &["X", "Y", "Z"]),
Value::Float4(values) => floats(ui, values, &["X", "Y", "Z", "W"]),
Value::Color(values) => floats(ui, values, &["Red", "Green", "Blue", "Alpha"]),
Value::Int(value) => integer(ui, value, "Value"),
Value::Int2(values) => integers(ui, values),
Value::Int3(values) => integers(ui, values),
Value::Int4(values) => integers(ui, values),
ui.horizontal_wrapped(|ui| fields(ui, value, false)).inner
}
/// Edit a function value with one full-width field per component, as a node face shows it
pub(crate) fn show_stacked(ui: &mut Ui, value: &mut Value) -> bool {
ui.vertical(|ui| fields(ui, value, true)).inner
}
/// How many fields `show_stacked` lays out for `value`
pub(crate) fn rows(value: &Value) -> usize {
match value {
Value::Float2(_) | Value::Int2(_) => 2,
Value::Float3(_) | Value::Int3(_) => 3,
Value::Float4(_) | Value::Int4(_) | Value::Color(_) => 4,
_ => 1,
}
}
fn fields(ui: &mut Ui, value: &mut Value, stacked: bool) -> bool {
match value {
Value::Float(value) => float(ui, value, "Value", stacked),
Value::Float2(values) => floats(ui, values, &["X", "Y"], stacked),
Value::Float3(values) => floats(ui, values, &["X", "Y", "Z"], stacked),
Value::Float4(values) => floats(ui, values, &["X", "Y", "Z", "W"], stacked),
Value::Color(values) => floats(ui, values, &["Red", "Green", "Blue", "Alpha"], stacked),
Value::Int(value) => integer(ui, value, "Value", stacked),
Value::Int2(values) => integers(ui, values, stacked),
Value::Int3(values) => integers(ui, values, stacked),
Value::Int4(values) => integers(ui, values, stacked),
Value::Bool(value) => {
let response = ui.checkbox(value, "");
let text = if !stacked {
""
} else if *value {
"True"
} else {
"False"
};
let response = ui.checkbox(value, crate::i18n::tr(text));
crate::widgets::name(&response, egui::Role::CheckBox, "Value");
response.changed()
}
@@ -24,34 +50,41 @@ pub(crate) fn show(ui: &mut Ui, value: &mut Value) -> bool {
response.changed()
}
_ => false,
})
.inner
}
}
fn float(ui: &mut Ui, value: &mut f32, label: &str) -> bool {
let response = ui.add(egui::DragValue::new(value).speed(0.01).max_decimals(3));
/// A stacked field fills the row and names its component in front of the number
fn field(ui: &mut Ui, drag: egui::DragValue<'_>, label: &str, stacked: bool) -> bool {
let response = if stacked {
let drag = if label == "Value" { drag } else { drag.prefix(format!("{} ", label.chars().next().unwrap_or(' '))) };
ui.add_sized([ui.available_width(), ui.spacing().interact_size.y], drag)
} else {
ui.add(drag)
};
crate::widgets::name(&response, egui::Role::SpinButton, label);
response.changed()
}
fn floats(ui: &mut Ui, values: &mut [f32], labels: &[&str]) -> bool {
fn float(ui: &mut Ui, value: &mut f32, label: &str, stacked: bool) -> bool {
field(ui, egui::DragValue::new(value).speed(0.01).max_decimals(3), label, stacked)
}
fn floats(ui: &mut Ui, values: &mut [f32], labels: &[&str], stacked: bool) -> bool {
let mut changed = false;
for (value, label) in values.iter_mut().zip(labels) {
changed |= float(ui, value, label);
changed |= float(ui, value, label, stacked);
}
changed
}
fn integer(ui: &mut Ui, value: &mut i32, label: &str) -> bool {
let response = ui.add(egui::DragValue::new(value).speed(0.1));
crate::widgets::name(&response, egui::Role::SpinButton, label);
response.changed()
fn integer(ui: &mut Ui, value: &mut i32, label: &str, stacked: bool) -> bool {
field(ui, egui::DragValue::new(value).speed(0.1), label, stacked)
}
fn integers(ui: &mut Ui, values: &mut [i32]) -> bool {
fn integers(ui: &mut Ui, values: &mut [i32], stacked: bool) -> bool {
let mut changed = false;
for (value, label) in values.iter_mut().zip(["X", "Y", "Z", "W"]) {
changed |= integer(ui, value, label);
changed |= integer(ui, value, label, stacked);
}
changed
}
+1
View File
@@ -6,6 +6,7 @@ mod dialogs;
mod export_window;
mod graph_properties;
mod interface_scale;
mod node_look;
mod normal_maps;
mod numeric_input;
mod preview_resolution;
+81
View File
@@ -0,0 +1,81 @@
//! The Library's draggable divider and the faces of function nodes
use egui::accesskit::Role;
use egui::{Event, Modifiers, PointerButton, Pos2, vec2};
use egui_kittest::Harness;
use egui_kittest::kittest::{By, Queryable};
use materialcraft_ui_egui::{MaterialCraftApp, UiState};
use serde_json::json;
fn harness(app: MaterialCraftApp) -> Harness<'static, MaterialCraftApp> {
// Short steps keep two clicks within the double-click delay
let mut harness = Harness::builder().with_size(vec2(1600.0, 960.0)).with_pixels_per_point(1.0).with_step_dt(0.05).build_ui_state(
|ui, app: &mut MaterialCraftApp| {
app.step(&ui.ctx().clone());
app.draw(ui);
},
app,
);
harness.run_steps(6);
harness
}
fn press(harness: &mut Harness<'static, MaterialCraftApp>, at: Pos2, pressed: bool) {
harness.event(Event::PointerButton { pos: at, button: PointerButton::Primary, pressed, modifiers: Modifiers::NONE });
harness.step();
}
fn divider(harness: &Harness<'static, MaterialCraftApp>) -> Pos2 {
harness.get(By::new().role(Role::Splitter).label("Library divider")).rect().center()
}
#[test]
fn the_library_divider_drags_the_tree_narrower_and_a_double_click_resets_it() {
let mut harness = harness(MaterialCraftApp::headless(materialcraft_engine::new_session(), UiState::default()));
assert_eq!(harness.state().ui.library_tree_width, 0.0, "the tree starts at its automatic width");
let start = divider(&harness);
harness.event(Event::PointerMoved(start));
harness.step();
press(&mut harness, start, true);
for step in 1..=6 {
harness.event(Event::PointerMoved(start - vec2(10.0 * step as f32, 0.0)));
harness.step();
}
press(&mut harness, start - vec2(60.0, 0.0), false);
harness.run_steps(3);
let dragged = harness.state().ui.library_tree_width;
assert!(dragged > 0.0, "a drag chooses a width");
let moved = start.x - divider(&harness).x;
assert!((40.0..=62.0).contains(&moved), "the divider follows the pointer, moved {moved}");
let at = divider(&harness);
harness.event(Event::PointerMoved(at));
harness.step();
for pressed in [true, false, true, false] {
press(&mut harness, at, pressed);
}
harness.run_steps(3);
assert_eq!(harness.state().ui.library_tree_width, 0.0, "a double click returns to the automatic width");
assert!((divider(&harness).x - start.x).abs() < 1.0);
}
#[test]
fn a_constant_node_fits_a_field_for_each_component() {
let mut app = MaterialCraftApp::headless(materialcraft_engine::new_session(), UiState::default());
app.run("file.new", json!({"kind": "function", "name": "Faces"})).unwrap();
app.run("graph.function.edit", json!({"edit": {"action": "add", "operation": "const_float4", "at": [0, 0]}})).unwrap();
app.run("graph.function.edit", json!({"edit": {"action": "add", "operation": "add", "at": [200, 0]}})).unwrap();
let harness = harness(app);
let card = harness.get(By::new().role(Role::Button).label("Float4")).rect();
for component in ["X", "Y", "Z", "W"] {
let field = harness.get(By::new().role(Role::SpinButton).label(component)).rect();
assert!(card.contains_rect(field), "{component} lies inside its node: {field:?} in {card:?}");
}
let operator = harness.get(By::new().role(Role::Button).label("Add")).rect();
assert!(operator.height() < card.height(), "an operator is a compact node");
assert!(operator.height() < operator.width(), "an operator has no empty preview square");
}
+3
View File
@@ -10,6 +10,9 @@ mod explorer;
#[path = "snapshot/export.rs"]
mod export;
#[path = "snapshot/node_look.rs"]
mod node_look;
#[path = "snapshot/function_instances.rs"]
mod function_instances;
@@ -0,0 +1,90 @@
use super::{By, MaterialCraftApp, Queryable, UiState, harness, json, save, settle};
use egui::accesskit::Role;
fn directory() -> std::path::PathBuf {
let directory = std::path::PathBuf::from(std::env::var_os("MC_SNAPSHOT_DIR").unwrap());
std::fs::create_dir_all(&directory).unwrap();
directory
}
#[test]
#[ignore = "requires an offscreen GPU; run explicitly with --ignored"]
fn function_nodes_show_their_values_and_symbols() {
let mut app = MaterialCraftApp::headless(materialcraft_engine::new_session(), UiState::default());
app.run("file.new", json!({"kind": "function", "name": "Look"})).unwrap();
let operations = [
("const_float1", [0, 0]),
("const_float2", [0, 120]),
("const_float4", [0, 260]),
("const_int1", [0, 420]),
("const_bool", [0, 520]),
("get_float1", [160, 0]),
("add", [160, 120]),
("mul", [160, 240]),
("div", [160, 360]),
("gt", [320, 0]),
("sqrt", [320, 120]),
("lerp", [320, 240]),
("ifelse", [320, 380]),
("vector3", [480, 0]),
("swizzle2", [480, 120]),
("sin", [480, 240]),
("min", [480, 360]),
];
for (operation, at) in operations {
app.run("graph.function.edit", json!({"edit": {"action": "add", "operation": operation, "at": at}})).unwrap();
}
let mut harness = harness(app, 1600.0, 960.0);
settle(&mut harness, 8);
save(&mut harness, &directory(), "look-function-nodes");
}
#[test]
#[ignore = "requires an offscreen GPU; run explicitly with --ignored"]
fn library_nodes_and_tiles_show_previews() {
let mut app = MaterialCraftApp::headless(materialcraft_engine::new_session(), UiState::default());
let entries = [
("node:uniform", [0, 0]),
("node:blur", [160, 0]),
("sbs://blur_hq.sbs#blur_hq", [320, 0]),
("sbs://edge_detect.sbs#edge_detect", [480, 0]),
("sbs://materials/pbr/bricks_001.sbs#bricks_001", [0, 220]),
("sbs://pattern_tile_sampler.sbs#tile_sampler", [200, 220]),
("sbs://mg_mask_builder.sbs#mg_mask_builder_2", [400, 220]),
("node:input_value", [640, 0]),
("node:value_processor", [640, 100]),
];
for (entry, at) in entries {
app.run("library.add", json!({"entry": entry, "at": at})).unwrap();
}
let mut harness = harness(app, 1600.0, 960.0);
// The graph cooks on a worker
for _ in 0..480 {
std::thread::sleep(std::time::Duration::from_millis(250));
settle(&mut harness, 2);
let session = &harness.state().session;
if session.graph().is_ok_and(|graph| session.cooked.nodes.len() >= graph.nodes.len()) {
break;
}
}
save(&mut harness, &directory(), "look-library-nodes");
for (top, sub, name) in
[("Filters", "Blurs", "look-library-blurs"), ("PBR materials", "Bricks", "look-library-bricks"), ("Functions", "Constant", "look-library-functions")]
{
harness.get(By::new().role(Role::TreeItem).label(top)).click();
settle(&mut harness, 3);
harness.get_all(By::new().role(Role::TreeItem).label(sub)).next().unwrap().click();
// Previews cook on a worker
for _ in 0..40 {
std::thread::sleep(std::time::Duration::from_millis(250));
settle(&mut harness, 2);
}
save(&mut harness, &directory(), name);
harness.get(By::new().role(Role::TreeItem).label(top)).click();
settle(&mut harness, 2);
harness.get(By::new().role(Role::TreeItem).label(top)).click();
settle(&mut harness, 2);
}
}