diff --git a/crates/nodes/src/pattern/evaluation.rs b/crates/nodes/src/pattern/evaluation.rs index bd6f1b23..30c3dc42 100644 --- a/crates/nodes/src/pattern/evaluation.rs +++ b/crates/nodes/src/pattern/evaluation.rs @@ -7,13 +7,22 @@ use crate::function::{EvaluationContext, EvaluationState, compile_with_literal_i use crate::random::FunctionRandom; use crate::{CookContext, CookResult}; -// A 512-by-512 quadtree takes 349,525 visits. Each discarded stamp can fund one extra visit, -// up to this same limit again. Retained stamps, raster copies and pixel work stay bounded. +// A 512-by-512 quadtree takes 349,525 visits. This limit bounds retained stamps and +// provides a second allowance for discarded draws. A terminal sibling group has at most +// three additional discards, and needs two ordinary visits (its parent and first discard). +// Thus at most five times this limit can execute, including the discarded stamps. const MAX_VISITS: usize = 1_048_576; // Overlapping squares establish the order of the sixteen grandchildren in a regular seven-level tree. const SEVEN_LEVEL_RUN_ORDER: [usize; 16] = [12, 13, 8, 9, 14, 0, 1, 15, 2, 11, 6, 7, 10, 3, 4, 5]; +#[derive(Clone, Copy, PartialEq, Eq)] +enum QuadrantChildren { + None, + AllTerminal, + Other, +} + #[derive(Default)] struct SevenLevelRuns { seen_root: bool, @@ -83,11 +92,17 @@ pub(crate) fn cook(context: &CookContext) -> CookResult { /// Cook a pattern with the supplied base-level-only flags in image port order. pub fn cook_with_base_level_inputs(context: &CookContext, base_level_only: &[bool]) -> CookResult { + cook_with_visit_limit(context, base_level_only, MAX_VISITS) +} + +pub(super) fn cook_with_visit_limit(context: &CookContext, base_level_only: &[bool], visit_limit: usize) -> CookResult { let Some(Value::PatternGraph(graph)) = context.params.get("pattern") else { return Err("missing pattern graph".into()); }; let opacity_depth = graph.validated_depth()?; + let terminal_nodes: BTreeSet<_> = + graph.nodes.iter().filter(|node| node.kind == PatternNodeKind::Quadrant && node.children.iter().all(Option::is_none)).map(|node| node.id).collect(); let mut nodes = BTreeMap::new(); let mut functions = BTreeMap::new(); let mut fixed_switches = BTreeSet::new(); @@ -109,7 +124,14 @@ pub fn cook_with_base_level_inputs(context: &CookContext, base_level_only: &[boo if fixed { fixed_switches.insert(node.id); } - nodes.insert(node.id, (node, literal_geometry)); + let quadrant_children = if terminal_nodes.contains(&node.id) { + QuadrantChildren::None + } else if node.kind == PatternNodeKind::Quadrant && node.children.iter().flatten().all(|id| terminal_nodes.contains(id)) { + QuadrantChildren::AllTerminal + } else { + QuadrantChildren::Other + }; + nodes.insert(node.id, (node, literal_geometry, quadrant_children)); } let image_slots: Vec<_> = @@ -128,8 +150,9 @@ pub fn cook_with_base_level_inputs(context: &CookContext, base_level_only: &[boo let mut variables = PatternVariables::new(context.vars.graph_values()); let mut max_depth = 0; let mut state = EvaluationState::default(); - let mut remaining = MAX_VISITS; - let mut discard_allowance = MAX_VISITS; + let mut terminal_siblings: Option<(usize, bool)> = None; + let mut remaining = visit_limit; + let mut discard_allowance = visit_limit; let grayscale = !context.b("color_mode"); let mut repeated_roots = None; let mut repeated_six_level: Option = None; @@ -153,6 +176,9 @@ pub fn cook_with_base_level_inputs(context: &CookContext, base_level_only: &[boo *slot = Some(stamps.len()); } } + if terminal_siblings.is_some_and(|(start, _)| pending.len() < start) { + terminal_siblings = None; + } variables.resume(pending.len()); max_depth = max_depth.max(visit.depth); if empty_switches.contains(&visit.node) { @@ -165,7 +191,7 @@ pub fn cook_with_base_level_inputs(context: &CookContext, base_level_only: &[boo let next = PatternVisit { number: visit.number + 1, seed: crate::random::iteration_child(visit.seed), ..visit.clone() }; pending.push((next, repeats_left - 1)); } - let &(node, literal_geometry) = nodes.get(&visit.node).ok_or("missing pattern node")?; + let &(node, literal_geometry, quadrant_children) = nodes.get(&visit.node).ok_or("missing pattern node")?; if seven_level_runs.as_mut().is_some_and(|runs| !runs.visit(node, visit.depth, stamps.len())) { seven_level_runs = None; } @@ -335,7 +361,12 @@ pub fn cook_with_base_level_inputs(context: &CookContext, base_level_only: &[boo terminal_quadrants = None; } if missed { - if discard_allowance > 0 { + // These siblings have no children. Each has already evaluated its own + // properties and failed the sample-grid test in the original draw order. + let later_discard = terminal_siblings.as_mut().is_some_and(|(_, seen)| std::mem::replace(seen, true)); + if later_discard { + remaining += 1; + } else if discard_allowance > 0 { discard_allowance -= 1; remaining += 1; } @@ -344,17 +375,22 @@ pub fn cook_with_base_level_inputs(context: &CookContext, base_level_only: &[boo } } - let mut child_random = visit.seed; - for (child, center) in node.children.iter().zip(visit.quadrant_centers()) { - let child_seed = crate::random::quadrant_child(&mut child_random, visit.depth.saturating_add(1)); - if let Some(child) = child { - let mut child_visit = visit.clone(); - child_visit.node = *child; - child_visit.depth = visit.depth.saturating_add(1); - child_visit.extent *= 0.5; - child_visit.seed = child_seed; - child_visit.center = center; - children.push(child_visit); + if quadrant_children == QuadrantChildren::AllTerminal { + terminal_siblings = Some((pending.len(), false)); + } + if quadrant_children != QuadrantChildren::None { + let mut child_random = visit.seed; + for (child, center) in node.children.iter().zip(visit.quadrant_centers()) { + let child_seed = crate::random::quadrant_child(&mut child_random, visit.depth.saturating_add(1)); + if let Some(child) = child { + let mut child_visit = visit.clone(); + child_visit.node = *child; + child_visit.depth = visit.depth.saturating_add(1); + child_visit.extent *= 0.5; + child_visit.seed = child_seed; + child_visit.center = center; + children.push(child_visit); + } } } } diff --git a/crates/nodes/src/pattern/tests.rs b/crates/nodes/src/pattern/tests.rs index 350020e7..fcf884e9 100644 --- a/crates/nodes/src/pattern/tests.rs +++ b/crates/nodes/src/pattern/tests.rs @@ -1756,6 +1756,61 @@ fn center_at_roughness(graph: PatternGraph, roughness: f32) -> f32 { (definition.cook)(&context).unwrap()[0].get_gray(8, 8, false) } +#[test] +fn terminal_quadrants_charge_the_first_discard_of_each_sibling_group() { + let mut graph = PatternGraph::with_root(PatternNodeKind::Iterate); + let marker = graph.add(PatternNodeKind::Quadrant).unwrap(); + let branch = graph.add(PatternNodeKind::Quadrant).unwrap(); + let leaf = graph.add(PatternNodeKind::Quadrant).unwrap(); + graph.nodes[0].children = vec![Some(marker), Some(branch)]; + graph.nodes[0].parameters.insert("numberadded".into(), Value::Int(48)); + square(&mut graph, 1); + graph.nodes[1].parameters.insert("opacity".into(), Value::Float(0.375)); + graph.nodes[2].children.fill(Some(leaf)); + square(&mut graph, 3); + graph.nodes[3].parameters.insert("patternsize".into(), Value::Float2([1.0 / 64.0; 2])); + + let render = |graph: &PatternGraph| { + let params = resolve_params( + find("fx_map").unwrap(), + &BTreeMap::from([ + ("pattern".into(), Value::PatternGraph(Box::new(graph.clone()))), + ("roughness".into(), Value::Float(0.0)), + ("color_mode".into(), Value::Bool(false)), + ]), + ); + let context = CookContext { + w: 4, + h: 4, + seed: 19, + tile: false, + inputs: &[], + input_formats: &[], + format: materialcraft_core::OutputFormat::F32, + params: ¶ms, + resource: &|_| None, + vars: &BTreeMap::new(), + }; + super::evaluation::cook_with_visit_limit(&context, &[], 64) + }; + let image = render(&graph).unwrap().remove(0); + for y in 0..4 { + for x in 0..4 { + assert_eq!(image.get_gray(x, y, false), 0.375); + } + } + + // Visible siblings each consume a visit, even if their pixels coincide. + let mut visible = graph.clone(); + visible.nodes[3].parameters.insert("patternsize".into(), Value::Float2([2.0; 2])); + assert!(render(&visible).unwrap_err().contains("execution budget")); + + // With only one child per branch, extending the iteration still exhausts the ordinary allowances. + graph.nodes[2].children[1..].fill(None); + graph.nodes[0].parameters.insert("numberadded".into(), Value::Int(80)); + assert!(render(&graph).unwrap_err().contains("execution budget")); +} + #[test] fn empty_switches_at_later_depths_still_affect_roughness() { let mut graph = PatternGraph::with_root(PatternNodeKind::Quadrant); diff --git a/docs/parity-fixes.md b/docs/parity-fixes.md index ba618685..8ad26d13 100644 --- a/docs/parity-fixes.md +++ b/docs/parity-fixes.md @@ -80,6 +80,23 @@ For the pixel controls use the [signed procedural F32 fields](#packed-products-i The range covers physically disconnected ports. A separate pair with two wires still differs when its leading wire reads an undeclared variable and the other carries a nonzero value. Scanning the reachable expressions in all 546 root graph bodies found zero one-wire vector constructors with the leading port disconnected. Called function bodies were outside that scan. The root count stays at 479. The regression failed on the preceding compiler. All 401 node release tests, formatting, strict workspace Clippy, dependency layers and WebAssembly passed. +### Bounded work for terminal Quadrant siblings + +The shared FX-Map evaluator now charges a group of at most four terminal Quadrant siblings for its first discarded stamp. Each child evaluates its own properties, applies its variable writes and reaches its own sample-grid test before it can share that charge. Each visible stamp still costs a visit. An iteration or a branch with descendants cannot obtain extra visits by repeating a single discarded stamp. Terminal nodes also skip the unused child-center and child-seed calculations. + +The ordinary limit covers 1,048,576 visits plus the same number of individual discards. Every group with an extra discard needs a distinct parent and first discarded child among those ordinary visits. At most three further discards can share their charge, bounding evaluated visits at 5,242,880. Stored stamps, stack occupancy, raster copies and pixel work retain their own bounds. A regression with a 64-visit allowance checks a visible marker and 48 four-child groups that miss all 4×4 samples. Changing those children to visible squares reaches the limit. Repeating a branch with a single missed child 80 times also reaches it. The previous cook failed on the marker case. + +Repeat the [four whole BNW Spots 3 v2 readouts](#four-cloud-noise-generators-and-repeated-saved-file-comparisons) with the normal release cook and compare the final F32 buffers with the desktop. The default 16×32 at seed zero gives 478/512 exact. At scale 1, the 32×16 seed 162065 and 64×32 seed 162283 give 449/512 and 1,860/2,048. Maximum channel errors are 1.1920929e−7, 1.1920929e−7 and 1.49011612e−7 respectively. The 32² scale-two seed 162174 previously exhausted the visit allowance. + +| Scale-two F32 comparison, 4,025,030 visits | Original, exact / total · maximum | MaterialCraft save reopened, exact / total · maximum | +|---|---:|---:| +| Explicit one-worker reference, both repeat runs | 1,024/1,024 · 0 | 1,024/1,024 · 0 | +| Desktop | 894/1,024 · 1.1920929e−7 | 894/1,024 · 1.1920929e−7 | +| Explicit eight-worker reference, first run | 878/1,024 · 1.78813934e−7 | 878/1,024 · 1.78813934e−7 | +| Explicit eight-worker reference, second run | 874/1,024 · 1.1920929e−7 | 874/1,024 · 1.1920929e−7 | + +Use the [same graph settings, reference captures and worker repeats](#dense-quadrant-traversal-and-reference-worker-counts). In the 32 original four-format Quadrant controls, 28 renders complete with 7,159/7,168 desktop pixels exact. Six of eight reopens complete with 766/768 exact. Maximum error in either set is 5.96046448e−8. The regular depth-eleven tree still reaches the limit at all four tested formats and both saved formats. The whole spot root remains in progress. All 402 node release tests, formatting, strict workspace Clippy, dependency layers and WebAssembly passed. + ### Dense Quadrant traversal and reference worker counts Construct a grayscale FX-Map with a .0625 background, zero roughness, overall opacity 1, both regions (0,1,0,1), center culling enabled and wrapping disabled. Start at (.5,.5). At each subdivision link all four children to the next empty Quadrant. At the last level draw additive squares of size (1.75,2.25), rotation zero and luminosity `rand(.0625) + .0625 * $pos.x`. In the returning-offset version move the root branch by (1.25,0) and the final stamp by (−1.25,0). In the narrow version change only the size to (.375,1.25). Use seeds 441151 + 31j, with j from zero to three in the column order below. @@ -105,7 +122,7 @@ For the whole BNW Spots 3 v2 graph use 32² F32, seed 162174, scale 2, disorder | Returning offset, 10 | 128/128 · 0 | 126/128 · 5.96046448e-08 | 105/128 · 5.96046448e-08 | 113/128 · 5.96046448e-08 | 102/128 · 5.96046448e-08 | | Whole Spots 3 v2 | 1,024/1,024 · 0 | 894/1,024 · 1.1920929e-07 | 878/1,024 · 1.78813934e-07 | 874/1,024 · 1.1920929e-07 | 887/1,024 · 2.38418579e-07 | -The dense spot traversal takes 4,025,030 visits. At depth eight in its final generator, testing a square with radius four times the current subdivision width around the incoming center plus the inherited frame offset would reject 6,442 of 753,536 subtrees that contained a retained stamp. The returning-offset controls also draw after their ancestors leave the image. The production visit limit and the multi-worker differences remain open. [Original spot traversal and whole-root measurements](#whole-root-precision-and-saved-comparisons-for-the-three-neighboring-spot-graphs) +The dense spot traversal takes 4,025,030 visits. At depth eight in its final generator, testing a square with radius four times the current subdivision width around the incoming center plus the inherited frame offset would reject 6,442 of 753,536 subtrees that contained a retained stamp. The returning-offset controls also draw after their ancestors leave the image. The [bounded terminal-sibling cook](#bounded-work-for-terminal-quadrant-siblings) subsequently completed this spot setting in production. The depth-eleven limit and the multi-worker differences remain open. [Original spot traversal and whole-root measurements](#whole-root-precision-and-saved-comparisons-for-the-three-neighboring-spot-graphs) ### Whole and reopened first-renderer irradiance pass diff --git a/docs/sbs-root-nodes.md b/docs/sbs-root-nodes.md index f61f53d5..0b68b84c 100644 --- a/docs/sbs-root-nodes.md +++ b/docs/sbs-root-nodes.md @@ -51,7 +51,7 @@ Eight original called-function graphs now match all 49,152 F32 pixels when a ste In the two eighth specular passes, the corrected pixel arithmetic matched all 2,304 scanline pixels across zero through eight contributions. The changed 128² pass 396 scores 16,384/16,384 · 0 in F16 and the default 128² pass 408 scores 16,384/16,384 · 0. All 376,832 pixels in the direct and reusable function graphs match, as do all 131,072 reopened pixels. [Raw counts and procedural inputs](parity-fixes.md#reciprocal-division-through-pixel-function-calls) -A completed diagnostic traversal of the dense 32² BNW Spots 3 v2 case matched 1,024/1,024 F32 pixels on both explicit one-worker reference runs. Two eight-worker reference runs matched one another on 887/1,024 pixels. The production cook still reaches its visit limit. [Dense Quadrant and saved-file measurements](parity-fixes.md#dense-quadrant-traversal-and-reference-worker-counts) +The production cook and its reopened file now match 1,024/1,024 F32 pixels on both explicit one-worker reference runs for dense 32² BNW Spots 3 v2. The desktop comparison gives 894/1,024, and two eight-worker reference runs match each other on 887/1,024. [Bounded terminal Quadrant work](parity-fixes.md#bounded-work-for-terminal-quadrant-siblings) [Dense Quadrant and saved-file measurements](parity-fixes.md#dense-quadrant-traversal-and-reference-worker-counts) Twelve original ancestor-offset controls matched 61,440/61,440 pixels. Three reopens matched another 15,360/15,360. In the two dense BNW Spots 3 packages, the tested square F32 settings that completed matched 4,608/4,608 pixels on the explicit one-worker renderer. Three settings still reached the execution budget. [Returning squares, renderer repeats and per-format counts](parity-fixes.md#branch-offsets-center-culling-and-two-dense-spot-graphs) @@ -386,7 +386,7 @@ Creased matches 10,947,840/10,947,840 pixels across 100 distinct settings throug | [noise_bnw_spots_1.sbs/bnw_spots_1](../assets/sbs/noise_bnw_spots_1.sbs) | 0 | Yes | [In progress · 782,741/841,728 pixels on one processor, 788,160/841,728 on eight across 86 settings](parity-fixes.md#first-level-draw-order-in-repeated-spot-quadrants) · [Earlier 60-setting comparison](parity-fixes.md#connected-quadrant-depth-and-amplified-spot-patterns) · [Zero roughness exact in U16 and F32](parity-fixes.md#grayscale-pattern-output-at-zero-roughness) · [Draw order, 18 changed-format comparisons](parity-fixes.md#draw-order-for-overlapping-procedural-grayscale-stamps) · [12 settings and four attempted reopens](parity-fixes.md#moisture-spot-and-cell-fields-across-processors-and-saved-packages) · [Explicit renderer workers and repeatability](parity-fixes.md#patterns-with-an-explicit-reference-worker-count) | | [noise_bnw_spots_1_v2.sbs/bnw_spots_1](../assets/sbs/noise_bnw_spots_1_v2.sbs) | 0 | No | [In progress · 831,506/842,752 pixels on one processor, 831,311/842,752 on eight · 87 settings](parity-fixes.md#whole-root-precision-and-saved-comparisons-for-the-three-neighboring-spot-graphs) · [Earlier spot comparison](parity-fixes.md#connected-quadrant-depth-and-amplified-spot-patterns) · [Zero roughness exact in U16 and F32](parity-fixes.md#grayscale-pattern-output-at-zero-roughness) · [Draw order, 18 changed-format comparisons](parity-fixes.md#draw-order-for-overlapping-procedural-grayscale-stamps) · [12 settings and four attempted reopens](parity-fixes.md#moisture-spot-and-cell-fields-across-processors-and-saved-packages) · [Explicit renderer workers and repeatability](parity-fixes.md#patterns-with-an-explicit-reference-worker-count) | | [noise_bnw_spots_3.sbs/bnw_spots_3](../assets/sbs/noise_bnw_spots_3.sbs) | 0 | Yes | [In progress · 671,452/671,744 pixels on one processor, 671,526/671,744 on eight · 48 of 62 settings rendered](parity-fixes.md#whole-root-precision-and-saved-comparisons-for-the-three-neighboring-spot-graphs) · [Earlier spot comparison](parity-fixes.md#deep-pattern-samples-in-custom-render-and-tiling-regions) · [Earlier matrix](parity-fixes.md#bnw-spots-3-and-cells-1-pattern-sources) · [64² precision and remaining traversal limits](parity-fixes.md#precision-of-two-dense-noise-generators-in-custom-regions) · [12 settings and four attempted reopens](parity-fixes.md#moisture-spot-and-cell-fields-across-processors-and-saved-packages) · [Explicit worker counts](parity-fixes.md#branch-offsets-center-culling-and-two-dense-spot-graphs) | -| [noise_bnw_spots_3_v2.sbs/bnw_spots_3](../assets/sbs/noise_bnw_spots_3_v2.sbs) | 0 | No | [In progress · 339,986/347,136 pixels on one processor, 341,093/347,136 on eight · 30 of 62 settings rendered](parity-fixes.md#whole-root-precision-and-saved-comparisons-for-the-three-neighboring-spot-graphs) · [Earlier spot comparison](parity-fixes.md#bnw-spots-3-and-cells-1-pattern-sources) · [12 settings and four attempted reopens](parity-fixes.md#moisture-spot-and-cell-fields-across-processors-and-saved-packages) · [bounded stage counts at scale two](parity-fixes.md#four-cloud-noise-generators-and-repeated-saved-file-comparisons) · [Explicit worker counts](parity-fixes.md#branch-offsets-center-culling-and-two-dense-spot-graphs) · [Dense F32 traversal and worker repeats](parity-fixes.md#dense-quadrant-traversal-and-reference-worker-counts) | +| [noise_bnw_spots_3_v2.sbs/bnw_spots_3](../assets/sbs/noise_bnw_spots_3_v2.sbs) | 0 | No | [In progress · dense 32² now renders, 1,024/1,024 on one worker, 894/1,024 on desktop](parity-fixes.md#bounded-work-for-terminal-quadrant-siblings) · [Earlier comparison · 339,986/347,136 pixels on one processor, 341,093/347,136 on eight · 30 of 62 settings rendered](parity-fixes.md#whole-root-precision-and-saved-comparisons-for-the-three-neighboring-spot-graphs) · [Earlier spot comparison](parity-fixes.md#bnw-spots-3-and-cells-1-pattern-sources) · [12 settings and four attempted reopens](parity-fixes.md#moisture-spot-and-cell-fields-across-processors-and-saved-packages) · [bounded stage counts at scale two](parity-fixes.md#four-cloud-noise-generators-and-repeated-saved-file-comparisons) · [Explicit worker counts](parity-fixes.md#branch-offsets-center-culling-and-two-dense-spot-graphs) · [Dense F32 traversal and worker repeats](parity-fixes.md#dense-quadrant-traversal-and-reference-worker-counts) | | [noise_cells_1.sbs/cells_1](../assets/sbs/noise_cells_1.sbs) | 0 | Yes | [Parity · 928,000/928,000 pixels across 88 distinct settings on one and eight processors](parity-fixes.md#inverting-the-stored-pixel-projection-in-scaled-stamp-regions) · [Earlier scaled-window comparisons](parity-fixes.md#projecting-stamp-vertices-relative-to-pixel-centers-in-scaled-windows) · [Earlier root comparisons](parity-fixes.md#bnw-spots-3-and-cells-1-pattern-sources) · [717,776/729,344 pixels in 60 settings at one and eight processors](parity-fixes.md#moisture-spot-and-cell-fields-across-processors-and-saved-packages) | | [noise_cells_1_v2.sbs/cells_1](../assets/sbs/noise_cells_1_v2.sbs) | 0 | No | [Parity · 947,456/947,456 pixels across 89 distinct settings on one and eight processors](parity-fixes.md#inverting-the-stored-pixel-projection-in-scaled-stamp-regions) · [Earlier scaled-window comparisons](parity-fixes.md#projecting-stamp-vertices-relative-to-pixel-centers-in-scaled-windows) · [Earlier root comparisons](parity-fixes.md#original-and-reopened-dirt-moisture-and-cellular-noise-fields) · [Earlier measurements](parity-fixes.md#streaming-repeated-pattern-visits) · [745,614/748,800 pixels in 61 settings at one and eight processors](parity-fixes.md#moisture-spot-and-cell-fields-across-processors-and-saved-packages) | | [noise_cells_4.sbs/cells_4](../assets/sbs/noise_cells_4.sbs) | 1 | Yes | [Parity · 1,028,608/1,028,608 pixels across 79 distinct settings](parity-fixes.md#distance-propagation-on-rectangular-and-tied-cellular-fields) · [Earlier measurements](parity-fixes.md#original-and-reopened-dirt-moisture-and-cellular-noise-fields) · [Earlier measurements](parity-fixes.md#paths-caustics-and-cell-fields-after-pattern-sampling) |