Evaluate shared pattern draws and scalar inputs in returned channel order

This commit is contained in:
chasse20 committed 2026-11-21 16:14:26 -05:00
1 parent fa77a30ee9
commit a45240f017
9 files changed
+371 -34

No files matched your search

+51 -11
View File
@@ -1,25 +1,62 @@
use super::Program;
use super::{Program, vector::PatternComponent};
use materialcraft_core::Value;
use std::collections::{BTreeMap, BTreeSet};
/// Schedule draws shared by a pixel branch and another part of its expression. An arm's
pub(super) struct PatternDraws {
shared: Vec<usize>,
true_count: usize,
}
impl PatternDraws {
// The true arm occurs first. A skipped arm still consumes any draw needed outside it.
pub(super) fn skipped(&self, take_true: bool) -> &[usize] {
let (through_true, through_false_only) = self.shared.split_at(self.true_count);
if take_true { through_false_only } else { through_true }
}
}
/// Schedule draws shared by an image branch and another part of its expression. An arm's
/// private draws stay lazy. The condition itself always runs first.
pub(super) fn identify(program: &mut Program) {
let instructions = &program.instructions;
if !instructions.iter().any(|op| op.definition.id == "ifelse")
|| !instructions.iter().any(|op| op.definition.id == "rand")
|| instructions.iter().any(|op| matches!(op.definition.id, "while" | "set") || op.call.as_ref().is_some_and(|call| call.exports))
|| instructions.iter().any(|op| op.definition.id == "while" || op.call.as_ref().is_some_and(|call| call.exports))
{
return;
}
// A range depending on assignment or image evaluation must stay at its original read.
let written: BTreeSet<_> = instructions
.iter()
.filter_map(|op| match (&op.value, op.definition.id) {
(Some(Value::Text(name)), "set") => Some(name.as_str()),
_ => None,
})
.collect();
// A range depending on an assignment or image sample must stay at its original read.
let mut simple = Vec::with_capacity(instructions.len());
let mut pattern_range = Vec::with_capacity(instructions.len());
for op in instructions {
simple.push(op.type_code == 256 && (op.definition.id == "const_float1" || (op.definition.id == "rand" && op.inputs.iter().all(|&i| simple[i]))));
let fixed_input = op.definition.id == "get_float1" && matches!(&op.value, Some(Value::Text(name)) if !written.contains(name.as_str()));
pattern_range.push(op.type_code == 256 && (op.literal || fixed_input || (op.definition.id == "rand" && op.inputs.iter().all(|&i| pattern_range[i]))));
}
let pixel = if written.is_empty() { shared_draws(program, &simple, None) } else { BTreeMap::new() };
// A called graph can observe the caller's assignments without listing them among its inputs.
if written.is_empty() || instructions.iter().all(|op| op.call.is_none()) {
program.pattern_draws = shared_draws(program, &pattern_range, Some(&program.pattern_components));
}
for (index, draws) in pixel {
program.instructions[index].control_registers = draws.shared;
}
}
fn shared_draws(program: &Program, ranges: &[bool], components: Option<&BTreeMap<usize, PatternComponent>>) -> BTreeMap<usize, PatternDraws> {
let instructions = &program.instructions;
let mut paths = vec![0_u8; instructions.len()];
let mut stack = Vec::new();
let mut draws = Vec::new();
let mut plans = Vec::new();
let mut plans = BTreeMap::new();
for (branch, op) in instructions.iter().enumerate().filter(|(_, op)| op.definition.id == "ifelse") {
let &[_, yes, no] = op.inputs.as_slice() else { continue };
paths.fill(0);
@@ -35,19 +72,22 @@ pub(super) fn identify(program: &mut Program) {
continue;
}
let node = &instructions[index];
if paths[index] == 0 && path != 4 && simple[index] && node.definition.id == "rand" && !node.inputs.is_empty() {
if paths[index] == 0 && path != 4 && ranges[index] && node.definition.id == "rand" && !node.inputs.is_empty() {
draws.push(index);
}
paths[index] |= path;
stack.extend(node.inputs.iter().rev().copied());
match components.and_then(|components| components.get(&index)) {
Some(PatternComponent::Scalar(source)) => stack.push(*source),
Some(PatternComponent::Zero) => {}
None => stack.extend(node.inputs.iter().rev().copied()),
}
}
}
let shared: Vec<_> = draws.iter().copied().filter(|&i| paths[i].count_ones() > 1).collect();
if !shared.is_empty() {
plans.push((branch, shared));
let true_count = shared.iter().take_while(|&&i| paths[i] & 1 != 0).count();
plans.insert(branch, PatternDraws { shared, true_count });
}
}
for (index, shared) in plans {
program.instructions[index].control_registers = shared;
}
plans
}
+6 -4
View File
@@ -154,9 +154,9 @@ fn compile_nested(graph: &FunctionGraph, seed: u32, depth: usize, remaining: &mu
return Err(format!("{}: input `{}` has the wrong type", instance.graph, port.identifier));
}
}
let inputs: Vec<_> = ports.iter().filter(|(_, input)| input.is_some()).map(|(name, _)| (*name).to_string()).collect();
let names: Vec<_> = ports.iter().filter(|(_, input)| input.is_some()).map(|(name, _)| (*name).to_string()).collect();
let mut defaults = instance.defaults.clone();
if !inputs.is_empty() {
if !names.is_empty() {
// Once a call supplies arguments, an omitted numeric argument reads its typed zero.
for (name, input) in &ports {
if input.is_none()
@@ -170,7 +170,8 @@ fn compile_nested(graph: &FunctionGraph, seed: u32, depth: usize, remaining: &mu
}
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, argument_factors: None, exports })
let pattern_arguments = super::function_call::PatternArguments::identify(&program, &names, &defaults, &inputs);
Some(super::function_call::FunctionCall { program, inputs: names, defaults, argument_factors: None, pattern_arguments, exports })
} else {
None
};
@@ -226,7 +227,7 @@ fn compile_nested(graph: &FunctionGraph, seed: u32, depth: usize, remaining: &mu
let output = indices.get(&output).copied().ok_or("missing result instruction")?;
Ok(Program { instructions, output, seed })
Ok(Program { instructions, output, seed, pattern_draws: BTreeMap::new(), pattern_components: BTreeMap::new() })
}
fn mark_literals(program: &mut Program, mut arguments: BTreeSet<&str>, pixel: Option<&super::EvaluationContext<'_>>) -> super::returned_product::Lanes {
@@ -272,6 +273,7 @@ fn mark_literals(program: &mut Program, mut arguments: BTreeSet<&str>, pixel: Op
let readers = pixel.and_then(|context| super::pixel_condition::live_readers(program, context));
super::product_sum::identify(&mut program.instructions, readers.as_deref());
super::branch_assignments::identify(program);
super::vector::identify_pattern_components(program);
super::branch_random::identify(program);
super::returned_product::identify(program, returned)
}
@@ -10,10 +10,67 @@ pub(crate) struct FunctionCall {
pub defaults: BTreeMap<String, Value>,
/// Parent registers for an argument used only in scalar sums within the call.
pub argument_factors: Option<[usize; 2]>,
pub(super) pattern_arguments: Option<PatternArguments>,
/// The called graph sets variables, directly or in a graph it calls; the caller reads them after the call
pub exports: bool,
}
/// First uses of scalar arguments in a straight-line pattern function, including directly returned channels.
pub(super) struct PatternArguments {
pub registers: Vec<usize>,
pub slots: Vec<usize>,
pub channels: [Option<usize>; 4],
}
impl PatternArguments {
pub(super) fn identify(program: &Program, names: &[String], defaults: &BTreeMap<String, Value>, registers: &[usize]) -> Option<Self> {
if names.is_empty() || !defaults.values().all(|v| matches!(v, Value::Float(_))) {
return None;
}
let slots_by_name: BTreeMap<_, _> = names.iter().enumerate().map(|(slot, name)| (name.as_str(), slot)).collect();
let mut seen = vec![false; names.len()];
let mut slots = Vec::new();
let mut origins = Vec::with_capacity(program.instructions.len());
for op in &program.instructions {
let mut lanes = [None; 4];
if let ("get_float1", Some(Value::Text(name))) = (op.definition.id, &op.value) {
if name.starts_with('$') {
return None;
}
defaults.get(name)?;
if let Some(&slot) = slots_by_name.get(name.as_str()) {
lanes[0] = Some(slot);
if !std::mem::replace(seen.get_mut(slot)?, true) {
slots.push(slot);
}
}
} else if let Some(forwarded) = super::returned_product::forwarded(op, &program.instructions, &origins, None) {
lanes = forwarded;
} else if !op.definition.id.starts_with("const_") && (!op.depends_only_on_operands() || matches!(op.definition.id, "ifelse" | "sequence")) {
// Random draws, assignments and control flow can interleave with the caller's inputs.
return None;
}
origins.push(lanes);
}
let selected = origins.get(program.output)?;
let width = super::returned_product::float_width(program.output_type());
if width > 0 && selected[..width].iter().all(Option::is_some) {
slots.clear();
seen.fill(false);
for &slot in selected[..width].iter().flatten() {
if !std::mem::replace(seen.get_mut(slot)?, true) {
slots.push(slot);
}
}
}
Some(Self {
registers: slots.iter().map(|slot| registers.get(*slot).copied()).collect::<Option<_>>()?,
slots,
channels: selected.map(|slot| slot.and_then(|i| registers.get(i)).copied()),
})
}
}
/// Wire presence is local to a call. Free variables can be defined by an executed Set in a caller.
pub(super) struct CallBindings<'a> {
pub call: &'a FunctionCall,
+37 -10
View File
@@ -9,6 +9,8 @@ pub struct Program {
pub(crate) instructions: Vec<Instruction>,
pub(crate) output: usize,
pub(crate) seed: u32,
pub(super) pattern_draws: std::collections::BTreeMap<usize, super::branch_random::PatternDraws>,
pub(super) pattern_components: std::collections::BTreeMap<usize, super::vector::PatternComponent>,
}
const MAX_EVALUATION_STEPS: usize = 100_000;
@@ -195,6 +197,15 @@ impl Program {
}
state.steps.push(Store(index));
if context.scope == super::FunctionScope::FxMap
&& let Some(source) = self.pattern_components.get(&index)
{
match source {
super::vector::PatternComponent::Scalar(source) => state.steps.push(Enter(*source)),
super::vector::PatternComponent::Zero => state.values.push(Value::Float(0.0)),
}
continue;
}
match instruction.definition.id {
"set" if matches!(&instruction.value, Some(Value::Text(name)) if bindings.is_some_and(|scope| scope.call.defaults.contains_key(name))) =>
@@ -219,6 +230,11 @@ impl Program {
state.steps.push(Apply { instruction: index, base: state.values.len() });
let inputs = match &instruction.pixel_product_sum {
Some(product) if context.scope == super::FunctionScope::PixelProcessor => product.inputs.as_slice(),
_ if context.scope == super::FunctionScope::FxMap => instruction
.call
.as_ref()
.and_then(|call| call.pattern_arguments.as_ref())
.map_or(instruction.inputs.as_slice(), |arguments| arguments.registers.as_slice()),
_ => instruction.inputs.as_slice(),
};
state.steps.extend(inputs.iter().rev().map(|&index| Enter(index)));
@@ -247,7 +263,10 @@ impl Program {
storage.argument_factors = factors;
storage.variables.clone_from(&state.variables);
storage.variables.extend(call.defaults.clone());
for (name, value) in call.inputs.iter().zip(arguments) {
let pattern = call.pattern_arguments.as_ref().filter(|_| context.scope == super::FunctionScope::FxMap);
for (i, value) in arguments.iter().enumerate() {
let slot = pattern.map_or(Some(i), |params| params.slots.get(i).copied()).ok_or("missing function argument slot")?;
let name = call.inputs.get(slot).ok_or("missing function argument name")?;
storage.variables.insert(name.clone(), value.clone());
}
@@ -295,17 +314,25 @@ impl Program {
}
Branch(index) => {
let condition = state.values.pop().ok_or("missing branch condition")?;
let slot = if value_type::boolean(&condition)? { 1 } else { 2 };
state.steps.push(Enter(self.input(index, slot)?));
if context.scope == super::FunctionScope::PixelProcessor {
for &shared in self.instruction(index)?.control_registers.iter().rev() {
if state.registers.get(shared).is_some_and(Option::is_none) {
state.steps.push(Discard);
state.steps.push(Enter(shared));
}
let take_true = value_type::boolean(&condition)?;
let selected = self.input(index, if take_true { 1 } else { 2 })?;
let (shared, after_selected) = match context.scope {
super::FunctionScope::PixelProcessor => (self.instruction(index)?.control_registers.as_slice(), false),
super::FunctionScope::FxMap => self.pattern_draws.get(&index).map_or((&[][..], false), |draws| (draws.skipped(take_true), take_true)),
_ => (&[][..], false),
};
if !after_selected {
state.steps.push(Enter(selected));
}
for &index in shared.iter().rev() {
if state.registers.get(index).is_some_and(Option::is_none) {
state.steps.push(Discard);
state.steps.push(Enter(index));
}
}
if after_selected {
state.steps.push(Enter(selected));
}
}
Discard => {
state.values.pop().ok_or("missing shared branch draw")?;
+16 -5
View File
@@ -79,7 +79,7 @@ pub(super) fn evaluate_sum(terms: &Sum, arguments: &[Value], subtract: bool, sta
pub(super) type Lanes = [Option<Source>; 4];
type Origins = [Option<usize>; 4];
fn float_width(code: u32) -> usize {
pub(super) fn float_width(code: u32) -> usize {
match code {
256 => 1,
512 => 2,
@@ -90,10 +90,15 @@ fn float_width(code: u32) -> usize {
}
/// Packing and component selection forward a lane without observing its rounded value.
fn forwarded(op: &Instruction, instructions: &[Instruction], origins: &[Origins]) -> Option<Origins> {
pub(super) fn forwarded<T: Copy>(op: &Instruction, instructions: &[Instruction], origins: &[[Option<T>; 4]], padding: Option<T>) -> Option<[Option<T>; 4]> {
let mut out = [None; 4];
match (op.definition.id, op.inputs.as_slice()) {
("vector2" | "vector3" | "vector4", [_, _]) => {
("vector2" | "vector3" | "vector4", [left, right]) => {
let left_width = float_width(instructions.get(*left)?.type_code);
let right_width = float_width(instructions.get(*right)?.type_code);
if left_width == 0 || right_width == 0 || left_width + right_width != float_width(op.type_code) {
return None;
}
let lanes = op.inputs.iter().flat_map(|i| {
let width = instructions.get(*i).map_or(0, |v| float_width(v.type_code));
origins.get(*i).into_iter().flatten().take(width)
@@ -104,9 +109,15 @@ fn forwarded(op: &Instruction, instructions: &[Instruction], origins: &[Origins]
}
("swizzle1" | "swizzle2" | "swizzle3" | "swizzle4", [input]) => {
let indices = value_type::integers(op.value.as_ref()?).ok()?;
let width = float_width(instructions.get(*input)?.type_code);
if width == 0 {
return None;
}
let input = origins.get(*input)?;
for (dst, i) in out.iter_mut().take(float_width(op.type_code)).zip(indices) {
*dst = usize::try_from(i).ok().and_then(|i| input.get(i)).copied().flatten();
let i = usize::try_from(i).ok()?;
let source = *input.get(i)?;
*dst = if i < width { source } else { padding };
}
}
_ => return None,
@@ -127,7 +138,7 @@ pub(super) fn identify(program: &mut Program, mut returned: BTreeMap<usize, Lane
let mut products: Vec<(Source, usize)> = Vec::new();
let mut sums = Vec::new();
for (index, op) in program.instructions.iter().enumerate() {
if let Some(lanes) = forwarded(op, &program.instructions, &origins) {
if let Some(lanes) = forwarded(op, &program.instructions, &origins, None) {
origins.push(lanes);
continue;
}
+128
View File
@@ -1149,6 +1149,134 @@ fn pixel_branch_shared_draws_precede_the_selected_arm() {
assert_eq!(result, Value::Float4([0x3e87_bb00, 0x3f59_6540, 0x3f22_ab7c, 0x3f22_ab7c].map(f32::from_bits)));
}
#[test]
fn pattern_branch_draws_shared_with_a_later_channel_keep_their_order() {
let mut graph = FunctionGraph::default();
let condition = graph.add("get_bool", &[], Some(Value::Text("take".into())));
let one = graph.add_constant(Value::Float(1.0));
let [a, b, c, alternate, green] = std::array::from_fn(|_| graph.add("rand", &[one], None));
let mixed = graph.add("lerp", &[a, b, c], None);
let red = graph.add("ifelse", &[condition, mixed, alternate], None);
let rg = graph.add("vector2", &[red, green], None);
graph.output = Some(graph.add("vector3", &[rg, a], None));
for (take, seed, bits) in [
(true, 31, [0x3f51_c505, 0x3e9a_198c, 0x3f34_57e6]),
(false, 31, [0x3f5a_33c2, 0x3f46_fab2, 0x3f34_57e6]),
(true, 12071, [0x3f12_cb20, 0x3f48_974e, 0x3ee5_cd7c]),
(false, 68047, [0x3c33_7c80, 0x3f58_d3c2, 0x3d46_3760]),
] {
let values = BTreeMap::from([("take".into(), Value::Bool(take))]);
let context = EvaluationContext {
scope: super::FunctionScope::FxMap,
position: [0.5; 2],
size: [16.0; 2],
images: &[],
image_formats: &[],
tile: true,
variables: &values,
};
let program = compile(&graph, seed).unwrap();
assert_eq!(program.evaluate(&context, &mut EvaluationState::default()).unwrap(), Value::Float3(bits.map(f32::from_bits)));
}
}
#[test]
fn shared_pattern_draws_follow_the_order_of_the_conditional_arms() {
let mut graph = FunctionGraph::default();
let take = graph.add("get_bool", &[], Some(Value::Text("take".into())));
let one = graph.add_constant(Value::Float(1.0));
let [a, b, c, d, next] = std::array::from_fn(|_| graph.add("rand", &[one], None));
let yes = graph.add("lerp", &[a, b, c], None);
let no = graph.add("lerp", &[c, b, d], None);
let branch = graph.add("ifelse", &[take, yes, no], None);
let rg = graph.add("vector2", &[branch, next], None);
graph.output = Some(graph.add("vector3", &[rg, d], None));
let program = compile(&graph, 31).unwrap();
for (take, bits) in [(true, [0x3f51_c505, 0x3f5b_5a9e, 0x3e9a_198c]), (false, [0x3f3c_c6a3, 0x3e9a_198c, 0x3f46_fab2])] {
let variables = BTreeMap::from([("take".into(), Value::Bool(take))]);
let context = EvaluationContext {
scope: super::FunctionScope::FxMap,
position: [0.5; 2],
size: [16.0; 2],
images: &[],
image_formats: &[],
tile: true,
variables: &variables,
};
assert_eq!(program.evaluate(&context, &mut EvaluationState::default()).unwrap(), Value::Float3(bits.map(f32::from_bits)));
}
}
#[test]
fn selecting_a_packed_pattern_channel_consumes_only_its_draw() {
let mut graph = FunctionGraph::default();
let one = graph.add_constant(Value::Float(1.0));
let [a, b, c, d] = std::array::from_fn(|_| graph.add("rand", &[one], None));
let left = graph.add("vector2", &[a, b], None);
let right = graph.add("vector2", &[c, d], None);
let packed = graph.add("vector4", &[left, right], None);
let [last, third, first] = [3, 2, 0].map(|i| graph.add("swizzle1", &[packed], Some(Value::Int(i))));
let pair = graph.add("vector2", &[last, third], None);
graph.output = Some(graph.add("vector3", &[pair, first], None));
let variables = BTreeMap::new();
let context = EvaluationContext {
scope: super::FunctionScope::FxMap,
position: [0.5; 2],
size: [16.0; 2],
images: &[],
image_formats: &[],
tile: true,
variables: &variables,
};
let value = compile(&graph, 31).unwrap().evaluate(&context, &mut EvaluationState::default()).unwrap();
assert_eq!(value, Value::Float3([0x3f34_57e6, 0x3f5a_33c2, 0x3f46_fab2].map(f32::from_bits)));
}
#[test]
fn pattern_call_arguments_follow_the_returned_channels() {
let names = ["red", "green", "blue"];
let mut body = FunctionGraph::default();
let [red, green, blue] = names.map(|n| body.add("get_float1", &[], Some(Value::Text(n.into()))));
let bg = body.add("vector2", &[blue, green], None);
body.output = Some(body.add("vector3", &[bg, red], None));
let mut graph = FunctionGraph::default();
let one = graph.add_constant(Value::Float(1.0));
let args: [_; 3] = std::array::from_fn(|_| graph.add("rand", &[one], None));
let result = graph.add("instance", &args, None);
let call = graph.nodes.last_mut().unwrap();
call.type_code = 1024;
call.instance = Some(materialcraft_core::GraphInstance {
package: String::new(),
graph: "reverse_channels".into(),
label: String::new(),
inputs: names.map(|n| materialcraft_core::GraphPort { identifier: n.into(), type_code: 256 }).into(),
outputs: Vec::new(),
defaults: names.map(|n| (n.into(), Value::Float(0.0))).into(),
});
call.source = Some(Ok(std::sync::Arc::new(body)));
let variables = BTreeMap::new();
let context = EvaluationContext {
scope: super::FunctionScope::FxMap,
position: [0.5; 2],
size: [16.0; 2],
images: &[],
image_formats: &[],
tile: true,
variables: &variables,
};
graph.output = Some(result);
let run = |graph: &FunctionGraph| compile(graph, 31).unwrap().evaluate(&context, &mut EvaluationState::default()).unwrap();
let draws = [0x3f34_57e6, 0x3f5a_33c2, 0x3f46_fab2].map(f32::from_bits);
assert_eq!(run(&graph), Value::Float3(draws));
let selected = graph.add("swizzle1", &[result], Some(Value::Int(0)));
let next = graph.add("rand", &[one], None);
let pair = graph.add("vector2", &[selected, next], None);
graph.output = Some(graph.add("vector3", &[pair, args[2]], None));
assert_eq!(run(&graph), Value::Float3([draws[0], draws[1], draws[0]]));
}
#[test]
fn packed_random_ranges_preserve_the_unrounded_draw_in_each_lane() {
let mut graph = FunctionGraph::default();
+41
View File
@@ -1,6 +1,47 @@
use super::value_type::{dimensions, floats, integer_value, integers, intermediate_float_value as float_value};
use materialcraft_core::Value;
#[derive(Clone, Copy)]
pub(super) enum PatternComponent {
Scalar(usize),
Zero,
}
/// A pattern that selects one packed channel visits only the expressions that supply it.
pub(super) fn identify_pattern_components(program: &mut super::Program) {
let instructions = &program.instructions;
if !instructions.iter().any(|op| op.definition.id == "swizzle1")
|| !instructions.iter().any(|op| matches!(op.definition.id, "rand" | "set") || op.call.is_some())
{
return;
}
// A call can read state written elsewhere in this graph, without an argument wire.
// Keep the original evaluation order when those dependencies are unknown.
if instructions.iter().any(|op| op.definition.id == "set")
&& instructions.iter().any(|op| op.call.as_ref().is_some_and(|call| call.pattern_arguments.is_none()))
{
return;
}
let mut sources = Vec::with_capacity(instructions.len());
for (index, op) in instructions.iter().enumerate() {
let mut lanes = [None; 4];
if let Some(forwarded) = super::returned_product::forwarded(op, instructions, &sources, Some(PatternComponent::Zero)) {
lanes = forwarded;
if op.definition.id == "swizzle1"
&& let Some(source) = lanes[0]
{
program.pattern_components.insert(index, source);
}
} else if let Some(arguments) = op.call.as_ref().and_then(|call| call.pattern_arguments.as_ref()) {
lanes = arguments.channels.map(|register| register.map(PatternComponent::Scalar));
}
if op.type_code == 256 && lanes[0].is_none() {
lanes[0] = Some(PatternComponent::Scalar(index));
}
sources.push(lanes);
}
}
pub(crate) fn evaluate(op: &str, args: &[Value], setting: Option<&Value>) -> Result<Value, String> {
let first = args.first().ok_or("missing vector input")?;
let count = op.chars().last().and_then(|c| c.to_digit(10)).unwrap_or(1) as usize;
+31
View File
@@ -1736,6 +1736,37 @@ The whole-root comparison uses the [78 settings per HQ blur](#directional-blur-w
Both whole roots retain differing pixels. The two impulse regressions failed on the previous renderer and passed after the change. The 416 release node and evaluation tests, formatting, strict Clippy, layering and all ten WebAssembly checks passed using the committed resource set.
### Shared random draws in pattern branches and returned color channels
In a pattern tint, a random draw used by a conditional arm and a later channel keeps its place in the order of the arms. The condition runs first. With the false arm selected, the tested draws shared with the skipped true arm run before the false result. With the true arm selected, its result runs before draws needed from the false arm. A scalar selection from a packed vector visits the supplying component. In a straight-line called function with scalar inputs, the first uses of those inputs determine their evaluation order. Repeated reads reuse the same draw.
Use one full-coverage rectangle, additive color on a black background, with unit alpha and independent unit draws A, B, C, D and E. Set the RGB result to (if take then lerp(A,B,C) else D, E, A). At seed 31 the F32 words for true are `3f51c505 3e9a198c 3f3457e6` and for false are `3f5a33c2 3f46fab2 3f3457e6`. Replace the false arm with lerp(C,B,D) and return D in blue. True gives `3f51c505 3f5b5a9e 3e9a198c` and false gives `3f3cc6a3 3e9a198c 3f46fab2`. Test all four combinations of two Boolean inputs when nesting the arms. Use 16², 32 × 16 and 16 × 32 with seeds 31, 12071 and 68047 respectively, and range inputs .25, .625 and .9375.
For the channel controls, form RGBA from two pairs of unit draws. Select individual channels, reverse or repeat them, try a padded channel and reuse an original draw in a later output. For the call controls expose red, green and blue as scalar arguments, each wired to a distinct draw. Return (blue,green,red), (blue,blue,red) or selected arithmetic on them. Compare the whole result and a single selected result assembled with the caller's next draw. Repeat with three return channels derived from one packed RGBA argument. The four F32 settings use 16² seed 31 with the switch off and on, 32 × 16 seed 12071 with it off, and 16 × 32 seed 68047 with it on. The saved controls preserve the original connections and argument order.
| F32 comparison | Renders | Earlier exact pixels / total · maximum | Current exact pixels / total · maximum |
|---|---:|---:|---:|
| Shared draws and branch controls | 84 | 29,184/32,256 · 0.852352262 | 30,720/32,256 · 0.852352262 |
| Two conditional arms, nested branches and assignments | 216 | 58,880/92,160 · 0.836026192 | 89,600/92,160 · 0.836026192 |
| Channel selection through nested vectors | 136 | 4,608/52,224 · 0.836026192 | 49,152/52,224 · 0.836026192 |
| Three scalar function inputs in different return orders | 104 | 6,144/39,936 · 0.836026192 | 23,040/39,936 · 0.836026192 |
| Returned channels with sums, products and interpolation | 96 | 1,536/36,864 · 0.836026192 | 29,184/36,864 · 0.873463869 |
| One vector argument with reordered and repeated channels | 180 | 0/69,120 · 0.836026192 | 11,520/69,120 · 0.836026192 |
| Channel selection with a local assignment or sequence | 80 | 1,536/30,720 · 3.07092288e+16 | 13,824/30,720 · 3.07092288e+16 |
The first six groups went from **100,352 to 233,216 exact pixels out of 322,560** across 816 renders. Another 338 renders matched every pixel. Each render retained or increased its exact count. The largest error in the arithmetic-call group increased from .836026192 to .873463869. Some last-group graphs read a variable without an executed write. That row reports exact captured pixels and the largest finite component difference. The captures include non-finite values, so the value of an undefined read remains unresolved.
| Saved graph family | Packages | Reopened renders | Cross-application exact pixels / total · maximum |
|---|---:|---:|---:|
| Packed channel selections | 10 | 40 | 15,360/15,360 · 0 |
| Scalar call arguments | 7 | 28 | 6,144/10,752 · 0.798588514 |
| Shared conditional draws | 8 | 32 | 11,520/12,288 · 0.271984816 |
| Packed call arguments | 10 | 40 | 1,536/15,360 · 0.836026192 |
Each application reproduced every pixel of its own original renders after reopening these files. Calls with vector inputs, arithmetic-dependent selections, assignments and nested conditionals retain measured differences.
Across all 958 previously recorded settings for roots 373–376, 441, 488 and 491, the exact counts and maxima are unchanged. Grayscale Tile Generator remains exact in **757,504/757,504** pixels across 221 settings. Color Tile Generator matches **621,344/765,184** across 331. Its per-channel tint draws still differ. A call with unknown dependencies can read a variable assigned in its caller, so those graphs retain their existing evaluation order. Four node regressions reproduced the earlier errors. All 416 release tests in the node and evaluator crates passed, along with formatting, strict workspace Clippy, dependency layers and WebAssembly.
## 2026-11-20 root comparisons
### Hue, saturation, lightness and Replace Color
+4 -4
View File
@@ -496,10 +496,10 @@ Creased matches 10,947,840/10,947,840 pixels across 100 distinct settings throug
| [pattern_splatter_circular.sbs/splatter_circular](../assets/sbs/pattern_splatter_circular.sbs) | 7 | No | [In progress · 130,917/132,096 exact pixels in 9 renders](parity-fixes.md#other-roots-using-uniform-arc-tangents) · [Stamp-width recheck](parity-fixes.md#pixel-reciprocals-for-stamp-edge-widths) |
| [pattern_splatter_circular.sbs/splatter_circular_color](../assets/sbs/pattern_splatter_circular.sbs) | 7 | No | [In progress · 130,678/132,096 exact pixels in 9 renders](parity-fixes.md#other-roots-using-uniform-arc-tangents) · [Stamp-width recheck](parity-fixes.md#pixel-reciprocals-for-stamp-edge-widths) |
| [pattern_stripes.sbs/stripes](../assets/sbs/pattern_stripes.sbs) | 0 | No | [Parity · 762,880/762,880 pixels across 83 distinct settings](parity-fixes.md#pixel-ratio-in-rectangular-directional-filters) |
| [pattern_tile_generator.sbs/tile_generator](../assets/sbs/pattern_tile_generator.sbs) | 7 | No | [Parity · 757,504/757,504 pixels across 221 distinct settings](parity-fixes.md#selected-blend-inputs-and-odd-sized-float-backgrounds-in-tile-generators) · [Previous bitmap-slot comparisons](parity-fixes.md#pattern-draw-order-for-fixed-and-runtime-image-slots) · [Previous storage and whole-root comparisons](parity-fixes.md#parameter-controlled-sizes-and-half-precision-pattern-backgrounds) · [Earlier whole-root comparison](parity-fixes.md#beveled-square-gradient-and-wave-stamps) · [Stamp-width recheck](parity-fixes.md#pixel-reciprocals-for-stamp-edge-widths) |
| [pattern_tile_generator.sbs/tile_generator_color](../assets/sbs/pattern_tile_generator.sbs) | 7 | No | [In progress · 621,344/765,184 pixels across 331 distinct settings](parity-fixes.md#selected-blend-inputs-and-odd-sized-float-backgrounds-in-tile-generators) · [Previous bitmap-slot comparisons](parity-fixes.md#pattern-draw-order-for-fixed-and-runtime-image-slots) · [Previous storage and whole-root comparisons](parity-fixes.md#parameter-controlled-sizes-and-half-precision-pattern-backgrounds) · [Earlier whole-root comparison](parity-fixes.md#tile-weave-splatter-and-fiber-stage-comparisons) · [Stamp-width recheck](parity-fixes.md#pixel-reciprocals-for-stamp-edge-widths) |
| [pattern_tile_random.sbs/tile_random](../assets/sbs/pattern_tile_random.sbs) | 2 | No | [In progress · 291,084/316,672 pixels across 52 distinct settings](parity-fixes.md#selected-blend-inputs-and-odd-sized-float-backgrounds-in-tile-generators) · [Previous bitmap-slot comparisons](parity-fixes.md#pattern-draw-order-for-fixed-and-runtime-image-slots) · [Previous storage and whole-root comparisons](parity-fixes.md#parameter-controlled-sizes-and-half-precision-pattern-backgrounds) · [Earlier whole-root comparison](parity-fixes.md#tile-random-image-and-soft-patterns) · [Stamp-width recheck](parity-fixes.md#pixel-reciprocals-for-stamp-edge-widths) |
| [pattern_tile_random.sbs/tile_random_color](../assets/sbs/pattern_tile_random.sbs) | 2 | No | [In progress · 498,989/619,776 pixels across 126 distinct settings](parity-fixes.md#selected-blend-inputs-and-odd-sized-float-backgrounds-in-tile-generators) · [Previous bitmap-slot comparisons](parity-fixes.md#pattern-draw-order-for-fixed-and-runtime-image-slots) · [Previous storage and whole-root comparisons](parity-fixes.md#parameter-controlled-sizes-and-half-precision-pattern-backgrounds) · [Earlier whole-root comparison](parity-fixes.md#signed-bitmap-blend-precision) · [Stamp-width recheck](parity-fixes.md#pixel-reciprocals-for-stamp-edge-widths) |
| [pattern_tile_generator.sbs/tile_generator](../assets/sbs/pattern_tile_generator.sbs) | 7 | No | [Parity · 757,504/757,504 pixels across 221 distinct settings](parity-fixes.md#selected-blend-inputs-and-odd-sized-float-backgrounds-in-tile-generators) · [Previous bitmap-slot comparisons](parity-fixes.md#pattern-draw-order-for-fixed-and-runtime-image-slots) · [Previous storage and whole-root comparisons](parity-fixes.md#parameter-controlled-sizes-and-half-precision-pattern-backgrounds) · [Earlier whole-root comparison](parity-fixes.md#beveled-square-gradient-and-wave-stamps) · [Stamp-width recheck](parity-fixes.md#pixel-reciprocals-for-stamp-edge-widths) · [conditional draws and returned channels](parity-fixes.md#shared-random-draws-in-pattern-branches-and-returned-color-channels) |
| [pattern_tile_generator.sbs/tile_generator_color](../assets/sbs/pattern_tile_generator.sbs) | 7 | No | [In progress · 621,344/765,184 pixels across 331 distinct settings](parity-fixes.md#selected-blend-inputs-and-odd-sized-float-backgrounds-in-tile-generators) · [Previous bitmap-slot comparisons](parity-fixes.md#pattern-draw-order-for-fixed-and-runtime-image-slots) · [Previous storage and whole-root comparisons](parity-fixes.md#parameter-controlled-sizes-and-half-precision-pattern-backgrounds) · [Earlier whole-root comparison](parity-fixes.md#tile-weave-splatter-and-fiber-stage-comparisons) · [Stamp-width recheck](parity-fixes.md#pixel-reciprocals-for-stamp-edge-widths) · [conditional draws and returned channels](parity-fixes.md#shared-random-draws-in-pattern-branches-and-returned-color-channels) |
| [pattern_tile_random.sbs/tile_random](../assets/sbs/pattern_tile_random.sbs) | 2 | No | [In progress · 291,084/316,672 pixels across 52 distinct settings](parity-fixes.md#selected-blend-inputs-and-odd-sized-float-backgrounds-in-tile-generators) · [Previous bitmap-slot comparisons](parity-fixes.md#pattern-draw-order-for-fixed-and-runtime-image-slots) · [Previous storage and whole-root comparisons](parity-fixes.md#parameter-controlled-sizes-and-half-precision-pattern-backgrounds) · [Earlier whole-root comparison](parity-fixes.md#tile-random-image-and-soft-patterns) · [Stamp-width recheck](parity-fixes.md#pixel-reciprocals-for-stamp-edge-widths) · [conditional draws and returned channels](parity-fixes.md#shared-random-draws-in-pattern-branches-and-returned-color-channels) |
| [pattern_tile_random.sbs/tile_random_color](../assets/sbs/pattern_tile_random.sbs) | 2 | No | [In progress · 498,989/619,776 pixels across 126 distinct settings](parity-fixes.md#selected-blend-inputs-and-odd-sized-float-backgrounds-in-tile-generators) · [Previous bitmap-slot comparisons](parity-fixes.md#pattern-draw-order-for-fixed-and-runtime-image-slots) · [Previous storage and whole-root comparisons](parity-fixes.md#parameter-controlled-sizes-and-half-precision-pattern-backgrounds) · [Earlier whole-root comparison](parity-fixes.md#signed-bitmap-blend-precision) · [Stamp-width recheck](parity-fixes.md#pixel-reciprocals-for-stamp-edge-widths) · [conditional draws and returned channels](parity-fixes.md#shared-random-draws-in-pattern-branches-and-returned-color-channels) |
| [pattern_tile_random_2.sbs/functions/debug_find_cell](../assets/sbs/pattern_tile_random_2.sbs) | 0 | Yes | [Parity: 4 cases](parity-fixes.md#verified-cases) |
| [pattern_tile_random_2.sbs/tile_random_2](../assets/sbs/pattern_tile_random_2.sbs) | 5 | No | [Parity · 285,184 exact pixels in 38 renders](parity-fixes.md#shared-lookups-and-environment-shadow-pass) |
| [pattern_tile_sampler.sbs/arrow](../assets/sbs/pattern_tile_sampler.sbs) | 0 | Yes | [Parity · seven 512×512 runs, four formats](parity-fixes.md#transform-edges-and-floating-point-filtering) |