Evaluate shared pixel draws before the selected conditional arm

This commit is contained in:
chasse20 committed 2026-11-19 04:07:23 -05:00
1 parent 1bb56ebcba
commit f0e6c9fdb4
9 files changed
+133 -9

No files matched your search

@@ -0,0 +1,53 @@
use super::Program;
/// Schedule draws shared by a pixel 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))
{
return;
}
// A range depending on assignment or image evaluation must stay at its original read.
let mut simple = 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 mut paths = vec![0_u8; instructions.len()];
let mut stack = Vec::new();
let mut draws = Vec::new();
let mut plans = Vec::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);
draws.clear();
// The first visit through the true arm sets the order when both arms use multiple draws.
for (root, path) in [(yes, 1), (no, 2), (program.output, 4)] {
if path == 4 && draws.is_empty() {
break;
}
stack.push(root);
while let Some(index) = stack.pop() {
if index == branch || paths[index] & path != 0 {
continue;
}
let node = &instructions[index];
if paths[index] == 0 && path != 4 && simple[index] && node.definition.id == "rand" && !node.inputs.is_empty() {
draws.push(index);
}
paths[index] |= path;
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));
}
}
for (index, shared) in plans {
program.instructions[index].control_registers = shared;
}
}
+4 -3
View File
@@ -113,7 +113,7 @@ fn compile_nested(graph: &FunctionGraph, seed: u32, depth: usize, remaining: &mu
literal_divisor: false,
pixel_product_sum: None,
pixel_interval: None,
repeated: Vec::new(),
control_registers: Vec::new(),
call: None,
});
instructions.len() - 1
@@ -169,7 +169,7 @@ fn compile_nested(graph: &FunctionGraph, seed: u32, depth: usize, remaining: &mu
literal_divisor: false,
pixel_product_sum: None,
pixel_interval: None,
repeated: Vec::new(),
control_registers: Vec::new(),
call,
};
let mut inputs = inputs;
@@ -192,7 +192,7 @@ fn compile_nested(graph: &FunctionGraph, seed: u32, depth: usize, remaining: &mu
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;
instruction.control_registers = repeated;
}
}
}
@@ -243,6 +243,7 @@ fn mark_literals(program: &mut Program, mut arguments: BTreeSet<&str>) -> super:
}
}
super::product_sum::identify(&mut program.instructions);
super::branch_random::identify(program);
super::returned_product::identify(program, returned)
}
@@ -5,6 +5,7 @@ pub(crate) enum EvaluationStep {
Store(usize),
Apply { instruction: usize, base: usize },
Branch(usize),
Discard,
Sequence(usize),
LoopStart(usize),
LoopCondition { instruction: usize, iteration: u32, last: Value },
+2 -2
View File
@@ -14,8 +14,8 @@ pub(crate) struct Instruction {
pub(super) pixel_product_sum: Option<super::product_sum::ProductSum>,
/// Registers for max(lower, min(value, upper)) with literal scalar bounds.
pub(super) pixel_interval: Option<Box<PixelInterval>>,
/// For a loop: the instructions of its condition and body, evaluated again on every iteration
pub repeated: Vec<usize>,
/// A loop refreshes its condition and body. A pixel branch first samples its shared draws.
pub control_registers: Vec<usize>,
pub call: Option<super::function_call::FunctionCall>,
}
+1
View File
@@ -10,6 +10,7 @@ const DEFAULT_LOOP_LIMIT: i32 = 32;
mod arithmetic;
mod binary_exponential;
mod branch_random;
mod catalog;
mod compile;
mod evaluation_context;
+12 -1
View File
@@ -208,6 +208,17 @@ impl Program {
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 &draw in self.instruction(index)?.control_registers.iter().rev() {
if state.registers.get(draw).is_some_and(Option::is_none) {
state.steps.push(Discard);
state.steps.push(Enter(draw));
}
}
}
}
Discard => {
state.values.pop().ok_or("missing shared branch draw")?;
}
Sequence(index) => {
state.values.pop().ok_or("missing sequence result")?;
@@ -254,7 +265,7 @@ impl Program {
fn clear_loop_results(&self, index: usize, state: &mut EvaluationState) -> Result<(), String> {
// Outgoing wires share a node value across reads, branches and effects
// Only the active loop condition and body run again
for repeated in &self.instruction(index)?.repeated {
for repeated in &self.instruction(index)?.control_registers {
if let Some(register) = state.registers.get_mut(*repeated) {
*register = None;
}
+26
View File
@@ -793,6 +793,32 @@ fn measured_pixel_reciprocals_preserve_runtime_rounding() {
}
}
#[test]
fn pixel_branch_shared_draws_precede_the_selected_arm() {
let mut graph = FunctionGraph::default();
let test = graph.add("get_bool", &[], Some(Value::Text("first".into())));
let one = graph.add_constant(Value::Float(1.0));
let [a, b, next] = std::array::from_fn(|_| graph.add("rand", &[one], None));
let left = graph.add("vector2", &[a, a], None);
let right = graph.add("vector2", &[b, a], None);
let branch = graph.add("ifelse", &[test, left, right], None);
let tail = graph.add("vector2", &[next, next], None);
graph.output = Some(graph.add("vector4", &[branch, tail], None));
let values = BTreeMap::from([("first".into(), Value::Bool(false))]);
let context = EvaluationContext {
scope: super::FunctionScope::PixelProcessor,
position: [24.5 / 32.0, 0.5 / 32.0],
size: [32.0; 2],
images: &[],
image_formats: &[],
tile: true,
variables: &values,
};
let program = compile(&graph, 137).unwrap();
let result = program.evaluate(&context, &mut EvaluationState::default()).unwrap();
assert_eq!(result, Value::Float4([0x3e87_bb00, 0x3f59_6540, 0x3f22_ab7c, 0x3f22_ab7c].map(f32::from_bits)));
}
#[test]
fn packed_random_ranges_preserve_the_unrounded_draw_in_each_lane() {
let mut graph = FunctionGraph::default();
+32 -1
View File
@@ -1042,6 +1042,37 @@ Every row includes the four original defaults, seed and parameter renders, the 6
The trapezoid pair each has two remaining differences across the archived and new comparisons. The [four-format inventory](#four-format-inventory-comparison) lists the original changed settings and port names.
### Conditional pixel draws and White Noise v2
White Noise v2 matches **183,808/183,808 pixels in 76 renders**, with maximum error zero. The original 19 renders improved from 104,036/143,872 to 143,872/143,872. Across the full matrix, all 122,880 U8, 8,192 U16, 11,264 F16 and 41,472 F32 values match. This generator has no input image.
| Root controls | Renders | Exact pixels / compared | Maximum error |
|---|---:|---:|---:|
| Defaults and previous disorder, speed and format variations | 19 | 143,872/143,872 | 0 |
| Uniform and Gaussian at three seeds | 33 | 8,448/8,448 | 0 |
| Uniform, Gaussian and Triangle at four additional seeds | 24 | 31,488/31,488 | 0 |
Use the [original settings](#per-pixel-random-initialization) for the first row. For the second row use 16² F32 at seeds 0, 1 and 137. At each seed use uniform with disorder and speed zero. For Gaussian use (disorder,speed) of (0,0), (.25,0), and speed 1 with disorder 0, .25, .5, .75, 1, 1.25, 1.5 and 2. For each distribution in the third row, render 16² F32 at seed 509 with (−.25,.6875), 32² in all four formats at seed 317 with (.125,.6875), 64² F32 at seed 709 with (.875,1.5), and 32² F16 and F32 at seed 1021 with (1.5,.25).
Ten intermediate scalar outputs each matched 1,024/1,024 F32 pixels when selected individually. They covered the unit draw shared by both generators, radial and angular inputs, angle conversion, cosine, logarithm, squared radius, unnormalized and normalized Gaussian values, and the Gaussian result. Use 16² at seed zero with (disorder,speed) of (0,0) and (.25,1), seed one with (.5,1) and seed 137 with (.75,1). In the complete graph with disorder and speed zero, the Gaussian branch uses the third unit draw for its radius and the first for its angle. Evaluating the Gaussian expression on its own changes that order.
For an original conditional pixel expression, evaluate its condition first. A scalar draw shared between both arms or also used outside the conditional consumes its sample before draws private to the selected arm. Multiple shared draws follow first use in the true arm, then the false arm. Nested conditionals and draws supplying another draw's range use the same cached samples.
| Original condition and return value | Exact pixels before | Exact RGBA pixels after / compared |
|---|---:|---:|
| (T ? A : B, C, A, B) | 2 | 9,472/9,472 |
| (T ? A : B−A, C, A, B) | 2 | 9,472/9,472 |
| (T ? (A,A) : (B,A), C, C) | 4,736 | 9,472/9,472 |
| (T ? A : A−B, C, A, B) | 4,738 | 9,472/9,472 |
| (S ? (A,A) : (D,A), C, C) | 4,736 | 9,472/9,472 |
| (T ? A : (S ? B−A : B+A), C, A, B) | 2 | 9,472/9,472 |
| (T ? A : (S ? B−A : D), C, A, B) | 2 | 9,472/9,472 |
| (T ? A−B : B−A, C, A, B) | 4,736 | 9,472/9,472 |
| (T ? B−A : A−B, C, A, B) | 4,736 | 9,472/9,472 |
| (T ? E : B−E, C, A, B) | 3 | 9,472/9,472 |
A, B, C and D are separate unit-range scalar draw nodes. E is a draw with range A. Repeated letters reuse the same node. T is normalized texel-center x < .5 and S is B < .5. Render each expression at 16² F32/seed 0, 32² F32/17, 32² in four formats/137 and 64² F32/613. All 94,720 pixels match every channel, with maximum error zero. For the third row the F32 words at (24,0) of the 32²/137 render are 3e87bb00, 3f596540, 3f22ab7c and 3f22ab7c. The [standalone vector-typed draw](#scaled-random-draws-and-offsets) remains open.
### Packed random draws in flood-fill color
| Root | Renders | Exact pixels before | Exact RGBA pixels after / compared | Maximum error after |
@@ -1134,7 +1165,7 @@ For Worley, Dissolve, the four diffusion passes, six flood-fill outputs and both
| Flood Fill 2 color/grayscale filtering | 1 | 0 | 1 |
| White Noise v2 distribution, disorder, speed | 1,.375,.625 | 0,.8125,1.25 | 1,.1875,.375 |
For Worley also set size (.75,1.25,1.5), Minkowski number .6875, border width .1875 and roundness .3125. Set optional diffusion controls where exposed. For Flood Fill 2 color use HSL adjustment (.125,−.1875,.25) and random range (.375,.625,.1875). For its grayscale equivalent use luminance adjustment −.1875 and random range .625. The random flood-fill outputs and fast white noise have no additional exposed numeric changes in these controls. Each residual flood-fill difference is at most one U16 level or .0000152587891 in F32. Uniform noise selects the measured per-texel stream. The Gaussian distribution in White Noise v2 still diverges.
For Worley also set size (.75,1.25,1.5), Minkowski number .6875, border width .1875 and roundness .3125. Set optional diffusion controls where exposed. For Flood Fill 2 color use HSL adjustment (.125,−.1875,.25) and random range (.375,.625,.1875). For its grayscale equivalent use luminance adjustment −.1875 and random range .625. The random flood-fill outputs and fast white noise have no additional exposed numeric changes in these controls. Each residual flood-fill difference is at most one U16 level or .0000152587891 in F32. Uniform noise selects the measured per-texel stream. The later [conditional draw comparison](#conditional-pixel-draws-and-white-noise-v2) resolves the Gaussian differences in White Noise v2.
### Float bitmap reduction and half output
+2 -2
View File
@@ -35,7 +35,7 @@ A graph may accept input pins and still be a root under the dependency criterion
Statuses: **Not checked**, **In progress**, **Parity** (exact pixels or typed values for the linked measured cases), or **Too hard** (reason recorded). Function calls do not count as regular graph dependencies.
The first pass covered all **546 roots**, with **166 Parity** and **380 Too hard**. The current inventory has **341 Parity**, **56 In progress** and **149 Too hard**. The November 17 and 18 comparisons include raw counts, output formats and remaining differences. [November 17 measurements](parity-fixes.md#2026-11-17-root-comparisons) · [November 18 measurements](parity-fixes.md#2026-11-18-root-comparisons)
The first pass covered all **546 roots**, with **166 Parity** and **380 Too hard**. The current inventory has **342 Parity**, **55 In progress** and **149 Too hard**. The November 17 and 18 comparisons include raw counts, output formats and remaining differences. [November 17 measurements](parity-fixes.md#2026-11-17-root-comparisons) · [November 18 measurements](parity-fixes.md#2026-11-18-root-comparisons)
[Grayscale sampler measurements](parity-fixes.md#grayscale-sampling-of-color-inputs) · [Value sampling across 240 typed comparisons](parity-fixes.md#value-processor-texture-filtering)
@@ -594,6 +594,6 @@ The first pass covered all **546 roots**, with **166 Parity** and **380 Too hard
| [weave_4.sbs/weave_4](../assets/sbs/weave_4.sbs) | 0 | Yes | [In progress · 170,018/171,264 exact pixels in 18 renders](parity-fixes.md#plane-light-splatter-symmetry-and-waveform-comparisons) |
| [white_noise.sbs/white_noise](../assets/sbs/white_noise.sbs) | 0 | Yes | [Parity: 3 cases](parity-fixes.md#verified-cases) |
| [white_noise.sbs/white_noise_fast](../assets/sbs/white_noise.sbs) | 0 | Yes | [Parity · 18 renders, 127,488 exact pixels](parity-fixes.md#per-pixel-random-initialization) |
| [white_noise_v2.sbs/white_noise_v2](../assets/sbs/white_noise_v2.sbs) | 0 | No | [In progress · 19 renders, 104,036/143,872 exact pixels](parity-fixes.md#per-pixel-random-initialization) |
| [white_noise_v2.sbs/white_noise_v2](../assets/sbs/white_noise_v2.sbs) | 0 | No | [Parity · 76 renders, 183,808 exact pixels](parity-fixes.md#conditional-pixel-draws-and-white-noise-v2) |
| [wood_fibers_1.sbs/wood_fibers_1](../assets/sbs/wood_fibers_1.sbs) | 0 | Yes | [Too hard: remaining pixel differences](parity-fixes.md#remaining-differences) |
| [wood_fibers_2.sbs/wood_fibers_2](../assets/sbs/wood_fibers_2.sbs) | 0 | Yes | [Too hard: remaining pixel differences](parity-fixes.md#remaining-differences) |