mirror of
https://github.com/storytold/materialcraft.git
synced 2026-11-28 17:19:17 +01:00
Preserve observable random draws in function sequences
This commit is contained in:
1 parent
ab4edf7154
commit
4fd6f29fdc
9 files changed
+239
-14
No files matched your search
@@ -234,7 +234,16 @@ 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, pattern_draws: BTreeMap::new(), pattern_components: BTreeMap::new(), loop_sums: BTreeMap::new() })
|
||||
let sequence_prefixes = super::sequence_prefix::identify(&instructions, output);
|
||||
Ok(Program {
|
||||
instructions,
|
||||
output,
|
||||
seed,
|
||||
sequence_prefixes,
|
||||
pattern_draws: BTreeMap::new(),
|
||||
pattern_components: BTreeMap::new(),
|
||||
loop_sums: BTreeMap::new(),
|
||||
})
|
||||
}
|
||||
|
||||
/// A write can replace an argument before its next read.
|
||||
|
||||
@@ -7,6 +7,7 @@ use std::collections::BTreeMap;
|
||||
pub struct EvaluationState {
|
||||
pub(crate) steps: Vec<EvaluationStep>,
|
||||
pub(crate) values: Vec<Value>,
|
||||
pub(super) visited_prefixes: Vec<bool>,
|
||||
pub(crate) registers: Vec<Option<Value>>,
|
||||
pub(crate) variables: BTreeMap<String, Value>,
|
||||
pub(crate) assignments: BTreeMap<String, Value>,
|
||||
|
||||
@@ -6,7 +6,8 @@ pub(crate) enum EvaluationStep {
|
||||
Enter(usize),
|
||||
Store(usize),
|
||||
Apply { instruction: usize, base: usize },
|
||||
Branch(usize),
|
||||
Branch { instruction: usize, prefix: bool },
|
||||
Prefix(usize),
|
||||
Discard,
|
||||
Sequence(usize),
|
||||
LoopStart(usize),
|
||||
|
||||
@@ -37,6 +37,7 @@ mod program;
|
||||
mod reciprocal;
|
||||
mod resolve_instances;
|
||||
mod returned_product;
|
||||
mod sequence_prefix;
|
||||
mod square_root;
|
||||
mod system_variable;
|
||||
mod trigonometry;
|
||||
|
||||
@@ -11,6 +11,7 @@ pub struct Program {
|
||||
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>,
|
||||
pub(super) sequence_prefixes: Vec<super::sequence_prefix::Visit>,
|
||||
pub(super) loop_sums: std::collections::BTreeMap<usize, super::loop_sum::LoopSum>,
|
||||
}
|
||||
|
||||
@@ -154,12 +155,11 @@ impl Program {
|
||||
|
||||
fn random_stream(&self, context: &EvaluationContext<'_>) -> FunctionRandom {
|
||||
let seed = context.variables.get("$randomseed").and_then(Value::as_i32).map_or(self.seed, |seed| seed as u32);
|
||||
if context.scope == super::FunctionScope::PixelProcessor {
|
||||
FunctionRandom::pixel(seed, context.position)
|
||||
} else if context.scope == super::FunctionScope::FxMap {
|
||||
FunctionRandom::image(seed)
|
||||
} else {
|
||||
FunctionRandom::uniform(seed)
|
||||
match context.scope {
|
||||
super::FunctionScope::PixelProcessor => FunctionRandom::pixel(seed, context.position),
|
||||
super::FunctionScope::ValueProcessor => FunctionRandom::pixel(seed, [0.0; 2]),
|
||||
super::FunctionScope::FxMap => FunctionRandom::image(seed),
|
||||
super::FunctionScope::Node => FunctionRandom::uniform(seed),
|
||||
}
|
||||
}
|
||||
|
||||
@@ -185,6 +185,8 @@ impl Program {
|
||||
state.assignments.clear();
|
||||
state.registers.clear();
|
||||
state.registers.resize(self.instructions.len(), None);
|
||||
state.visited_prefixes.clear();
|
||||
state.visited_prefixes.resize(self.sequence_prefixes.len(), false);
|
||||
state.steps.push(Enter(self.output));
|
||||
|
||||
while let Some(step) = state.steps.pop() {
|
||||
@@ -216,9 +218,13 @@ impl Program {
|
||||
state.values.push(kind.default_value());
|
||||
}
|
||||
"ifelse" => {
|
||||
state.steps.push(Branch(index));
|
||||
state.steps.push(Branch { instruction: index, prefix: false });
|
||||
state.steps.push(Enter(self.input(index, 0)?));
|
||||
}
|
||||
"sequence" if !self.sequence_prefixes.is_empty() => {
|
||||
state.steps.push(Enter(self.input(index, 1)?));
|
||||
state.steps.push(Prefix(self.input(index, 0)?));
|
||||
}
|
||||
"sequence" => {
|
||||
state.steps.push(Sequence(index));
|
||||
state.steps.push(Enter(self.input(index, 0)?));
|
||||
@@ -341,7 +347,27 @@ impl Program {
|
||||
let register = state.registers.get_mut(index).ok_or("invalid function register")?;
|
||||
*register = Some(value.clone());
|
||||
}
|
||||
Branch(index) => {
|
||||
Prefix(index) => {
|
||||
use super::sequence_prefix::Visit;
|
||||
if state.registers.get(index).is_some_and(Option::is_some)
|
||||
|| state.visited_prefixes.get_mut(index).is_some_and(|seen| std::mem::replace(seen, true))
|
||||
{
|
||||
continue;
|
||||
}
|
||||
match self.sequence_prefixes.get(index).copied().unwrap_or(Visit::Value) {
|
||||
Visit::Skip => {}
|
||||
Visit::Value => {
|
||||
state.steps.push(Discard);
|
||||
state.steps.push(Enter(index));
|
||||
}
|
||||
Visit::Inputs => state.steps.extend(self.instruction(index)?.inputs.iter().rev().copied().map(Prefix)),
|
||||
Visit::Branch => {
|
||||
state.steps.push(Branch { instruction: index, prefix: true });
|
||||
state.steps.push(Enter(self.input(index, 0)?));
|
||||
}
|
||||
}
|
||||
}
|
||||
Branch { instruction: index, prefix } => {
|
||||
let condition = state.values.pop().ok_or("missing branch condition")?;
|
||||
let take_true = value_type::boolean(&condition)?;
|
||||
let selected = self.input(index, if take_true { 1 } else { 2 })?;
|
||||
@@ -350,21 +376,24 @@ impl Program {
|
||||
super::FunctionScope::FxMap => self.pattern_draws.get(&index).map_or((&[][..], false), |draws| (draws.skipped(take_true), take_true)),
|
||||
_ => (&[][..], false),
|
||||
};
|
||||
let selected = || if prefix { Prefix(selected) } else { Enter(selected) };
|
||||
if !after_selected {
|
||||
state.steps.push(Enter(selected));
|
||||
state.steps.push(selected());
|
||||
}
|
||||
for &index in shared.iter().rev() {
|
||||
if state.registers.get(index).is_some_and(Option::is_none) {
|
||||
if prefix {
|
||||
state.steps.push(Prefix(index));
|
||||
} else 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));
|
||||
state.steps.push(selected());
|
||||
}
|
||||
}
|
||||
Discard => {
|
||||
state.values.pop().ok_or("missing shared branch draw")?;
|
||||
state.values.pop().ok_or("missing discarded function value")?;
|
||||
}
|
||||
Sequence(index) => {
|
||||
state.values.pop().ok_or("missing sequence result")?;
|
||||
|
||||
@@ -0,0 +1,92 @@
|
||||
use super::instruction::Instruction;
|
||||
|
||||
/// How to evaluate a Sequence's first input when its return value is discarded.
|
||||
#[derive(Clone, Copy)]
|
||||
pub(super) enum Visit {
|
||||
Skip,
|
||||
Value,
|
||||
Inputs,
|
||||
Branch,
|
||||
}
|
||||
|
||||
pub(super) fn identify(instructions: &[Instruction], output: usize) -> Vec<Visit> {
|
||||
if !instructions.iter().any(|op| op.definition.id == "sequence") || !instructions.iter().any(|op| op.definition.id == "rand") {
|
||||
return Vec::new();
|
||||
}
|
||||
// A loop can read the same register at several points with different assignments and draws.
|
||||
// Keep its existing evaluation and invalidation until each iteration's reads are accounted for.
|
||||
if instructions.iter().any(|op| op.definition.id == "while") {
|
||||
return Vec::new();
|
||||
}
|
||||
|
||||
let mut readers = vec![Vec::new(); instructions.len()];
|
||||
let mut needed = vec![false; instructions.len()];
|
||||
let mut effects = vec![false; instructions.len()];
|
||||
enum Mark {
|
||||
Value(usize),
|
||||
Effect(usize),
|
||||
}
|
||||
use Mark::*;
|
||||
let mut pending = vec![Value(output)];
|
||||
for (index, op) in instructions.iter().enumerate() {
|
||||
for &input in &op.inputs {
|
||||
readers[input].push(index);
|
||||
}
|
||||
// A call may read or export a variable without a wire to the caller.
|
||||
if op.definition.id == "set" || op.call.is_some() {
|
||||
pending.push(Value(index));
|
||||
pending.push(Effect(index));
|
||||
}
|
||||
}
|
||||
while let Some(mark) = pending.pop() {
|
||||
match mark {
|
||||
Value(i) if !needed[i] => {
|
||||
needed[i] = true;
|
||||
let op = &instructions[i];
|
||||
if op.definition.id == "rand" || op.definition.id.starts_with("get_") {
|
||||
pending.push(Effect(i));
|
||||
}
|
||||
if let ("sequence", &[_, last]) = (op.definition.id, op.inputs.as_slice()) {
|
||||
pending.push(Value(last));
|
||||
} else {
|
||||
pending.extend(op.inputs.iter().copied().map(Value));
|
||||
}
|
||||
}
|
||||
Effect(i) if !effects[i] => {
|
||||
effects[i] = true;
|
||||
for &reader in &readers[i] {
|
||||
pending.push(Effect(reader));
|
||||
let op = &instructions[reader];
|
||||
if let ("ifelse", &[condition, yes, no]) = (op.definition.id, op.inputs.as_slice())
|
||||
&& (i == yes || i == no)
|
||||
{
|
||||
pending.push(Value(condition));
|
||||
}
|
||||
}
|
||||
}
|
||||
_ => {}
|
||||
}
|
||||
}
|
||||
|
||||
instructions
|
||||
.iter()
|
||||
.enumerate()
|
||||
.map(|(i, op)| {
|
||||
if !effects[i] {
|
||||
Visit::Skip
|
||||
} else if needed[i] {
|
||||
Visit::Value
|
||||
} else if let ("ifelse", &[_, yes, no]) = (op.definition.id, op.inputs.as_slice())
|
||||
&& (effects[yes] || effects[no])
|
||||
{
|
||||
Visit::Branch
|
||||
} else {
|
||||
Visit::Inputs
|
||||
}
|
||||
})
|
||||
.collect()
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
#[path = "sequence_prefix.test.rs"]
|
||||
mod tests;
|
||||
@@ -0,0 +1,75 @@
|
||||
use crate::function::{EvaluationContext, EvaluationState, FunctionScope, compile};
|
||||
use materialcraft_core::{FunctionGraph, Value};
|
||||
use std::collections::BTreeMap;
|
||||
|
||||
#[test]
|
||||
fn value_processor_random_draws_use_the_scalar_evaluation_position() {
|
||||
let mut graph = FunctionGraph::default();
|
||||
let one = graph.add_constant(Value::Float(1.0));
|
||||
let first = graph.add("rand", &[one], None);
|
||||
let second = graph.add("rand", &[one], None);
|
||||
graph.output = Some(graph.add("vector2", &[first, second], None));
|
||||
let variables = BTreeMap::new();
|
||||
for size in [[16.0; 2], [128.0, 32.0]] {
|
||||
let context = EvaluationContext {
|
||||
scope: FunctionScope::ValueProcessor,
|
||||
position: [0.0; 2],
|
||||
size,
|
||||
images: &[],
|
||||
image_formats: &[],
|
||||
tile: true,
|
||||
variables: &variables,
|
||||
};
|
||||
for (seed, pair) in [(3, [280133, 3213511]), (20, [233407, 5314947])] {
|
||||
let expected = Value::Float2(pair.map(|level| level as f32 / 8388608.0));
|
||||
assert_eq!(compile(&graph, seed).unwrap().evaluate(&context, &mut EvaluationState::default()).unwrap(), expected, "seed {seed}");
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn discarded_sequence_values_preserve_assignments_and_shared_random_draws() {
|
||||
let mut graph = FunctionGraph::default();
|
||||
let one = graph.add_constant(Value::Float(1.0));
|
||||
let zero = graph.add_constant(Value::Float(0.0));
|
||||
let choice = graph.add("get_bool", &[], Some(Value::Text("choice".into())));
|
||||
let first = graph.add("rand", &[one], None);
|
||||
let unused = graph.add("rand", &[one], None);
|
||||
let last = graph.add("rand", &[one], None);
|
||||
let write = graph.add("set", &[first], Some(Value::Text("tone".into())));
|
||||
let read = graph.add("get_float1", &[], Some(Value::Text("tone".into())));
|
||||
let observe = graph.add("mul", &[read, zero], None);
|
||||
let following = graph.add("add", &[observe, last], None);
|
||||
let sum = graph.add("add", &[write, unused], None);
|
||||
let branch = graph.add("ifelse", &[choice, write, unused], None);
|
||||
let shared_zero = graph.add("mul", &[first, zero], None);
|
||||
let shared = graph.add("add", &[last, shared_zero], None);
|
||||
let pure = graph.add("sequence", &[unused, last], None);
|
||||
let assigned = graph.add("sequence", &[sum, following], None);
|
||||
let conditional = graph.add("sequence", &[branch, following], None);
|
||||
let reused = graph.add("sequence", &[first, shared], None);
|
||||
let vertices = [pure, assigned, conditional, reused];
|
||||
let control = graph.add("vector2", &[first, last], None);
|
||||
|
||||
for scope in [FunctionScope::Node, FunctionScope::FxMap, FunctionScope::PixelProcessor, FunctionScope::ValueProcessor] {
|
||||
for choice in [true, false] {
|
||||
let variables = BTreeMap::from([("choice".into(), Value::Bool(choice)), ("tone".into(), Value::Float(0.25))]);
|
||||
let context = EvaluationContext { scope, position: [0.0; 2], size: [16.0; 2], images: &[], image_formats: &[], tile: true, variables: &variables };
|
||||
for seed in [0, 17] {
|
||||
// An ordinary vector observes the first two draws from this particular scope.
|
||||
graph.output = Some(control);
|
||||
let reference = compile(&graph, seed).unwrap().evaluate(&context, &mut EvaluationState::default()).unwrap();
|
||||
let Value::Float2([a, b]) = reference else { panic!("two draws") };
|
||||
for (root, value) in vertices.into_iter().zip([a, b, if choice { b } else { a }, b]) {
|
||||
graph.output = Some(root);
|
||||
let mut state = EvaluationState::default();
|
||||
let result = compile(&graph, seed).unwrap().evaluate(&context, &mut state).unwrap();
|
||||
assert_eq!(result, Value::Float(value), "scope {scope:?}, root {root}, choice {choice}");
|
||||
if root == assigned || (root == conditional && choice) {
|
||||
assert_eq!(state.assignments().get("tone"), Some(&Value::Float(a)));
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -73,6 +73,21 @@ For a separate check at 256² and seed 372421, compile the same original wrapper
|
||||
|
||||
Maximum U16 error is zero throughout the three-setting desktop column. The desktop original and reopen also agree in 139,264/139,264 pixels per root. At the previously disputed 256² seed, MaterialCraft and the live desktop agree in 65,536/65,536 pixels per root. The same six, two and four discrepancies recur between the two reference rendering paths on all four one-worker runs per root. The eight-worker runs give more than one output for the same settings. The inventory retains the existing cross-worker differences. [Earlier seed and worker measurements](#computed-graph-seeds-on-load-evaluation-and-save)
|
||||
|
||||
### Sequence evaluation and scalar random values
|
||||
|
||||
Build an original function around two distinct Random(1) nodes. In Sequence, use the first draw directly, multiply it by zero in the returned expression, assign it to a variable, or use it in both the discarded input and the returned expression. Include a write with a second unused draw beside it, a conditional write and both signs of its control. Render the eleven variants at 16², with control +1 and −1 and graph seeds 0 and 17. Repeat after an ordinary MaterialCraft save and desktop reopen.
|
||||
|
||||
| Function context | Original exact samples | Reopened exact samples | Maximum absolute error |
|
||||
|---|---:|---:|---:|
|
||||
| FX-Map quadrant opacity, F32 pixels | 11,264/11,264 | 11,264/11,264 | 0 |
|
||||
| Pixel Processor, F32 pixels | 11,264/11,264 | 11,264/11,264 | 0 |
|
||||
| Uniform Color parameter, RGBA F32 pixels | 11,264/11,264 | 11,264/11,264 | 0 |
|
||||
| Value Processor, typed floats | 44/44 | 44/44 | 0 |
|
||||
|
||||
A discarded draw leaves the next random value available. A write, a draw used elsewhere or a draw multiplied by zero in the returned expression can still advance the stream. Scalar Value Processor starts its stream at the zero-coordinate pixel hash. A second test uses the first draw, a zero-weighted draw and a shared draw, with twelve caller seeds from 0 through 372421, a relative seed offset of +3 and two sizes (16² and 128 × 32). All 72/72 typed results match on the original and the reopened graphs, maximum 0. Each original desktop result above also matches the reopened desktop result.
|
||||
|
||||
Two further controls put a three-iteration loop on the discarded side of Sequence. Its body either discards Random(1) or assigns the draw. The reference returns the first draw after either loop. These cases still differ in MaterialCraft. Across both loops and four settings, FX-Map matches 0/2,048, maximum 0.386968136, Pixel Processor matches 0/2,048, maximum 0.961201191 and Value Processor matches 0/8, maximum 0.662862062. Seven further controls outside those two loops, including an empty loop, produce 7,168/7,168, maximum 0 in FX-Map, 7,168/7,168, maximum 0 in Pixel Processor and 24/28, maximum 0.45432511 in Value Processor. The four scalar differences occur when a false conditional arm shares a draw with another expression. Random expressions passed as graph arguments are also under separate investigation.
|
||||
|
||||
### Pixel size on graph instance outputs
|
||||
|
||||
At 128² and seed 0, the Gaussian source in Bricks 01 returns a 64² U16 field with pixel size (2,2). The input to Blur matches the reference in all 4,096 pixels. The filter intensity is 1.61. The instance previously returned the caller's unit pixel size to downstream filters. Blur then copied the field and matched just 53/4,096, maximum U16 error 21,379.
|
||||
|
||||
@@ -43,6 +43,8 @@ Ordinary SBS saves preserve graph seed inheritance across 22 nested graphs. The
|
||||
|
||||
The Bricks 01 material provides a separate 2D display check. The corrected preview matches all 258 tested encoded RGB channels. The headless 2D PNG also matches every pixel of a 16² uniform-color control in both display modes. With the shared pattern and instance pixel-size fixes, default Base Color matches 4,096/4,096 raw pixels at 64² and 16,379/16,384 at 128², maximum byte errors 0 and 1. At 256² the raw outputs match 65,508/65,536, maximum 1. [Child output pixel size and whole-material measurements](parity-fixes.md#pixel-size-on-graph-instance-outputs) [Color swatches](parity-fixes.md#stored-graph-color-in-the-2d-view) · [Whole-material measurements](parity-fixes.md#selected-channels-in-pattern-expressions)
|
||||
|
||||
Original Sequence controls and their ordinary saves each match 11,264/11,264 pixels in each of three image contexts and 44/44 typed Value Processor results. A further 72/72 typed values match across seeds and dimensions. Discarded loops and shared draws in scalar conditionals have remaining differences. [Procedure, exact counts and maximum errors](parity-fixes.md#sequence-evaluation-and-scalar-random-values)
|
||||
|
||||
The grayscale Tile Generator again has measured parity. Its 55 earlier settings match 284,416/284,416 pixels. Both luminance seeds and all 24 new procedural source, grid and format settings match, including ordinary saves. [Reproduction and zero-error counts](parity-fixes.md#selected-channels-in-pattern-expressions)
|
||||
|
||||
BNW Spots 1, Clouds 1 and Clouds 2 each match 9,216/9,216 direct U16 pixels and a further 9,216/9,216 across four actual output formats. Reopened graphs have the same counts and maximum error 0. At the disputed 256² seed, all three now match 65,536/65,536 in the live desktop. The standalone renderer differs from that same desktop by six, two and four pixels. All captured intermediate ports also match the desktop across three settings per root. In a seven-level additive control, 120 group pairs match 1,966,080/1,966,080 desktop pixels. [Per-root counts and renderer order](parity-fixes.md#intermediate-noise-outputs-and-the-order-of-overlapping-pattern-draws) [Direct desktop and standalone comparisons](parity-fixes.md#live-desktop-and-standalone-rendering-of-three-noise-roots) [Nested sizes, seeds and output formats](parity-fixes.md#computed-caller-sizes-on-bnw-spots-1-and-clouds-1-and-2)
|
||||
|
||||
Reference in new issue
Block a user