From 5de18a496e78f5dbbbd73544d7590ccd44fbfa73 Mon Sep 17 00:00:00 2001 From: selune <35337584+0xlillith@users.noreply.github.com> Date: Fri, 30 Oct 2026 13:30:34 +0100 Subject: [PATCH] docs(render): preserve reviewed parity preparation and original unrun acceptance cases --- .../CURRENT-REBIND.md | 5 + .../current-rebind.patch | 1021 +++++++++++++++++ .../render/2026-10-30/ev-hdr-e2e/README.md | 7 + .../2026-10-30/ev-hdr-e2e/proposal.patch | 184 +++ .../midpass-film-preparation/README.md | 9 + .../midpass-film-preparation/options.md | 104 ++ .../midpass-film-preparation/proposal.patch | 246 ++++ .../output-envelope-helpers/README.md | 7 + .../output-envelope-helpers/proposal.patch | 709 ++++++++++++ 9 files changed, 2292 insertions(+) create mode 100644 proposals/render/2026-10-30/cpu-nested-boxes-v2-source-review/CURRENT-REBIND.md create mode 100644 proposals/render/2026-10-30/cpu-nested-boxes-v2-source-review/current-rebind.patch create mode 100644 proposals/render/2026-10-30/ev-hdr-e2e/README.md create mode 100644 proposals/render/2026-10-30/ev-hdr-e2e/proposal.patch create mode 100644 proposals/render/2026-10-30/midpass-film-preparation/README.md create mode 100644 proposals/render/2026-10-30/midpass-film-preparation/options.md create mode 100644 proposals/render/2026-10-30/midpass-film-preparation/proposal.patch create mode 100644 proposals/render/2026-10-30/output-envelope-helpers/README.md create mode 100644 proposals/render/2026-10-30/output-envelope-helpers/proposal.patch diff --git a/proposals/render/2026-10-30/cpu-nested-boxes-v2-source-review/CURRENT-REBIND.md b/proposals/render/2026-10-30/cpu-nested-boxes-v2-source-review/CURRENT-REBIND.md new file mode 100644 index 000000000..b007e0f37 --- /dev/null +++ b/proposals/render/2026-10-30/cpu-nested-boxes-v2-source-review/CURRENT-REBIND.md @@ -0,0 +1,5 @@ +# Current-source cumulative V2 plus engine proposal + +The current-rebind.patch is a single seven-path cumulative proposal against the pinned C12 receiver, replacing separate V2/engine applications; do not double-apply. It preserves current Area/LED, all213 UI declarations and all prior Render test prefixes. Only one NEW engine-test diagnostic literal is updated for the actual Area/LED contract; no historical assertion or optical oracle changes. + +Independent numerical delta and Engine route reviews found no new actionable source blocker. It proposes13 Render and2 Engine declarations. All remain uncompiled/unrun and the proposal is NOT APPLIED. The shared C12 source remains frozen. Recheck exact preimages and dependencies before any later adoption. Existing V1 remains blocked and archived; general/progressive/Interactive glass and normal physical-library routing remain open. diff --git a/proposals/render/2026-10-30/cpu-nested-boxes-v2-source-review/current-rebind.patch b/proposals/render/2026-10-30/cpu-nested-boxes-v2-source-review/current-rebind.patch new file mode 100644 index 000000000..3661c4d63 --- /dev/null +++ b/proposals/render/2026-10-30/cpu-nested-boxes-v2-source-review/current-rebind.patch @@ -0,0 +1,1021 @@ +--- a/crates/render/src/raytrace/dielectric.rs ++++ b/crates/render/src/raytrace/dielectric.rs +@@ -241,6 +241,160 @@ + lo.x <= hi.x && lo.y <= hi.y && lo.z <= hi.z + } + ++/// Immediate parents of already-certified axis-aligned boxes. Strict containment ++/// is sufficient for this exact box subset; touching and partial overlap refuse. ++/// Eight overrides bound this to at most 64 comparisons, without allocation. ++pub(super) fn parents( ++ certificates: &[Option; MAX_OVERRIDES], ++ nested: bool, ++) -> Result<[Option; MAX_OVERRIDES]> { ++ let mut result = [None; MAX_OVERRIDES]; ++ for (child, certificate) in certificates.iter().enumerate() { ++ let Some(Certificate::ClosedBox(bounds)) = certificate else { continue }; ++ for (candidate, certificate) in certificates.iter().enumerate() { ++ let Some(Certificate::ClosedBox(container)) = certificate else { continue }; ++ if candidate == child || !overlaps(*bounds, *container) { ++ continue; ++ } ++ if !nested { ++ return Err(TraceError::InvalidInput("nested, touching or overlapping dielectric volumes are unsupported")); ++ } ++ if strictly_contains(*container, *bounds) { ++ let parent = result.get_mut(child).ok_or(TraceError::Internal("dielectric child index"))?; ++ let replace = match *parent { ++ None => true, ++ Some(previous) => match certificates.get(previous).copied().flatten() { ++ Some(Certificate::ClosedBox(old)) => strictly_contains(old, *container), ++ _ => return Err(TraceError::Internal("dielectric parent certificate")), ++ }, ++ }; ++ if replace { ++ *parent = Some(candidate); ++ } ++ } else if !strictly_contains(*bounds, *container) { ++ return Err(TraceError::InvalidInput("dielectric boxes must be disjoint or strictly nested; touching and overlap are unsupported")); ++ } ++ } ++ } ++ Ok(result) ++} ++ ++fn strictly_contains(outer: Bounds, inner: Bounds) -> bool { ++ let lo = outer.min(); ++ let hi = outer.max(); ++ let a = inner.min(); ++ let b = inner.max(); ++ lo.x < a.x && lo.y < a.y && lo.z < a.z && hi.x > b.x && hi.y > b.y && hi.z > b.z ++} ++ ++/// A certified axis-aligned face point, shared by propagation and Beer intervals. ++/// This is used only by the explicit nested-box path, never by general spawn. ++#[derive(Clone, Copy)] ++pub(super) struct ExactBoxFace { ++ pub point: Vec3, ++ axis: usize, ++ outward: f64, ++ entering: bool, ++} ++ ++impl ExactBoxFace { ++ pub fn spawn(self, direction: Vec3, reflected: bool) -> Result { ++ let ray = super::Ray::new(self.point, direction, 0.0_f64.next_up(), super::MAX_DISTANCE_MM)?; ++ let side = super::component(ray.direction(), self.axis) * self.outward; ++ let exterior = if reflected { self.entering } else { !self.entering }; ++ if (exterior && side <= 0.0) || (!exterior && side >= 0.0) { ++ return Err(TraceError::InvalidInput("nested box continuation is tangent or on the wrong side")); ++ } ++ Ok(ray) ++ } ++} ++ ++/// Recover the exact constant-axis coordinate from the actual certified face. ++/// Tangential coordinates are validated, never clamped or displaced. Equal ++/// ray/other-face depths conservatively refuse independently of ordinal ties. ++pub(super) fn exact_box_face( ++ bounds: Bounds, ++ vertices: [Vec3; 3], ++ normal: Vec3, ++ position: Vec3, ++ incoming: super::Ray, ++) -> Result { ++ let mut face = None; ++ for axis in 0..3 { ++ let [a, b, c] = vertices.map(|v| super::component(v, axis)); ++ if a == b && b == c { ++ if face.is_some() { ++ return Err(TraceError::InvalidInput("nested box face has ambiguous constant axes")); ++ } ++ face = Some((axis, a)); ++ } ++ } ++ let (axis, plane) = face.ok_or(TraceError::InvalidInput("nested box face is not axis aligned"))?; ++ let lo = bounds.min(); ++ let hi = bounds.max(); ++ let outward = if plane == super::component(lo, axis) { ++ -1.0 ++ } else if plane == super::component(hi, axis) { ++ 1.0 ++ } else { ++ return Err(TraceError::InvalidInput("nested box face disagrees with its certificate")); ++ }; ++ let axis_vector = match axis { ++ 0 => Vec3::X, ++ 1 => Vec3::Y, ++ 2 => Vec3::Z, ++ _ => return Err(TraceError::Internal("nested box face axis")), ++ }; ++ if normal != axis_vector * outward || Triangle::new(vertices)?.geometric_normal() != Some(normal) { ++ return Err(TraceError::InvalidInput("nested box outward normal disagrees with its certified face")); ++ } ++ for vertex in vertices { ++ for a in 0..3 { ++ let coordinate = super::component(vertex, a); ++ if coordinate != super::component(lo, a) && coordinate != super::component(hi, a) { ++ return Err(TraceError::InvalidInput("nested box face vertex is not a certified corner")); ++ } ++ } ++ } ++ let point = match axis { ++ 0 => Vec3::new(plane, position.y, position.z), ++ 1 => Vec3::new(position.x, plane, position.z), ++ 2 => Vec3::new(position.x, position.y, plane), ++ _ => return Err(TraceError::Internal("nested box point axis")), ++ }; ++ if !point.is_finite() { ++ return Err(TraceError::InvalidInput("nested box reconstructed point is not finite")); ++ } ++ let direction = super::component(incoming.direction(), axis); ++ if direction == 0.0 { ++ return Err(TraceError::InvalidInput("nested box incident ray is tangent")); ++ } ++ let depth = (plane - super::component(incoming.origin(), axis)) / direction; ++ let [min, max] = incoming.interval(); ++ if !depth.is_finite() || depth < min || depth > max { ++ return Err(TraceError::InvalidInput("nested box face is outside the incident ray interval")); ++ } ++ for a in 0..3 { ++ if a == axis { ++ continue; ++ } ++ let coordinate = super::component(point, a); ++ if coordinate <= super::component(lo, a) || coordinate >= super::component(hi, a) { ++ return Err(TraceError::InvalidInput("nested box edge, corner or outside-face point is ambiguous")); ++ } ++ let d = super::component(incoming.direction(), a); ++ if d != 0.0 { ++ for plane in [super::component(lo, a), super::component(hi, a)] { ++ let other = (plane - super::component(incoming.origin(), a)) / d; ++ if other == depth { ++ return Err(TraceError::InvalidInput("nested box simultaneous face depths are ambiguous")); ++ } ++ } ++ } ++ } ++ Ok(ExactBoxFace { point, axis, outward, entering: direction * outward < 0.0 }) ++} ++ + #[cfg(test)] + #[path = "dielectric_tests.rs"] + pub(super) mod tests; +--- a/crates/render/src/raytrace/image.rs ++++ b/crates/render/src/raytrace/image.rs +@@ -80,22 +80,16 @@ + } + type Look = PreparedPrimitive; + +-fn certificates(scene: &ProductScene, options: &RaytraceOptions) -> job::Result<[Option; MAX_OVERRIDES]> { ++fn certificates( ++ scene: &ProductScene, ++ options: &RaytraceOptions, ++ nested: bool, ++) -> job::Result<([Option; MAX_OVERRIDES], [Option; MAX_OVERRIDES])> { + let mut result = [None; MAX_OVERRIDES]; + for (slot, input) in result.iter_mut().zip(&options.dielectrics) { + *slot = Some(dielectric::certify(scene, input).map_err(error)?); + } +- for (i, left) in result.iter().enumerate() { +- if let Some(Certificate::ClosedBox(a)) = left { +- for right in result.iter().skip(i + 1) { +- if let Some(Certificate::ClosedBox(b)) = right +- && dielectric::overlaps(*a, *b) +- { +- return Err(invalid("nested, touching or overlapping dielectric volumes are unsupported")); +- } +- } +- } +- } ++ let parents = dielectric::parents(&result, nested).map_err(error)?; + // Sheets within volumes are unsupported. Conservatively use the admitted + // tiny sheet's bounds, rather than pretending to resolve medium nesting. + for (i, certificate) in result.iter().enumerate() { +@@ -112,10 +106,19 @@ + } + } + } +- Ok(result) ++ Ok((result, parents)) + } + + pub fn admit(scene: &ProductScene, request: &ImageRequest, options: &RaytraceOptions) -> job::Result { ++ admit_with_nested(scene, request, options, false) ++} ++ ++pub(crate) fn admit_with_nested( ++ scene: &ProductScene, ++ request: &ImageRequest, ++ options: &RaytraceOptions, ++ nested: bool, ++) -> job::Result { + options.validate()?; + if let Some(original) = &request.raytrace { + original.validate()?; +@@ -161,7 +164,7 @@ + } + } + anisotropic_faces::prepare(scene, options, || Ok(()))?; +- certificates(scene, options)?; ++ certificates(scene, options, nested)?; + for input in &options.dielectrics { + if options.reflections.as_ref().is_some_and(|r| r.bodies.iter().any(|v| v.body == input.body_name)) + || options.anisotropic_faces.iter().flatten().any(|v| v.body_index == input.body_index) +@@ -376,6 +379,8 @@ + /// lighting state, encode pixels, or allocate outside the existing job reservation. + struct OpticalTask { + certificates: [Option; MAX_OVERRIDES], ++ parents: [Option; MAX_OVERRIDES], ++ nested: bool, + pending: Option, + } + +@@ -515,16 +520,27 @@ + options: RaytraceOptions, + input: Option, + ) -> job::Result { ++ Self::new_with_environment_and_nested(scene, request, cancel, options, input, false) ++ } ++ ++ pub(crate) fn new_with_environment_and_nested( ++ scene: ProductScene, ++ request: ImageRequest, ++ cancel: CancelToken, ++ options: RaytraceOptions, ++ input: Option, ++ nested: bool, ++ ) -> job::Result { + cancel.check()?; +- let mut admission = admit(&scene, &request, &options)?; ++ let mut admission = admit_with_nested(&scene, &request, &options, nested)?; + let mut optical = Vec::new(); + if !options.dielectrics.is_empty() { +- let certificates = certificates(&scene, &options)?; ++ let (certificates, parents) = certificates(&scene, &options, nested)?; + optical.try_reserve_exact(1).map_err(|_| error(TraceError::AllocationFailed))?; + if optical.capacity() != 1 { + return Err(error(TraceError::MemoryLimit)); + } +- optical.push(OpticalTask { certificates, pending: None }); ++ optical.push(OpticalTask { certificates, parents, nested, pending: None }); + } + if input.is_some() { + options.validate_environment_reflections(&scene)?; +@@ -1299,7 +1315,19 @@ + let scene = PreparedScene { bvh, primitives: &self.looks, source: &self.scene }; + // Optics always uses the certified geometric boundary, before optional opaque + // shading-normal effects. Distance starts before the numerical spawn offset. +- let shared = scene.resolve_hit(pending.ray, hit).map_err(error)?; ++ let mut shared = scene.resolve_hit(pending.ray, hit).map_err(error)?; ++ let exact_face = if optical.nested { ++ match state.selected.and_then(|index| optical.certificates.get(index).copied().flatten()) { ++ Some(Certificate::ClosedBox(bounds)) => { ++ let face = dielectric::exact_box_face(bounds, shared.vertices, shared.geometric_normal, shared.position, pending.ray).map_err(error)?; ++ shared.position = face.point; ++ Some(face) ++ } ++ _ => None, ++ } ++ } else { ++ None ++ }; + if let Some(index) = state.path.medium { + let medium = self.options.dielectrics.get(index).ok_or_else(|| invalid("active dielectric medium"))?; + let distance = shared.position.dist(state.path.segment_start); +@@ -1363,16 +1391,21 @@ + if boundary_axes > 1 { + return Err(invalid("dielectric box edge or corner has an ambiguous interface normal")); + } ++ let parent = optical.parents.get(index).copied().ok_or_else(|| invalid("missing dielectric parent"))?; ++ let parent_ior = match parent { ++ Some(parent) => self.options.dielectrics.get(parent).ok_or_else(|| invalid("missing parent optical material"))?.ior, ++ None => 1.0, ++ }; + let (incident, transmitted, next_medium) = if shared.front_face { +- if state.path.medium.is_some() { +- return Err(invalid("nested dielectric entry")); ++ if state.path.medium != parent { ++ return Err(invalid("dielectric entry does not match certified parent")); + } +- (1.0, medium.ior, Some(index)) ++ (parent_ior, medium.ior, Some(index)) + } else { + if state.path.medium != Some(index) { + return Err(invalid("dielectric exit without matching entry")); + } +- (medium.ior, 1.0, None) ++ (medium.ior, parent_ior, parent) + }; + let optics = dielectric::interface(direction, normal, incident, transmitted).map_err(error)?; + let f = optics.reflectance; +@@ -1380,8 +1413,14 @@ + (optics, Vec3::new(f, f, f), Vec3::new(t, t, t), next_medium) + } + }; ++ let spawn = |direction, reflected| { ++ match exact_face { ++ Some(face) => face.spawn(direction, reflected).map_err(error), ++ None => shared.spawn(direction).map_err(error), ++ } ++ }; + state.push(OpticalPath { +- ray: shared.spawn(optics.reflected).map_err(error)?, ++ ray: spawn(optics.reflected, true)?, + throughput: dielectric::multiply(state.path.throughput, reflected_weight), + medium: state.path.medium, + segment_start: shared.position, +@@ -1390,7 +1429,7 @@ + })?; + if let Some(direction) = optics.transmitted { + state.push(OpticalPath { +- ray: shared.spawn(direction).map_err(error)?, ++ ray: spawn(direction, false)?, + throughput: dielectric::multiply(state.path.throughput, transmitted_weight), + medium: next_medium, + segment_start: shared.position, +--- a/crates/render/src/job/host.rs ++++ b/crates/render/src/job/host.rs +@@ -624,15 +624,16 @@ + request: ImageRequest, + cancel: CancelToken, + environment: Option, ++ job_options: JobOptions, + ) -> Result { +- let _ = &environment; ++ let _ = (&environment, &job_options); + match request.integrator { + Integrator::Raster => ImageTask::new(scene, request, cancel).and_then(TaskSlot::new).map(Self::Raster), + Integrator::Raytrace => { + #[cfg(feature = "raytrace-cpu")] + { + let options = request.raytrace.clone().unwrap_or_default(); +- crate::raytrace::image::ImageTask::new_with_environment(scene, request, cancel, options, environment) ++ crate::raytrace::image::ImageTask::new_with_environment_and_nested(scene, request, cancel, options, environment, job_options.nested_media) + .and_then(TaskSlot::new) + .map(Self::Raytrace) + } +@@ -695,7 +696,13 @@ + let request = work.request.ok_or_else(|| JobError::new(ErrorCode::Internal, "missing registered executor request"))?; + executor.begin(work.scene, request, work.handle.0.options, work.handle.0.cancel.clone()).map(WorkTask::Registered) + } else { +- WorkTask::new(work.scene, work.handle.0.request.clone(), work.handle.0.cancel.clone(), work.environment) ++ WorkTask::new( ++ work.scene, ++ work.handle.0.request.clone(), ++ work.handle.0.cancel.clone(), ++ work.environment, ++ work.handle.0.options, ++ ) + } + })) + .unwrap_or_else(|_| Err(JobError::new(ErrorCode::Internal, "image executor failed while preparing the job"))); +@@ -1104,10 +1111,27 @@ + Ok(admission) + } else { + request.cpu_budget().validate_execution()?; +- if options != JobOptions::default() { ++ // Only the existing nesting opt-in is admitted on the CPU raytrace path. ++ // Every other JobOptions field retains its exact default-only contract. ++ if (JobOptions { nested_media: false, ..options }) != JobOptions::default() { + return Err(JobError::new(ErrorCode::InvalidRequest, "CPU images use raytrace options, not progressive sampling controls")); + } +- admit(scene, request) ++ if !options.nested_media { ++ return admit(scene, request); ++ } ++ if request.integrator != Integrator::Raytrace || request.environment.is_some() || request.textures.is_some() || scene.has_transmission() { ++ return Err(JobError::new(ErrorCode::InvalidRequest, "CPU nested media require explicit raytrace dielectric overrides")); ++ } ++ #[cfg(feature = "raytrace-cpu")] ++ { ++ let defaults = super::RaytraceOptions::default(); ++ let raytrace = request.raytrace.as_ref().unwrap_or(&defaults); ++ crate::raytrace::image::admit_with_nested(scene, request, raytrace, true) ++ } ++ #[cfg(not(feature = "raytrace-cpu"))] ++ { ++ Err(JobError::new(ErrorCode::HostUnavailable, "CPU raytracing is not compiled in; enable raytrace-cpu")) ++ } + } + } + +--- a/crates/render/src/raytrace/dielectric_tests.rs ++++ b/crates/render/src/raytrace/dielectric_tests.rs +@@ -514,3 +514,212 @@ + // maps to 98, so this also detects a consumer still using the old series. + assert_eq!(pixel.expect("Brewster sheet fixture must finish"), [95, 95, 95, 255]); + } ++ ++#[test] ++fn strict_box_parent_selection_is_order_independent_and_opt_in() { ++ let bounds = |lo: f64, hi: f64| Bounds::new(Vec3::new(lo, lo, lo), Vec3::new(hi, hi, hi)).unwrap(); ++ let mut certificates = [None; MAX_OVERRIDES]; ++ certificates[0] = Some(Certificate::ClosedBox(bounds(2.0, 3.0))); ++ certificates[1] = Some(Certificate::ClosedBox(bounds(0.0, 5.0))); ++ certificates[2] = Some(Certificate::ClosedBox(bounds(1.0, 4.0))); ++ assert!(parents(&certificates, false).is_err()); ++ assert_eq!(parents(&certificates, true).unwrap(), [Some(2), None, Some(1), None, None, None, None, None]); ++ certificates.swap(0, 1); ++ assert_eq!(parents(&certificates, true).unwrap(), [None, Some(2), Some(0), None, None, None, None, None]); ++} ++ ++#[test] ++fn nesting_opt_in_still_refuses_touching_equal_and_partially_overlapping_boxes() { ++ let outer = Bounds::new(Vec3::ZERO, Vec3::new(4.0, 4.0, 4.0)).unwrap(); ++ for (lo, hi) in [ ++ (Vec3::new(0.0, 1.0, 1.0), Vec3::new(3.0, 3.0, 3.0)), ++ (Vec3::new(4.0, 1.0, 1.0), Vec3::new(5.0, 3.0, 3.0)), ++ (Vec3::new(4.0, 4.0, 1.0), Vec3::new(5.0, 5.0, 3.0)), ++ (Vec3::new(4.0, 4.0, 4.0), Vec3::new(5.0, 5.0, 5.0)), ++ (Vec3::ZERO, Vec3::new(4.0, 4.0, 4.0)), ++ (Vec3::new(3.0, 1.0, 1.0), Vec3::new(5.0, 3.0, 3.0)), ++ ] { ++ let mut certificates = [None; MAX_OVERRIDES]; ++ certificates[0] = Some(Certificate::ClosedBox(outer)); ++ certificates[1] = Some(Certificate::ClosedBox(Bounds::new(lo, hi).unwrap())); ++ assert!(parents(&certificates, true).is_err()); ++ } ++} ++ ++pub(in crate::raytrace) fn nested_fixture(reverse: bool) -> (ProductScene, RaytraceOptions) { ++ let mut outer = box_body(4.0); ++ outer.name = "Outer".into(); ++ let mut inner = box_body(2.0); ++ inner.name = "Inner".into(); ++ for p in &mut Arc::make_mut(&mut inner.mesh).positions { ++ *p = Vec3::new(p.x * 0.5, p.y * 0.5, p.z + 1.0); ++ } ++ let mut scene = scene(outer); ++ scene.meshes.push(inner); ++ if reverse { ++ scene.meshes.reverse(); ++ } ++ let dielectrics = scene.meshes.iter().enumerate().map(|(body_index, body)| DielectricOptions { ++ body_index, ++ body_name: body.name.clone(), ++ boundary: DielectricBoundary::ClosedBox, ++ ior: 1.0, ++ absorption_per_mm: if body.name == "Outer" { [0.1, 0.2, 0.0] } else { [0.3, 0.4, 0.0] }, ++ thickness_mm: 0.0, ++ }).collect(); ++ (scene, RaytraceOptions { ++ dielectrics, ++ environment: environment(), ++ lights: Some(Vec::new()), ++ shadows: false, ++ ..Default::default() ++ }) ++} ++ ++#[test] ++fn actual_nested_png_uses_parent_only_outside_the_inner_interval() { ++ for reverse in [false, true] { ++ let (scene, options) = nested_fixture(reverse); ++ assert!(super::super::image::admit(&scene, &request(options.clone()), &options).is_err()); ++ let mut task = super::super::image::ImageTask::new_with_environment_and_nested( ++ scene, request(options.clone()), CancelToken::default(), options, None, true, ++ ).unwrap(); ++ let mut completed = false; ++ for _ in 0..100_000 { ++ if let TaskPoll::Complete(png) = task.step(16384).unwrap() { ++ let image = ::image::load_from_memory(&png).unwrap().to_rgba8(); ++ // Outer length2, inner length2; Beer radiance (exp(-.8), exp(-1.2), 1). ++ // Reinhard then IEC sRGB encoding gives these independently fixed bytes. ++ assert_eq!(image.get_pixel(0, 0).0, [151, 132, 188, 255]); ++ completed = true; ++ break; ++ } ++ } ++ assert!(completed, "nested final image did not complete"); ++ } ++} ++ ++#[test] ++fn nested_opt_in_does_not_enable_dielectric_progressive_or_interactive() { ++ let (_, mut options) = nested_fixture(false); ++ options.progressive = Some(Default::default()); ++ assert!(options.validate().is_err()); ++ let (_, options) = nested_fixture(false); ++ assert!(crate::job::interactive::cpu_request(&request(options)).is_err()); ++} ++ ++#[cfg(not(target_arch = "wasm32"))] ++#[test] ++fn native_host_forwards_only_the_existing_nested_media_exception() { ++ use crate::job::{CpuHost, ErrorCode, JobId, JobOptions, Phase}; ++ let host = CpuHost::for_platform().unwrap(); ++ let (scene, options) = nested_fixture(false); ++ let request = request(options); ++ let nested = JobOptions { nested_media: true, ..Default::default() }; ++ assert!(host.admit(&scene, &request, JobOptions::default()).is_err()); ++ assert!(host.admit(&scene, &request, nested).is_ok()); ++ for bad in [ ++ JobOptions { samples: 2, ..nested }, ++ JobOptions { max_depth: 2, ..nested }, ++ JobOptions { seed: 7, ..nested }, ++ JobOptions { exposure_ev: 1.0, ..nested }, ++ JobOptions { transmission_samples: 2, ..nested }, ++ JobOptions { denoise: true, ..nested }, ++ JobOptions { linear_exr: true, ..nested }, ++ ] { ++ assert_eq!(host.admit(&scene, &request, bad).unwrap_err().code, ErrorCode::InvalidRequest); ++ } ++ let mut raster = request.clone(); ++ raster.integrator = Integrator::Raster; ++ raster.raytrace = None; ++ assert!(host.admit(&scene, &raster, nested).is_err()); ++ let handle = host.submit_with_options( ++ JobId { session: 6302, serial: 1, generation: 1 }, 1, scene, request, nested, ++ ).unwrap(); ++ assert_eq!(handle.wait_timeout(std::time::Duration::from_secs(60)).unwrap().progress.phase, Phase::Completed); ++ assert_eq!(handle.status().unwrap().options.nested_media, true); ++ let frame = handle.frame().unwrap().unwrap(); ++ let image = ::image::load_from_memory(frame.png()).unwrap().to_rgba8(); ++ assert_eq!(image.get_pixel(0, 0).0, [151, 132, 188, 255]); ++} ++ ++fn face_fixture(axis: usize, positive: bool) -> (Bounds, [Vec3; 3], Vec3, Vec3) { ++ let point = |a: f64, u: f64, v: f64| match axis { ++ 0 => Vec3::new(a, u, v), ++ 1 => Vec3::new(v, a, u), ++ 2 => Vec3::new(u, v, a), ++ _ => panic!("test axis"), ++ }; ++ let bounds = Bounds::new(Vec3::new(1.0, 1.0, 1.0), Vec3::new(4.0, 4.0, 4.0)).unwrap(); ++ let plane = if positive { 4.0 } else { 1.0 }; ++ let mut vertices = [point(plane, 1.0, 1.0), point(plane, 4.0, 1.0), point(plane, 4.0, 4.0)]; ++ if !positive { ++ vertices.swap(1, 2); ++ } ++ let normal = match axis { 0 => Vec3::X, 1 => Vec3::Y, 2 => Vec3::Z, _ => panic!("test axis") } * if positive { 1.0 } else { -1.0 }; ++ (bounds, vertices, normal, point(plane, 2.5, 2.5)) ++} ++ ++#[test] ++fn exact_face_excludes_own_zero_depth_and_retains_one_ulp_neighbour_on_every_axis_and_side() { ++ use super::super::Ray; ++ for axis in 0..3 { ++ for positive in [false, true] { ++ let (bounds, vertices, normal, position) = face_fixture(axis, positive); ++ for entering in [false, true] { ++ let direction = if entering { -normal } else { normal }; ++ let incoming = Ray::new(position - direction, direction, 0.0, 10.0).unwrap(); ++ let face = exact_box_face(bounds, vertices, normal, position, incoming).unwrap(); ++ assert_eq!(face.point, position, "face diagonal is valid interior"); ++ let optics = interface(direction, -direction, if entering { 1.0 } else { 1.5 }, if entering { 1.5 } else { 1.0 }).unwrap(); ++ let reflected = face.spawn(optics.reflected, true).unwrap(); ++ let transmitted = face.spawn(optics.transmitted.unwrap(), false).unwrap(); ++ let triangle = Triangle::new(vertices).unwrap(); ++ assert!(triangle.intersect(&reflected).is_none(), "own reflected face at t0 must be excluded"); ++ assert!(triangle.intersect(&transmitted).is_none(), "own transmitted face at t0 must be excluded"); ++ assert_eq!(reflected.origin(), face.point); ++ assert_eq!(transmitted.origin(), face.point); ++ assert_eq!(transmitted.interval()[0], 0.0_f64.next_up()); ++ let plane = super::super::component(position, axis); ++ let next = if super::super::component(direction, axis) > 0.0 { plane.next_up() } else { plane.next_down() }; ++ let neighbour = vertices.map(|v| match axis { ++ 0 => Vec3::new(next, v.y, v.z), ++ 1 => Vec3::new(v.x, next, v.z), ++ 2 => Vec3::new(v.x, v.y, next), ++ _ => panic!("test axis"), ++ }); ++ let hit = Triangle::new(neighbour).unwrap().intersect(&transmitted).expect("one-ULP positive face must remain ahead"); ++ assert_eq!(hit.distance, (next - plane).abs()); ++ } ++ } ++ } ++} ++ ++#[test] ++fn exact_face_recovers_certified_plane_without_clamping_or_blessing_ties() { ++ use super::super::Ray; ++ let (bounds, vertices, normal, point) = face_fixture(2, false); ++ let incoming = Ray::new(point - Vec3::Z, Vec3::Z, 0.0, 10.0).unwrap(); ++ let rounded = Vec3::new(point.x, point.y, point.z.next_up()); ++ let face = exact_box_face(bounds, vertices, normal, rounded, incoming).unwrap(); ++ assert_eq!(face.point, point); ++ for bad in [ ++ Vec3::new(1.0, 2.5, 1.0), Vec3::new(1.0, 1.0, 1.0), ++ Vec3::new(1.0_f64.next_down(), 2.5, 1.0), Vec3::new(f64::NAN, 2.5, 1.0), ++ ] { ++ assert!(exact_box_face(bounds, vertices, normal, bad, incoming).is_err()); ++ } ++ let tied = Ray::new(Vec3::ZERO, Vec3::new(1.0, 1.0, 1.0), 0.0, 10.0).unwrap(); ++ // Even if rounded tangential reconstruction claims interior, independently ++ // equal actual ray/face depths cannot inherit the BVH ordinal's blessing. ++ let uncertain = Vec3::new(1.0_f64.next_up(), 1.0_f64.next_up(), 1.0); ++ assert!(exact_box_face(bounds, vertices, normal, uncertain, tied).is_err()); ++ assert!(exact_box_face(bounds, vertices, -normal, point, incoming).is_err()); ++ let other_bounds = Bounds::new(Vec3::ZERO, Vec3::new(4.0, 4.0, 4.0)).unwrap(); ++ assert!(exact_box_face(other_bounds, vertices, normal, point, incoming).is_err()); ++ let tangent = Ray::new(point - Vec3::X, Vec3::X, 0.0, 10.0).unwrap(); ++ assert!(exact_box_face(bounds, vertices, normal, point, tangent).is_err()); ++ assert!(face.spawn(Vec3::X, true).is_err()); ++ assert!(face.spawn(-Vec3::Z, false).is_err()); ++ assert!(face.spawn(Vec3::Z, true).is_err()); ++} +--- a/crates/render/src/raytrace/image_tests.rs ++++ b/crates/render/src/raytrace/image_tests.rs +@@ -1421,3 +1421,241 @@ + cancel.cancel(); + assert_eq!(PendingPixelSlot::new(&cancel).err().unwrap().code, ErrorCode::Cancelled); + } ++ ++fn nested_optical_task() -> ImageTask { ++ let (scene, mut options) = dielectric::tests::nested_fixture(false); ++ for medium in &mut options.dielectrics { ++ medium.ior = if medium.body_name == "Outer" { 1.5 } else { 2.0 }; ++ medium.absorption_per_mm = [0.0; 3]; ++ } ++ ImageTask::new_with_environment_and_nested( ++ scene, dielectric::tests::request(options.clone()), CancelToken::default(), options, None, true, ++ ).unwrap() ++} ++ ++#[test] ++fn nested_image_interfaces_use_actual_parent_ior_and_restore_it_on_exit() { ++ let mut task = nested_optical_task(); ++ let outer_entry = 0.96 / 2.25; ++ let inner_entry = outer_entry * (27.0 / 49.0); ++ let inner_exit = inner_entry * (256.0 / 147.0); ++ let expected = [ ++ (1, Some(0), outer_entry), ++ (2, Some(1), inner_entry), ++ (3, Some(0), inner_exit), ++ (4, None, inner_exit * 2.16), ++ ]; ++ let mut next = 0; ++ for _ in 0..100_000 { ++ assert!(matches!(task.step(1).unwrap(), TaskPoll::Pending(_))); ++ if let Some(state) = task.optical.first().and_then(|optical| optical.pending.as_ref()) { ++ let (depth, medium, throughput) = expected[next]; ++ if state.path.boundaries == depth && state.path.medium == medium { ++ assert!((state.path.throughput.x - throughput).abs() < 1e-12); ++ assert!((state.path.throughput.y - throughput).abs() < 1e-12); ++ assert!((state.path.throughput.z - throughput).abs() < 1e-12); ++ next += 1; ++ if next == expected.len() { ++ return; ++ } ++ } ++ } ++ } ++ panic!("nested first transmitted path did not cross all four interfaces"); ++} ++ ++#[test] ++fn nested_paths_keep_one_unit_work_cancellation_and_total_budget_contracts() { ++ for cancel in [false, true] { ++ let mut task = nested_optical_task(); ++ let mut observed = false; ++ for _ in 0..100_000 { ++ let before = task.work.used(); ++ assert!(matches!(task.step(1).unwrap(), TaskPoll::Pending(_))); ++ assert!(task.work.used() - before <= 1, "one-unit continuation overspent its quantum"); ++ if task.optical.first().and_then(|optical| optical.pending.as_ref()).is_some_and(|state| state.path.medium == Some(1)) { ++ if cancel { ++ task.cancel.cancel(); ++ } else { ++ task.work.limit = task.work.used(); ++ } ++ assert_eq!(task.step(1).err().unwrap().code, if cancel { ErrorCode::Cancelled } else { ErrorCode::LimitExceeded }); ++ assert!(!task.done); ++ observed = true; ++ break; ++ } ++ } ++ assert!(observed, "nested interior was never reached"); ++ } ++} ++ ++#[test] ++fn nested_admission_bills_parent_table_and_keeps_geometry_and_camera_refusals() { ++ let (scene, options) = dielectric::tests::nested_fixture(false); ++ let request = dielectric::tests::request(options.clone()); ++ let admitted = admit_with_nested(&scene, &request, &options, true).unwrap(); ++ let original = options.retained_dielectric_bytes().unwrap() ++ + request.raytrace.as_ref().unwrap().retained_dielectric_bytes().unwrap() ++ + std::mem::size_of::() as u64; ++ assert!(admitted.preparation_bytes >= original); ++ assert!(std::mem::size_of::() >= std::mem::size_of::<[Option; MAX_OVERRIDES]>()); ++ ++ let mut invalid = scene.clone(); ++ std::sync::Arc::make_mut(&mut invalid.meshes[1].mesh).triangles.pop(); ++ assert!(admit_with_nested(&invalid, &request, &options, true).is_err()); ++ ++ let mut inside = request.clone(); ++ inside.camera.distance = 0.1; ++ inside.camera.target = Vec3::new(0.0, 0.0, 2.0); ++ let mut task = ImageTask::new_with_environment_and_nested(scene, inside, CancelToken::default(), options, None, true).unwrap(); ++ for _ in 0..100_000 { ++ match task.step(1) { ++ Err(error) => { ++ assert_eq!(error.code, ErrorCode::InvalidScene); ++ assert!(error.message.contains("inside a dielectric")); ++ return; ++ } ++ Ok(TaskPoll::Pending(_)) => {} ++ Ok(TaskPoll::Complete(_)) => panic!("inside camera must not publish"), ++ } ++ } ++ panic!("inside camera was not refused"); ++} ++ ++fn close_gap_nested_task(gap: f64, positive: bool) -> ImageTask { ++ use std::sync::Arc; ++ let mut outer = dielectric::tests::box_body(3.0); ++ outer.name = "OuterGap".into(); ++ for p in &mut Arc::make_mut(&mut outer.mesh).positions { ++ *p = Vec3::new(p.x * 0.2, p.y * 0.2, p.z + 1.0); ++ } ++ let mut inner = dielectric::tests::box_body(2.0); ++ inner.name = "InnerGap".into(); ++ for p in &mut Arc::make_mut(&mut inner.mesh).positions { ++ *p = Vec3::new(p.x * 0.1, p.y * 0.1, if p.z == 0.0 { 1.0 + gap } else { 3.0 }); ++ } ++ let mut scene = dielectric::tests::scene(outer); ++ scene.meshes.push(inner); ++ let options = RaytraceOptions { ++ dielectrics: scene.meshes.iter().enumerate().map(|(body_index, body)| job::DielectricOptions { ++ body_index, body_name:body.name.clone(), boundary:job::DielectricBoundary::ClosedBox, ++ ior:1.0, absorption_per_mm:[0.0;3], thickness_mm:0.0, ++ }).collect(), ++ lights:Some(Vec::new()), shadows:false, ++ environment:Some(job::RaytraceEnvironmentOptions { color:[1.0;3], intensity:1.0 }), ++ ..Default::default() ++ }; ++ let mut request = dielectric::tests::request(options.clone()); ++ request.camera.set_view(if positive { crate::StandardView::Bottom } else { crate::StandardView::Top }); ++ request.camera.target = Vec3::new(0.0,0.0,2.5); ++ request.camera.fov = 0.0; ++ ImageTask::new_with_environment_and_nested(scene, request, CancelToken::default(), options, None, true).unwrap() ++} ++ ++#[test] ++fn positive_one_ulp_nested_gap_and_separated_control_visit_every_real_interface() { ++ for gap in [f64::EPSILON, 0.25] { ++ for positive in [false, true] { ++ let mut task = close_gap_nested_task(gap, positive); ++ let points = if positive { [1.0,1.0+gap,3.0,4.0] } else { [4.0,3.0,1.0+gap,1.0] }; ++ let media = [Some(0),Some(1),Some(0),None]; ++ let mut next = 0; ++ let mut completed = false; ++ for _ in 0..100_000 { ++ match task.step(1).unwrap() { ++ TaskPoll::Pending(_) => { ++ if next < points.len() ++ && let Some(state) = task.optical.first().and_then(|optical| optical.pending.as_ref()) ++ && state.path.boundaries == next as u8 + 1 ++ { ++ assert_eq!(state.path.medium, media[next]); ++ assert_eq!(state.path.segment_start.z, points[next]); ++ assert_eq!(state.path.ray.origin(), state.path.segment_start, "propagation and Beer start share one physical point"); ++ assert_eq!(state.path.throughput, Vec3::new(1.0,1.0,1.0)); ++ next += 1; ++ } ++ } ++ TaskPoll::Complete(png) => { ++ assert_eq!(next, 4, "an admitted interface was skipped"); ++ let image = ::image::load_from_memory(&png).unwrap().to_rgba8(); ++ assert_eq!(image.get_pixel(0,0).0, [188,188,188,255]); ++ completed = true; ++ break; ++ } ++ } ++ } ++ assert!(completed, "close-gap image failed to complete"); ++ } ++ } ++} ++ ++#[test] ++fn nested_reflected_route_keeps_child_beer_then_restores_parent_from_both_sides() { ++ for positive in [false, true] { ++ let (scene, mut options) = dielectric::tests::nested_fixture(false); ++ for medium in &mut options.dielectrics { ++ medium.ior = if medium.body_name == "Outer" { 1.5 } else { 2.0 }; ++ } ++ let mut request = dielectric::tests::request(options.clone()); ++ request.camera.set_view(if positive { crate::StandardView::Bottom } else { crate::StandardView::Top }); ++ request.camera.target = Vec3::new(0.0,0.0,2.0); ++ request.camera.fov = 0.0; ++ let mut task = ImageTask::new_with_environment_and_nested(scene, request, CancelToken::default(), options, None, true).unwrap(); ++ let (near, far) = if positive { (1.0,3.0) } else { (3.0,1.0) }; ++ let factor = (0.96 / 2.25) * (27.0 / 49.0) / 49.0; ++ let reflected = Vec3::new(factor * (-0.1_f64 - 0.3*2.0).exp(), factor * (-0.2_f64 - 0.4*2.0).exp(), factor); ++ let returned = dielectric::multiply(reflected, Vec3::new((-0.3_f64*2.0).exp(),(-0.4_f64*2.0).exp(),1.0)) * (256.0/147.0); ++ let mut saw_reflected = false; ++ let mut restored = false; ++ for _ in 0..1_000_000 { ++ if let TaskPoll::Complete(_) = task.step(1).unwrap() { ++ break; ++ } ++ let Some(state) = task.optical.first().and_then(|optical| optical.pending.as_ref()) else { continue }; ++ let path = state.path; ++ if path.boundaries == 3 && path.medium == Some(1) && path.segment_start.z == far { ++ assert!((path.throughput - reflected).len() < 1e-12); ++ assert_eq!(path.ray.origin(), path.segment_start); ++ assert!(path.ray.direction().z * if positive { -1.0 } else { 1.0 } > 0.0); ++ saw_reflected = true; ++ } ++ if saw_reflected && path.boundaries == 4 && path.medium == Some(0) && path.segment_start.z == near { ++ assert!((path.throughput - returned).len() < 1e-12); ++ assert_eq!(path.ray.origin(), path.segment_start); ++ restored = true; ++ break; ++ } ++ } ++ assert!(saw_reflected && restored, "actual reflected child route never restored its parent"); ++ } ++} ++ ++#[test] ++fn exact_box_launch_is_opt_in_and_legacy_default_origin_is_preserved() { ++ for nested in [false, true] { ++ let mut material = dielectric::tests::input(job::DielectricBoundary::ClosedBox); ++ material.ior = 1.0; ++ let options = RaytraceOptions { dielectrics:vec![material], lights:Some(Vec::new()), shadows:false, ..Default::default() }; ++ let request = dielectric::tests::request(options.clone()); ++ let mut task = ImageTask::new_with_environment_and_nested( ++ dielectric::tests::scene(dielectric::tests::box_body(2.0)), request, CancelToken::default(), options, None, nested, ++ ).unwrap(); ++ let mut observed = false; ++ for _ in 0..100_000 { ++ assert!(matches!(task.step(1).unwrap(), TaskPoll::Pending(_))); ++ if let Some(state) = task.optical.first().and_then(|optical| optical.pending.as_ref()) ++ && state.path.boundaries == 1 && state.path.medium == Some(0) ++ { ++ assert_eq!(state.path.segment_start.z, 2.0); ++ if nested { ++ assert_eq!(state.path.ray.origin(), state.path.segment_start); ++ } else { ++ assert!(state.path.ray.origin().z < state.path.segment_start.z, "default must retain its original inward offset"); ++ } ++ observed = true; ++ break; ++ } ++ } ++ assert!(observed, "first box entry was not observed"); ++ } ++} +--- a/crates/engine/src/cmd/render/jobs.rs ++++ b/crates/engine/src/cmd/render/jobs.rs +@@ -11,6 +11,7 @@ + #[derive(Default, Deserialize)] + #[serde(default, deny_unknown_fields)] + struct Start { ++ nested_media: bool, + studio_weights: Option<[f64; 3]>, + progressive: bool, + denoise: bool, +@@ -381,6 +382,119 @@ + assert_eq!(before, (s.revision, s.undo.len(), s.redo.len(), s.evaluations, s.is_dirty())); + assert_eq!(wire["settings"]["width"], 3840); + } ++ #[cfg(all(feature = "raytrace-cpu", not(target_arch = "wasm32")))] ++ fn nested_command_fixture() -> (Session, Value) { ++ let mut s = Session::default(); ++ for (name, length, width, height) in [("Outer", 20, 20, 4), ("Inner", 10, 10, 2)] { ++ s.execute("solid.box", &json!({ ++ "length":length,"width":width,"height":height,"center":[0,0,2], ++ "operation":"new","body_name":name, ++ })).unwrap(); ++ } ++ s.execute("render.scene", &json!({})).unwrap(); ++ let scene = crate::product_scene::extract(&s).unwrap(); ++ assert_eq!(scene.meshes.len(), 2); ++ let dielectrics: Vec<_> = scene.meshes.iter().enumerate().map(|(index, body)| { ++ assert!(matches!(body.name.as_str(), "Outer" | "Inner")); ++ json!({ ++ "body_index":index,"body_name":body.name,"boundary":"closed_box","ior":1.0, ++ "absorption_per_mm":if body.name == "Outer" { [0.1,0.2,0.0] } else { [0.3,0.4,0.0] }, ++ "thickness_mm":0.0, ++ }) ++ }).collect(); ++ let mut camera = solidcraft_render::Camera { distance:50.0, fov:0.0, ..Default::default() }; ++ camera.set_view(solidcraft_render::StandardView::Top); ++ camera.target = solidcraft_geom::Vec3::new(0.0,0.0,2.0); ++ let host = solidcraft_render::job::CpuHost::for_platform().unwrap(); ++ assert_eq!(host.kind(), solidcraft_render::job::HostKind::NativeWorker); ++ assert!(host.is_available(), "this native test requires an available real CPU worker"); ++ s.set_render_job_host(Some(host)).unwrap(); ++ let wire = json!({ ++ "integrator":"raytrace","nested_media":true, ++ "settings":{"width":1,"height":1,"camera":camera,"background":[255,255,255],"job":null}, ++ "raytrace":{"dielectrics":dielectrics,"lights":[],"shadows":false, ++ "environment":{"color":[1,1,1],"intensity":1}}, ++ }); ++ (s, wire) ++ } ++ ++ #[cfg(all(feature = "raytrace-cpu", not(target_arch = "wasm32")))] ++ #[test] ++ fn command_nested_opt_in_reaches_retained_job_options_and_real_beer_transport() { ++ use solidcraft_render::job::{JobId, Phase}; ++ let (mut s, wire) = nested_command_fixture(); ++ let before = (s.revision, s.undo.len(), s.redo.len(), s.evaluations, s.is_dirty()); ++ let document = s.doc.clone(); ++ for value in [None, Some(false)] { ++ let mut default = wire.clone(); ++ if let Some(value) = value { ++ default["nested_media"] = json!(value); ++ } else { ++ default.as_object_mut().unwrap().remove("nested_media"); ++ } ++ for command in ["render.preflight", "render.start"] { ++ let error = s.execute(command, &default).unwrap_err().to_string(); ++ assert!(error.contains("nested, touching or overlapping dielectric volumes are unsupported"), "{command}: {error}"); ++ } ++ } ++ let checked = s.execute("render.preflight", &wire).unwrap(); ++ assert_eq!(checked["resolved"]["executor"], "cpu-raytrace"); ++ assert_eq!(checked["request"]["raytrace"]["dielectrics"], wire["raytrace"]["dielectrics"]); ++ let started = s.execute("render.start", &wire).unwrap(); ++ let id: JobId = serde_json::from_value(started["job"].clone()).unwrap(); ++ let handle = s.render_job_handle(id).unwrap(); ++ let status = handle.wait_timeout(std::time::Duration::from_secs(60)).unwrap(); ++ assert_eq!(status.progress.phase, Phase::Completed, "{:?}", status.error); ++ assert_eq!(status.options, solidcraft_render::job::JobOptions { nested_media:true, ..Default::default() }); ++ let retained = s.execute("render.status", &json!({"job":id})).unwrap(); ++ assert_eq!(retained["options"]["nested_media"], true); ++ let frame = handle.frame().unwrap().unwrap(); ++ let image = image::load_from_memory(frame.png()).unwrap().to_rgba8(); ++ // Independent Beer oracle: outer2mm + inner2mm, replacing the parent ++ // interval, yields exp(-.8), exp(-1.2),1 -> Reinhard+sRGB [151,132,188]. ++ assert_eq!(image.get_pixel(0,0).0, [151,132,188,255]); ++ assert!(std::sync::Arc::ptr_eq(&document, &s.doc)); ++ assert_eq!(before, (s.revision, s.undo.len(), s.redo.len(), s.evaluations, s.is_dirty())); ++ } ++ ++ #[cfg(all(feature = "raytrace-cpu", not(target_arch = "wasm32")))] ++ #[test] ++ fn command_nesting_keeps_default_false_and_rejects_other_gpu_controls_and_progressive_glass() { ++ use solidcraft_render::job::{JobId, JobOptions, Phase}; ++ let (mut s, wire) = nested_command_fixture(); ++ for (key, value) in [ ++ ("samples", json!(2)), ("max_depth", json!(2)), ("seed", json!(7)), ++ ("denoise", json!(true)), ("lens", json!({})), ++ ] { ++ let mut invalid = wire.clone(); ++ invalid[key] = value; ++ for command in ["render.preflight", "render.start"] { ++ assert!(s.execute(command, &invalid).is_err(), "{command} accepted unrelated control {key}"); ++ } ++ } ++ let mut progressive = wire.clone(); ++ progressive["raytrace"]["progressive"] = json!({"samples_per_pixel":2,"seed":0}); ++ let refusal = "InvalidRequest: CPU progressive currently supports isotropic opaque surfaces; use fixed sampling for dielectric or anisotropic inputs"; ++ for command in ["render.preflight", "render.start"] { ++ assert_eq!(s.execute(command, &progressive).unwrap_err().to_string(), refusal); ++ } ++ assert_eq!(interactive_params(&wire).unwrap_err().to_string(), refusal); ++ ++ // Ordinary CPU requests retain the exact default JobOptions; omission is ++ // not silently promoted to nesting by adding this explicit opt-in. ++ let mut opaque = wire; ++ opaque.as_object_mut().unwrap().remove("nested_media"); ++ opaque["raytrace"].as_object_mut().unwrap().remove("dielectrics"); ++ s.execute("render.preflight", &opaque).unwrap(); ++ let started = s.execute("render.start", &opaque).unwrap(); ++ let id: JobId = serde_json::from_value(started["job"].clone()).unwrap(); ++ let status = s.render_job_handle(id).unwrap().wait_timeout(std::time::Duration::from_secs(60)).unwrap(); ++ assert_eq!(status.progress.phase, Phase::Completed, "{:?}", status.error); ++ assert_eq!(status.options, JobOptions::default()); ++ let retained = s.execute("render.status", &json!({"job":id})).unwrap(); ++ assert_eq!(retained["options"]["nested_media"], false); ++ } ++ + } + + /// Resolve portable intent before choosing an executor. Legacy requests are left intact; +@@ -677,7 +791,8 @@ + background: settings.background, + transparent_background: input.transparent_background, + }; +- let mut admission = solidcraft_render::job::admit(&scene, &request).map_err(job_error)?; ++ let options = solidcraft_render::job::JobOptions { nested_media: input.nested_media, ..Default::default() }; ++ let mut admission = host.admit(&scene, &request, options).map_err(job_error)?; + let environment_bytes = environment.as_ref().map_or(Ok(0), |e| e.required_bytes()).map_err(|e| bad(command, e.to_string()))?; + let retained_lights = request.raytrace.as_ref().map_or(Ok(0), |o| o.retained_bytes()).map_err(job_error)?; + let retained_environment = +@@ -698,7 +813,7 @@ + Integrator::Raytrace => "opaque_only", + }; + let reply = json!({"ignored_controls":ignored,"stage_panels":settings.stage.len(),"stage_transport":"CPU direct/specular only; no diffuse interreflection", "cpu_budget":budget,"cpu_limits":budget.limits(),"environment":environment_info,"retained_request_bytes":retained_request_bytes,"resolved":resolved,"admission":admission,"request":request,"scene_generation":s.revision,"host":host.kind(),"transparency":transparency,"refraction":refraction,"dielectric_boundaries":if refraction {vec!["thin_sheet","closed_box"]} else {Vec::<&str>::new()}}); +- Ok(Prepared { replace: input.replace, scene, request, reply, environment, executor: resolved.executor, options: Default::default() }) ++ Ok(Prepared { replace: input.replace, scene, request, reply, environment, executor: resolved.executor, options }) + } + + fn prepare_progressive( +--- a/crates/engine/src/cmd/render.rs ++++ b/crates/engine/src/cmd/render.rs +@@ -124,7 +124,7 @@ + CommandSpec::new("render.settings.capture_hdr", "Save Render Settings with HDR", resources::capture_settings).icon("settings").doc_only() + .params("name, set: typed CPU/GPU setup patch with hdr/environment unset; path: scoped HDR; expected_sha256?: digest returned by render.hdr.inspect (changed sources refuse); rotation_rad?:0, intensity?:1; samples?:1/4/16/64 for CPU only (default16); assume_linear_srgb?:false for GPU only. Captures immutable bytes and saves resource plus setup atomically in one undo, without a host; returns name/setup/resource metadata, never source bytes"), + CommandSpec::new("render.preflight", "Check Render Request", jobs::preflight).icon("inspect").noundo().doc_only() +- .params("setup?: saved name OR settings?: full RenderSetup. A typed job selects raster/cpu_raytrace/gpu_path and its numerical options plus embedded HDR before dispatch; only replace and transient studio_weights may accompany it. Without job, the legacy runtime controls below remain available. See docs/render-settings.md. studio_weights?: three finite 0..1 visibility weights for raster or implicit GPU studio sources only; never saved. integrator?: raster (default) or raytrace; progressive?: false (registered GPU path, CPU integrator/LED options are mutually exclusive); samples?: 1..4096; max_depth?: 1..16; seed?: u32 for progressive; raytrace?: bounded runtime progressive/primary_samples/lights/punctual_lights/area_lights/area_samples/seed/exposure_ev/shadows/reflections/anisotropic_faces/emissions/surface_effects/dielectrics/environment options, only with raytrace. CPU raytrace.budget?: compact (legacy default), studio or workstation; see docs/render-cpu-resource-profiles.md for explicit image/geometry/memory/work limits. CPU raytrace.progressive?: {samples_per_pixel:1..profile limit, seed:u32}; requires primary_samples:1 and selected reflections.samples:1; bounded area/LED direct lights retain their existing source and emitter-sample limits; anisotropy and dielectrics require fixed sampling. See docs/render-cpu-progressive.md; environment?: {path: scoped HDR, expected_sha256?: inspected digest, rotation_radians: 0, intensity: 1, samples: 16} OR {resource: saved HDR digest, rotation_radians, intensity, samples}; embedded resources cannot combine with path/hash; explicit sRGB/D65 HDR primaries required. Opaque CPU preview with selected mirror/rough-specular reflections and certified planar anisotropy. HDR with rough reflections or anisotropy requires fully metallic selected bodies and all effective faces; unsupported combinations refuse. No MIS or GI. CPU runtime dielectrics support only certified thin_sheet/closed_box boundaries with explicit IOR and Beer absorption; see docs/render-raytrace-dielectrics.md. CPU emissions are visible radiance only; surface_effects change roughness/shading normals without geometry changes. led_strip?: continuous world-mm LED rectangle recipe; led_samples?: 1/4/16/64 for the whole strip, default16. At most8directional+8punctual+4rectangle/LED sources; shared area N. See docs/render-light-union.md. transparent_background?: false; replace?: false. With progressive:true, raytrace instead accepts GPU dielectrics/clear_coats/textures; environment instead accepts tagged hdr/embedded_hdr/sky with rotation_rad/intensity; file hdr supports expected_sha256, embedded_hdr uses a document resource digest. See docs/render-hdr-resources.md. GPU lens, studio lighting, tone_map, denoise, bounded finishing/backdrop and linear_exr retention are also available. GPU adaptive?: {pilot_samples:16..256,min_samples:16..samples,relative_error:0..1,absolute_error:0.000001..1000000,coverage_error:0.001..0.25} allocates independent production budgets; pilots are discarded, not a certified error guarantee. transmission_samples?:1|2|4 stratifies the first Fresnel branch with extra path cost. volume?:{min_mm:[x,y,z],max_mm:[x,y,z],extinction_per_mm:0..1000,scattering_albedo:[r,g,b],anisotropy:-0.95..0.95} is one finite homogeneous world-mm medium; active media require explicit lighting/environment and refuse glass, denoise and multiple transmission strata. These fields also persist in GPU job.options. See docs/render-materials/TRANSPORT-MASTER-BATCH-2026-10-23.md; see docs/render-transmission.md, render-environment.md, render-runtime-textures.md, render-thin-lens.md, render-studio-lighting.md and render-denoise.md. Optional CPU raytracing requires a raytrace-cpu build and native host, checked before scene capture. Stale geometry is rejected. See docs/render-jobs.md"), ++ .params("setup?: saved name OR settings?: full RenderSetup. A typed job selects raster/cpu_raytrace/gpu_path and its numerical options plus embedded HDR before dispatch; only replace and transient studio_weights may accompany it. Without job, the legacy runtime controls below remain available. See docs/render-settings.md. studio_weights?: three finite 0..1 visibility weights for raster or implicit GPU studio sources only; never saved. integrator?: raster (default) or raytrace; progressive?: false (registered GPU path, CPU integrator/LED options are mutually exclusive); samples?: 1..4096; max_depth?: 1..16; seed?: u32 for progressive; raytrace?: bounded runtime progressive/primary_samples/lights/punctual_lights/area_lights/area_samples/seed/exposure_ev/shadows/reflections/anisotropic_faces/emissions/surface_effects/dielectrics/environment options, only with raytrace. CPU raytrace.budget?: compact (legacy default), studio or workstation; see docs/render-cpu-resource-profiles.md for explicit image/geometry/memory/work limits. CPU raytrace.progressive?: {samples_per_pixel:1..profile limit, seed:u32}; requires primary_samples:1 and selected reflections.samples:1; bounded area/LED direct lights retain their existing source and emitter-sample limits; anisotropy and dielectrics require fixed sampling. See docs/render-cpu-progressive.md; environment?: {path: scoped HDR, expected_sha256?: inspected digest, rotation_radians: 0, intensity: 1, samples: 16} OR {resource: saved HDR digest, rotation_radians, intensity, samples}; embedded resources cannot combine with path/hash; explicit sRGB/D65 HDR primaries required. Opaque CPU preview with selected mirror/rough-specular reflections and certified planar anisotropy. HDR with rough reflections or anisotropy requires fully metallic selected bodies and all effective faces; unsupported combinations refuse. No MIS or GI. CPU runtime dielectrics support only certified thin_sheet/closed_box boundaries with explicit IOR and Beer absorption. nested_media?: false is the existing JobOptions opt-in; fixed CPU images admit only strictly nested certified closed_box boundaries with an exterior camera, while touching/partial overlaps, sheets within volumes and clearcoat combinations refuse. Other nondefault JobOptions remain unsupported on CPU; dielectric progressive and Interactive requests still refuse. GPU progressive uses the same nested_media field with its own certified-media contract; see docs/render-raytrace-dielectrics.md. CPU emissions are visible radiance only; surface_effects change roughness/shading normals without geometry changes. led_strip?: continuous world-mm LED rectangle recipe; led_samples?: 1/4/16/64 for the whole strip, default16. At most8directional+8punctual+4rectangle/LED sources; shared area N. See docs/render-light-union.md. transparent_background?: false; replace?: false. With progressive:true, raytrace instead accepts GPU dielectrics/clear_coats/textures; environment instead accepts tagged hdr/embedded_hdr/sky with rotation_rad/intensity; file hdr supports expected_sha256, embedded_hdr uses a document resource digest. See docs/render-hdr-resources.md. GPU lens, studio lighting, tone_map, denoise, bounded finishing/backdrop and linear_exr retention are also available. GPU adaptive?: {pilot_samples:16..256,min_samples:16..samples,relative_error:0..1,absolute_error:0.000001..1000000,coverage_error:0.001..0.25} allocates independent production budgets; pilots are discarded, not a certified error guarantee. transmission_samples?:1|2|4 stratifies the first Fresnel branch with extra path cost. volume?:{min_mm:[x,y,z],max_mm:[x,y,z],extinction_per_mm:0..1000,scattering_albedo:[r,g,b],anisotropy:-0.95..0.95} is one finite homogeneous world-mm medium; active media require explicit lighting/environment and refuse glass, denoise and multiple transmission strata. These fields also persist in GPU job.options. See docs/render-materials/TRANSPORT-MASTER-BATCH-2026-10-23.md; see docs/render-transmission.md, render-environment.md, render-runtime-textures.md, render-thin-lens.md, render-studio-lighting.md and render-denoise.md. Optional CPU raytracing requires a raytrace-cpu build and native host, checked before scene capture. Stale geometry is rejected. See docs/render-jobs.md"), + CommandSpec::new("render.start", "Render Image", jobs::start).key("R").noundo().doc_only().at("RENDER", "IMAGE").icon("render_image") + .params("Same request as render.preflight. Captures an immutable product scene and queues a bounded image job. Returns its session-scoped job identity, captured scene_generation and progress. Does not change the design. See docs/render-jobs.md"), + CommandSpec::new("render.status", "Render Progress", jobs::status).icon("list").noundo().doc_only() diff --git a/proposals/render/2026-10-30/ev-hdr-e2e/README.md b/proposals/render/2026-10-30/ev-hdr-e2e/README.md new file mode 100644 index 000000000..7d811df8a --- /dev/null +++ b/proposals/render/2026-10-30/ev-hdr-e2e/README.md @@ -0,0 +1,7 @@ +# Additional real CPU Interactive EV/HDR tests + +Source-only, independently reviewed, NOT APPLIED/FORMATTED/COMPILED/RUN. Appends two original tests to the actual213-test C12 postformatter prefix, resulting in215 declarations. Do not apply both this patch and a whole test-file overlay. + +EV0,+1,-1,0 follows real Snapshot/native CPU/admitted job/PNG/cache/upload. A normal-facing index-matched grey Lambert surface with one light has independently calculated display RGB51,72,35,51. Outer EV stays0; actual CPU job carries EV once. Reversal must restore identical PNG bytes. HDR adds accepted-image invalidation by pending intent, failed Resume, explicit Pause during real inspection/correction, actual CPU recovery and retention of that newly recovered frame when paused. Digest is checked on captured wire; no full job-HDR provenance, rotation/radiometry, desktop slider, Undo/Redo or in-place linear regrade claim is made. + +Requires two positive real-CPU markers. A feature-disabled/refused branch is not qualification. Existing source remains frozen for C12, so these tests belong to a subsequent coherent validation batch, not its53-case selection. diff --git a/proposals/render/2026-10-30/ev-hdr-e2e/proposal.patch b/proposals/render/2026-10-30/ev-hdr-e2e/proposal.patch new file mode 100644 index 000000000..28f994f43 --- /dev/null +++ b/proposals/render/2026-10-30/ev-hdr-e2e/proposal.patch @@ -0,0 +1,184 @@ +diff --git a/crates/ui-egui/src/render_workspace_tests.rs b/crates/ui-egui/src/render_workspace_tests.rs +--- a/crates/ui-egui/src/render_workspace_tests.rs ++++ b/crates/ui-egui/src/render_workspace_tests.rs +@@ -8407,3 +8407,180 @@ + assert_eq!(final_job.status().unwrap().progress.phase, Phase::Queued, "Off cannot cancel the unrelated final"); + final_job.cancel().unwrap(); + } ++ ++#[cfg(not(target_arch = "wasm32"))] ++#[test] ++fn interactive_ev_reversal_real_cpu_pixels_follow_one_exposure_with_independent_lambert_oracle() { ++ use solidcraft_engine::render::job::DirectionalLightOptions; ++ let mut h = interactive_ui_fixture(); ++ if !interactive_test_cpu_branch(&mut h, "interactive_ev_reversal_real_cpu_pixels_follow_one_exposure_with_independent_lambert_oracle") { ++ return; ++ } ++ h.app.run( ++ "appearance.assign", ++ json!({"bodies":["Subject"],"color":"#808080","opacity":1.0, ++ "pbr":{"metallic":0.0,"roughness":1.0,"dielectric_ior":1.0}}), ++ ).unwrap(); ++ // Front view sees the y=0 face normally. All jittered rays through the ++ // central pixel stay inside that face, so neither coverage nor noise is an oracle. ++ h.app.cam.target = solidcraft_engine::geom::Vec3::new(5.0, 4.0, 2.0); ++ h.app.cam.yaw = 0.0; ++ h.app.cam.pitch = 0.0; ++ h.app.cam.roll = 0.0; ++ h.app.cam.distance = 10.0; ++ h.app.cam.fov = 0.0; ++ h.app.cam.up = solidcraft_engine::render::UpAxis::Z; ++ h.app.render_workspace.view.cpu.environment = cpu::Environment::None; ++ h.app.render_workspace.view.raytrace = solidcraft_engine::render::job::RaytraceOptions { ++ lights: Some(vec![DirectionalLightOptions { direction: [0.0, -1.0, 0.0], color: [1.0; 3], intensity: 0.5 }]), ++ shadows: false, ++ ..Default::default() ++ }; ++ let camera = h.app.cam; ++ let final_options = h.app.render_workspace.view.raytrace.clone(); ++ let final_size = (h.app.render_workspace.view.draft.width, h.app.render_workspace.view.draft.height); ++ let document = h.app.session.doc.clone(); ++ let history = (h.app.session.revision, h.app.session.undo.len(), h.app.session.redo.len(), h.app.session.is_dirty()); ++ let epoch = interactive::test_clock(&h.app).as_secs_f64(); ++ h.app.run("render.interactive", json!({"action":"on"})).unwrap(); ++ let mut previous_job = None; ++ let mut baseline_png = None; ++ let mut previous_visual = None; ++ for (step, ev) in [0.0_f64, 1.0, -1.0, 0.0].into_iter().enumerate() { ++ let time = epoch + step as f64; ++ h.app.render_workspace.view.draft.exposure_ev = ev; ++ interactive_clear_acceptance_frame(&mut h, time, false); ++ let visual = interactive::inspect(&h.app)["visual_revision"].as_u64().unwrap(); ++ if let Some(previous) = previous_visual { ++ assert!(visual > previous, "each committed EV must invalidate the previous image"); ++ } ++ previous_visual = Some(visual); ++ assert!(interactive::test_cache(&h.app).is_none()); ++ assert!(interactive::test_current(&h.app).unwrap().is_none()); ++ // This is the real runtime request, not a test-only renderer request. ++ let wire = interactive_request(&h.app).unwrap(); ++ assert_eq!(wire["settings"]["exposure_ev"], 0.0, "outer EV must not duplicate the CPU EV"); ++ assert_eq!(wire["raytrace"]["exposure_ev"], ev); ++ interactive_clear_acceptance_frame(&mut h, time + 0.201, true); ++ let held = interactive_hold_real_completed_callback(&mut h); ++ let status = held.job.status().unwrap(); ++ assert_eq!(status.request.camera, camera); ++ assert_eq!(status.request.raytrace.as_ref().unwrap().exposure_ev, ev, "actual admitted job must carry EV exactly once"); ++ if let Some(previous) = previous_job { ++ assert_ne!(held.job.id(), previous, "an EV edit must not reuse the old admitted job"); ++ } ++ previous_job = Some(held.job.id()); ++ let frame = held.job.frame().unwrap().unwrap(); ++ let png = image::load_from_memory_with_format(frame.png(), image::ImageFormat::Png).unwrap().to_rgba8(); ++ // Original closed-form oracle: index-matched opaque dielectric has no ++ // Fresnel/specular term, so L = IEC-sRGB(128) * 0.5 / pi at normal incidence. ++ // Apply 2^EV once, Reinhard once, then IEC sRGB once and round to eight bits. ++ // No renderer BRDF/transfer helper or measured baseline supplies expectations. ++ let encoded = 128.0_f64 / 255.0; ++ let albedo = ((encoded + 0.055) / 1.055).powf(2.4); ++ let exposed = albedo * 0.5 / std::f64::consts::PI * 2.0_f64.powf(ev); ++ let mapped = exposed / (1.0 + exposed); ++ let srgb = if mapped <= 0.0031308 { 12.92 * mapped } else { 1.055 * mapped.powf(1.0 / 2.4) - 0.055 }; ++ let expected = (255.0 * srgb).round() as u8; ++ assert!(expected > 0 && expected < 255, "fixture must stay away from black and clipping"); ++ assert_eq!(png.get_pixel(7, 7).0, [expected, expected, expected, 255], "EV={ev}: actual native CPU PNG must match analytic radiance"); ++ if step == 0 { ++ baseline_png = Some(frame.png().to_vec()); ++ } else if step == 3 { ++ assert_eq!(frame.png(), baseline_png.as_ref().unwrap().as_slice(), "EV reversal must return the deterministic original PNG"); ++ } ++ held.sender.send(held.reply).unwrap(); ++ let (mut output, painted) = interactive_acceptance_frame(&mut h, time + 0.3, false, true); ++ assert!(painted); ++ let (cached, samples, complete, texture) = interactive::test_cache(&h.app).unwrap(); ++ assert_eq!((cached.job, cached.png_sha256), (held.job.id(), frame.info.png_sha256.clone())); ++ assert_eq!((samples, complete), (16, true)); ++ let uploaded = &output.textures_delta.set.get(&texture).unwrap().first().unwrap().image; ++ let egui::ImageData::Color(pixels) = uploaded; ++ assert_eq!(pixels.size, [16, 16]); ++ assert_eq!(pixels.pixels[7 * 16 + 7], Color32::from_rgb(expected, expected, expected), "the accepted texture must contain the analytic pixel"); ++ output.textures_delta.clear(); ++ assert_eq!(interactive::inspect(&h.app)["phase"], "TargetReached"); ++ assert_eq!(interactive::inspect(&h.app)["stale"], false); ++ assert_eq!(interactive::inspect(&h.app)["provisional"], true); ++ interactive_assert_final_export_isolation(&mut h, &held.job); ++ assert_eq!(h.app.render_workspace.view.raytrace, final_options); ++ assert_eq!((h.app.render_workspace.view.draft.width, h.app.render_workspace.view.draft.height), final_size); ++ assert!(Arc::ptr_eq(&document, &h.app.session.doc)); ++ assert_eq!((h.app.session.revision, h.app.session.undo.len(), h.app.session.redo.len(), h.app.session.is_dirty()), history); ++ } ++ h.app.run("render.interactive", json!({"action":"off"})).unwrap(); ++} ++ ++#[cfg(not(target_arch = "wasm32"))] ++#[test] ++fn interactive_pending_hdr_invalidates_accepted_pixels_and_checked_resume_then_pause_retains_recovery() { ++ let mut h = interactive_ui_fixture(); ++ if !interactive_test_cpu_branch(&mut h, "interactive_pending_hdr_invalidates_accepted_pixels_and_checked_resume_then_pause_retains_recovery") { ++ return; ++ } ++ let document = h.app.session.doc.clone(); ++ let history = (h.app.session.revision, h.app.session.undo.len(), h.app.session.redo.len(), h.app.session.is_dirty()); ++ let epoch = interactive::test_clock(&h.app).as_secs_f64(); ++ h.app.run("render.interactive", json!({"action":"on"})).unwrap(); ++ let original = interactive_recovery_require_success(&mut h, epoch + 0.201, epoch + 0.3); ++ let original_visual = interactive::inspect(&h.app)["visual_revision"].as_u64().unwrap(); ++ let path = h.dir.join("interactive-accepted-to-pending-original.hdr"); ++ let bytes = original_hdr_bytes(192, true); ++ std::fs::write(&path, &bytes).unwrap(); ++ h.app.render_workspace.view.cpu.environment = cpu::Environment::Hdr; ++ h.app.render_workspace.view.cpu.hdr = hdr::Input::FilePending { path: path.to_string_lossy().into_owned() }; ++ // Even a real valid file is not admitted until inspected. An already ++ // displayed CPU frame must disappear, not masquerade as the new HDR intent. ++ let (mut output, painted) = interactive_acceptance_frame(&mut h, epoch + 0.4, true, true); ++ assert!(!painted); ++ output.textures_delta.clear(); ++ let error = interactive_recovery_require_error(&mut h, epoch + 0.5); ++ assert_eq!(error, h.app.tr("render.hdr_inspect_required")); ++ assert!(interactive::inspect(&h.app)["visual_revision"].as_u64().unwrap() > original_visual); ++ assert!(h.app.run("render.interactive", json!({"action":"resume"})).is_err()); ++ assert_eq!(interactive_recovery_require_error(&mut h, epoch + 1.0), error); ++ // A correcting inspection must respect explicit user pause. Resume then ++ // captures the actual checked HDR through Snapshot/CPU, rather than falling ++ // back to the old frame or manufacturing a successful callback. ++ h.app.run("render.interactive", json!({"action":"pause"})).unwrap(); ++ hdr::inspect(&mut h.app, hdr::Target::Cpu, path.to_string_lossy().into_owned()).unwrap(); ++ let checked = interactive_request(&h.app).unwrap(); ++ { ++ use sha2::{Digest, Sha256}; ++ assert_eq!(checked["environment"]["expected_sha256"], format!("{:x}", Sha256::digest(&bytes))); ++ } ++ interactive_clear_acceptance_frame(&mut h, epoch + 1.1, false); ++ interactive_clear_acceptance_frame(&mut h, epoch + 1.5, true); ++ assert_eq!(interactive::inspect(&h.app)["phase"], "Paused"); ++ assert_eq!(interactive::inspect(&h.app)["paused"], true); ++ assert!(interactive::inspect(&h.app)["error"].is_null()); ++ assert!(!h.app.render_workspace.interactive.pending()); ++ assert!(interactive::test_current(&h.app).unwrap().is_none()); ++ assert!(interactive::test_cache(&h.app).is_none(), "the earlier accepted image cannot return after correcting HDR"); ++ h.app.run("render.interactive", json!({"action":"resume"})).unwrap(); ++ let recovered = interactive_recovery_require_success(&mut h, epoch + 1.701, epoch + 1.8); ++ assert_ne!(recovered, original); ++ let job = interactive::test_current(&h.app).unwrap().unwrap(); ++ assert_eq!(job.id(), recovered); ++ let frame = job.frame().unwrap().unwrap(); ++ let (cached, samples, complete, texture) = interactive::test_cache(&h.app).unwrap(); ++ assert_eq!(cached.png_sha256, frame.info.png_sha256); ++ assert_eq!((cached.job, samples, complete), (recovered, 16, true)); ++ assert_eq!(interactive_request(&h.app).unwrap(), checked); ++ h.app.run("render.interactive", json!({"action":"pause"})).unwrap(); ++ let (mut output, painted) = interactive_acceptance_frame(&mut h, epoch + 2.0, true, true); ++ assert!(painted, "Pause retains the newly recovered actual frame"); ++ assert_eq!(interactive::inspect(&h.app)["phase"], "Paused"); ++ assert_eq!(interactive::inspect(&h.app)["paused"], true); ++ let (paused, paused_samples, paused_complete, paused_texture) = interactive::test_cache(&h.app).unwrap(); ++ assert_eq!((paused.job, paused.png_sha256, paused_samples, paused_complete, paused_texture), (recovered, frame.info.png_sha256.clone(), 16, true, texture)); ++ assert!(!output.textures_delta.set.contains_key(&texture), "Pause reuses the recovered texture"); ++ output.textures_delta.clear(); ++ assert!(!h.app.render_workspace.interactive.pending()); ++ assert_eq!(job.frame().unwrap().unwrap().png(), frame.png()); ++ interactive_assert_final_export_isolation(&mut h, &job); ++ assert!(Arc::ptr_eq(&document, &h.app.session.doc)); ++ assert_eq!((h.app.session.revision, h.app.session.undo.len(), h.app.session.redo.len(), h.app.session.is_dirty()), history); ++ h.app.run("render.interactive", json!({"action":"off"})).unwrap(); ++} diff --git a/proposals/render/2026-10-30/midpass-film-preparation/README.md b/proposals/render/2026-10-30/midpass-film-preparation/README.md new file mode 100644 index 000000000..af00ddf93 --- /dev/null +++ b/proposals/render/2026-10-30/midpass-film-preparation/README.md @@ -0,0 +1,9 @@ +# Genuine midpass progress: private foundation + +Selected direction: Option A from options.md, a bounded reduced snapshot of the actual accumulating final film. Option B is deferred. Neither host streaming nor UI integration is implemented. + +A1 adds only separate read-only partial-film access and five original tests in the existing film test file. Actual source state yields counts s+(index=1 and preview dimensions equal request; general render_workspace.rs1325 also requires request-sized frames and labels uniform SPP. Both need explicit partial/reduced provenance, not weakened dimension checks. +- Interactive Snapshot::run engine/render_interactive.rs228 already passes captured scene/request/options/environment to a distinct job; render/job/interactive.rs12 fits its request to1024. A final Workstation request can still be16384 on an edge and67,108,864 pixels. A preview envelope must not overwrite that final request/FrameInfo/export. + +## Common invariants and proposed policy boundary + +Keep PrimaryFilm.pixel strict for legacy complete-pass/final consumers. Add a separate proposed partial snapshot view; do not change old tests' partial-pass refusal. Existing default whole-pass checkpoint behavior and its exact PNG/work/sequence tests stay unchanged. An internal ephemeral presentation policy selecting the new behavior must be explicitly routed by Engineer through host construction/submission; there is no such policy API today. Do not infer it from JobId or add a saved/public request flag casually. If the behavior is intended for manual progressive jobs too, review that contract separately instead of silently changing the legacy observer. + +A snapshot is captured only immediately after a successfully committed pixel with pending.is_none(). Keep the existing self.pixel, film.samples/next_pixel and every sampler ordinal unchanged. Resolving/encoding pauses integration over an immutable captured frontier; resume the SAME next pixel, never replay completed updates or discard a pending ray. At the full-pass boundary the existing cursor-N/film-next0 transition is special and remains distinct from a partial prefix. + +For P final pixels, s completed passes and prefix k (0<=k0. +No new final-film sample counter is needed. A fresh descriptor records s,k,P and source dimensions, allowing counts for every source pixel. n=0 is UNSAMPLED, not a zero-radiance hit, opaque black, or a measured camera miss. n>0,c=0 is a real miss and retains the original display-sRGB backplate. c/n remains physical coverage; tone/exposure/composite occur once exactly as composite_spatial for sampled data. + +New publications need a monotonic sequence independent of SPP, job+visual revision/generation, separate preview dimensions, captured frontier and sampling/reduction provenance. UI must show nonuniform counts/range/coverage honestly. A reduced snapshot cannot masquerade as final dimensions or a uniform1SPP frame. No export/final ownership transfer, old-generation adoption or reuse of a stale payload under a new sequence. + +## Option A — bounded reduced whole-PNG snapshot of a partial final film + +Smallest change to delivery: retain immutable independently decodable PNG checkpoints, but read a partial film into a bounded display grid, max edge1024 (existing Interactive ceiling), preserving final request and full film. + +Use a deterministic PROPOSED representative-source mapping for each preview pixel (u,v): +x=floor(u*W/w), y=floor(v*H/h), source_index=y*W+x. +This is nearest representative sampling of committed final pixels, not a box average, new camera render, or full-resolution convergence statement. Top-left representatives allow the first committed source pixel to produce actual visible content. The mapping is fixed by captured dimensions and never affects trace pixel ids/seeds. A centered mapping is possible but delays first-row visibility; choose one explicitly before implementation. + +Resolve at most M=w*h actual source pixels, not all P pixels. Each representative carries its actual n,c; n is derived from s,k and mapping, c requires a bounded u16 sidecar if exposed per preview pixel. The sidecar allocation is billed outside the fixed1024-byte FrameInfo metadata allowance. Unsampled cells use an explicit mask/transparent provisional presentation plus an unknown canvas treatment, never a fake sample/backplate claim. +An unsampled visual placeholder is not the request's transparent_background setting and cannot become exportable output. + +At a safe committed frontier with changed represented data and an available publication credit, pause and resolve O(M), encode at preview dimensions, hash incrementally, publish, then resume the exact final-film cursor. Reuse a bounded prefix of existing admitted RGBA scratch if safe; otherwise bill separate4M scratch. Do not allocate a second full final film or change camera rays. Coalesce dirty frontiers while publication is unavailable; do not encode an image the host cannot retain. + +Pros: independent snapshots tolerate skipped frames; uses existing PNG decoder/upload path after explicit metadata changes; no tile acknowledgement/mosaic state. Keeps final accumulation byte order intact. +Costs/limits: O(M) resolve, PNG encode, hash, decode and full preview upload for each new snapshot; representative aliasing; no fresh picture until geometry initialization and at least a useful committed pixel exist. It cannot guarantee a wall-time frame rate for a single expensive in-flight ray. Real cadence must be measured; no sleep/fake timer can establish it. + +Required paths: +film_primary.rs: new read-only partial accessor/frontier without relaxing pixel(); +raytrace/progressive.rs: snapshot/resume frontier; +raytrace/image.rs: safe trigger, bounded resolve/encoder dimensions and cursor preservation, same work counter; +job/host.rs + job/mod.rs: partial descriptor, sequence and resource-credit admission/publication; +job/encoding.rs: existing dimensional encoder reused, not relabelled; +engine/render_interactive.rs and its actual submission route: proposed ephemeral policy, captured revision; +UI render_workspace_interactive.rs and render_workspace.rs: explicit source/preview dimensions, partial sample/unknown state; normal final decoder/export unchanged. +Tests remain in film_tests.rs, primary_aa_tests.rs, host_tests.rs and existing engine/UI test files under their current owners. + +## Option B — bounded reduced preview grid, dirty tile patches from committed samples + +Retain the SAME final-film row-major loop. After each committed final pixel sample, update one cell in a separate bounded preview grid (max edge1024); cells correspond to integer source-pixel rectangles. This is preview-only state, not another renderer and not tile-first tracing. + +Each display cell stores sum RGB, aggregate committed camera-attempt count N and aggregate primary-covered count C over its source footprint. L=sum/N is a weighted mean of committed attempts; C/N is its coverage. N=0 remains explicitly UNSAMPLED. N is not SPP: source pixels in a partially advanced footprint can have s or s+1 samples. The snapshot also records frontier s,k and footprint, so that source per-pixel counts remain derivable. Partial-footprint/weighted-preview provenance must be visible; no claim that it equals an equal-spatial-weight final downsample during an incomplete pass. + +Update staging must be atomic with film.add: validate both new states and required work before either mutation, then commit without an intervening fallible/cancel boundary. Never commit film, fail preview work, and then replay the sample to repair the side grid. Each sum uses checked bounds; count type must cover the existing profile's total camera-sample cap, not u16 SPP. + +Publish a bounded dirty rectangle/tile (e.g. a proposed32x32 cell cap) with exact rect, sequence/base, source frontier, actual N/C sidecar, encoding and job/revision identity. Copy/resolve O(T) committed display cells, not P; UI uploads that subrectangle to a bounded texture. Final film/request/PNG stay untouched. A raw tile is not a PNG or a final FrameInfo; use a distinct typed provisional payload, not a forged png_sha256. + +Delivery MUST handle a slow UI: a delta may apply only to the exact acknowledged base/generation. Keep bounded dirty state and coalesce cells; require an explicit applied-sequence acknowledgement or a bounded full-grid resync if a delta was missed. One latest patch slot without ack/resync loses updates and is invalid. These APIs do not currently exist. No unbounded patch queue, history of tile images, or full-frame clone per patch. + +Pros: new content can update a cell from each actual final-pixel commit; small resolve/upload latency and no repeated full PNG. Better fit when the first pass itself is slow. +Costs: additional preview-grid sums/counts and charged work per commit, stricter dual-commit invariants, separate payload/UI texture-update path, acknowledgement/resync protocol and dirty-cell bookkeeping. This is broader than Option A; keep it confined to the same film/host/UI adapter rather than introduce a rendering framework. + +Dependencies: all common paths above; replace PNG preview-only delivery with a typed raw-patch path in host/WorkPoll and UI, leave encoding.rs's final PNG logic untouched. film_primary.rs/add and image.rs/finish_sample require staged commit review; progressive.rs owns bounded grid/dirty state. No BVH, BSDF, sampler, kernel or saved-format change. + +## Cost at the actual large envelopes + +Current limits are numerical admission bounds, not qualified performance results: +Workstation max edge16384 / max pixels67,108,864; max job12GiB. Primary Pixel layout is target-dependent, commonly32bytes (verify target), so this film alone is about2GiB; final RGBA256MiB. +Current encoded bound image.rs229 is8P+65,536: at67,108,864 it is512MiB+64KiB for EACH full-size PNG capacity, before metadata. A complete snapshot also resolves67million pixels and scans/encodes/hashes proportional to that size. Repeating this midpass is not a bounded low-latency display solution. + +Both options bound DISPLAY pixels M<=1,048,576 independently. Option A encoded capacity <=8MiB+64KiB plus up to2MiB covered-count sidecar and4MiB working RGBA (or already paid scratch). A16384x4096 final would display at1024x256, not secretly render/export at that resolution. No O(P) downsample scan is hidden: A reads representative indices only. +Option B's grid with3f64 sums+2u64 counts is nominal40M bytes plus checked actual layout/dirty state, at most about40MiB for M=1,048,576. A32x32 patch is at most1024 display cells; include RGBA, N/C arrays, headers and staging in the same admission. These are estimates to verify in source/target, not benchmarked gains. + +## Retained copies and backpressure: necessary for BOTH options + +Proposed fixed K=2 independently retainable preview allocations plus ONE bounded in-flight encode/copy slot, all paid by the existing job/host lease and existing profile ceiling. K is a review choice, not a new public budget. Cloned Arcs of one payload do not count as another PNG allocation. +Admission must use this peak and actual allocated capacities, not preview_count times all future frames. Do not lower admission thresholds or pretend immutable external payloads disappeared. +Reservation::split alone cannot recycle publication capacity: last-drop releases globally, while the task's original reservation remains depleted. A small per-job lease-credit return/merge seam on the SAME Budget identity is needed; it is not currently implemented. No mutable buffer is reused while an external Arc exists. On terminal cleanup free credits release, externally held payloads retain their actual lease until last-drop; final PNG owns its independent unchanged lease. +If K payloads remain externally held, do not resolve/encode/copy another checkpoint. Continue tracing, coalesce dirty progress and publish the newest actual data when a credit returns. Never block final completion waiting for an uncooperative consumer. Show the last payload as older data with its original provenance, not as a freshly rendered texture. + +All initialization/read/copy/resolve/encode/hash work and cancellation use the SAME existing cumulative WorkBudget. No new work budget, reset, uncharged scan, off-thread helper renderer or side pool. Extra snapshots have real cost: cannot honestly promise the same historical total used units or unconditional completion at an already exhausted cap. A reviewed deterministic production trigger (independent of worker quantum/seed) and finite presentation-work scheduling/coalescing are required. Backpressure changes presentation work, never sample ordinals. If the requirement were identical historical work consumption, arbitrary additional presentations are impossible unless replacing existing presentation work; raise this explicitly rather than hide cost. +Legacy mode keeps its old work/quantum/power-of-two tests unchanged. New-policy tests must separate invariant trace results from honestly charged optional presentation work and require LimitExceeded before partial mutation/publication. No invented wall-clock cadence acceptance; later native measurements include resolve/encode/hash/decode/upload. + +## Original oracles to propose, not execute + +1. Four-pixel raw-film frontier: after first two commits, s0/k2 -> n[1,1,0,0], c[1,0,0,0]; pixel0 radiance[2,0,0], pixel1 real miss, pixels2/3 explicitly UNSAMPLED. After one pass plus two commits, n[2,2,1,1]. With p0 first[2,0,0], second[4,0,0], its mean is[3,0,0], covered2. With p1 firstmiss, second[0,2,0], its premultiplied mean is[0,1,0], covered1/2. No division by zero or black-unobserved fiction. +2. Snapshot/resume at k=1 and k=P-1 and full-pass sentinel: exact next (pixel,ordinal) sequence equals no-partial-preview control, including non-power-of-two target5, seeds0/123, Area1/4/16/64 and HDR/reflection existing fixtures. Compare final PNG bytes and film sum f64 bits, not just visual tolerance. No call-size/timing key enters variates. +3. Existing camera_film_keeps_linear_sums_coverage_and_uniform_absolute_passes still rejects legacy pixel() during a partial pass. New accessor accepts exactly the observed frontier, not arbitrary/trusted input counters. +4. Sampling/coverage display: N>0,C0 preserves exact backplate regardless exposure; unknownN0 is separately flagged. Mixed coverage computes physical C/N and tones once, never averages encoded RGB. A representative mapping must match its chosen source index. B aggregate box of4 committed attempts [2,0,0],miss,[0,2,0],miss yields sum[2,2,0],N4,C2,premultiplied mean[.5,.5,0],coverage.5. +5. K=2 held external payloads: third publication performs zero new buffer allocation/encode, no new sequence; tracing continues. Release one -> next published payload carries the LATEST real frontier, not queued old progress. Cancel/replace during resolve/hash/publication cannot attach a late preview; old external immutable payload stays billed. Final completes while credits are full, independent final-frame lease. Check actual capacities/pool return and last-drop behavior. +6. B only: apply exact base then patch yields known mosaic; missing/duplicate/out-of-order/generation-mismatched patch refuses or performs bounded explicit resync. N/C and dirty-cell versions cannot be silently lost by replacing a latest slot. +7. Resource/cadence acceptance: a high-size request keeps final16384x4096 while preview<=1024edge; instrument bounded read/copy/encoder/upload counts to show no hidden P scan in A/B previews. A deterministic safe-pixel barrier can show a new payload before pass completion without sleeps; this proves midpass publication, not FPS. Later native timed evidence is separate and must include actual preparation and worst pixel stalls. + +## Decision requested from Engineer, not user permission + +Select A or B, confirm transient routing/default compatibility, preview-side count/provenance fields and the K-credit lifecycle, and define the new-mode presentation work/trigger contract. Then assign disjoint film/host/UI ownership with existing Area/LED/glass preserved. No implementation is authorized by this report. No timer, deadline, app control or automatic successor was created. diff --git a/proposals/render/2026-10-30/midpass-film-preparation/proposal.patch b/proposals/render/2026-10-30/midpass-film-preparation/proposal.patch new file mode 100644 index 000000000..1447f2895 --- /dev/null +++ b/proposals/render/2026-10-30/midpass-film-preparation/proposal.patch @@ -0,0 +1,246 @@ +--- a/crates/render/src/film_primary.rs ++++ b/crates/render/src/film_primary.rs +@@ -10,6 +10,23 @@ + struct Pixel { + sum: [f64; 3], + covered: u32, ++} ++ ++/// Observed scanline frontier; metadata only, never a caller-supplied authority. ++/// Every pixel before updated_prefix has one more sample than completed_passes. ++#[derive(Clone, Copy, Debug, PartialEq, Eq)] ++pub(crate) struct PartialFrontier { ++ pub completed_passes: u32, ++ pub updated_prefix: usize, ++ pub pixels: usize, ++} ++ ++/// A partial view never invents a zero sample for a pixel not yet observed. ++/// Sampled linear radiance includes zero contributions from primary misses. ++#[derive(Clone, Copy, Debug, PartialEq)] ++pub(crate) enum PartialPixel { ++ Unknown, ++ Sampled { linear_premultiplied: [f64; 3], covered: u32, count: u32 }, + } + + pub(crate) struct PrimaryFilm { +@@ -121,4 +138,49 @@ + let samples = u16::try_from(self.samples).map_err(|_| limit("primary sample count exceeds resolve representation"))?; + Ok((pixel.sum.map(|sum| sum / f64::from(self.samples)), covered, samples)) + } ++ /// Inspect only the real committed state. This value does not freeze the film ++ /// or authorize a snapshot. A caller resolving several pixels must keep the ++ /// film immutably borrowed at one completed-pixel frontier, and must charge ++ /// reads/copies and check cancellation against its existing job budget. ++ pub(crate) fn partial_frontier(&self) -> Result { ++ if !self.ready() ++ || self.next_pixel >= self.count ++ || self.samples > self.sample_limit ++ || (self.samples == self.sample_limit && self.next_pixel != 0) ++ { ++ return Err(invalid("primary film has no initialized partial frontier")); ++ } ++ Ok(PartialFrontier { completed_passes: self.samples, updated_prefix: self.next_pixel, pixels: self.count }) ++ } ++ ++ /// Bounded allocation-free read, separate from the strict complete-pass pixel(). ++ /// Counts come from this film, never from a supplied frontier or sample count. ++ /// Unknown means count0/covered0; a sampled miss has count>0 and covered0. ++ /// No exposure, tone mapping, background, work lease or publication occurs here. ++ /// The caller owes cancellation checks and work charges for each read/copy; ++ /// this accessor creates no independent budget and never advances an ordinal. ++ pub(crate) fn partial_pixel(&self, index: usize) -> Result { ++ let frontier = self.partial_frontier()?; ++ let pixel = self.pixels.get(index).ok_or_else(|| invalid("primary film partial index out of range"))?; ++ let count = frontier ++ .completed_passes ++ .checked_add(u32::from(index < frontier.updated_prefix)) ++ .filter(|count| *count <= self.sample_limit) ++ .ok_or_else(|| limit("primary partial sample count exceeded"))?; ++ if pixel.covered > count { ++ return Err(invalid("primary partial coverage exceeds its committed count")); ++ } ++ if count == 0 { ++ if pixel.covered != 0 || pixel.sum != [0.0; 3] { ++ return Err(invalid("unobserved primary pixel has accumulated data")); ++ } ++ return Ok(PartialPixel::Unknown); ++ } ++ Ok(PartialPixel::Sampled { ++ linear_premultiplied: pixel.sum.map(|sum| sum / f64::from(count)), ++ covered: pixel.covered, ++ count, ++ }) ++ } ++ + } +--- a/crates/render/src/film_tests.rs ++++ b/crates/render/src/film_tests.rs +@@ -275,3 +275,167 @@ + assert!(film.add(0, 512, [0.0; 3], true, &cancel, &mut || Ok(())).is_err()); + assert_eq!(film.samples(), 512); + } ++ ++ ++#[cfg(feature = "raytrace-cpu")] ++mod partial_camera_passes { ++ use super::primary::{PartialFrontier, PartialPixel, PrimaryFilm}; ++ use super::*; ++ use crate::job::{CpuBudget, CpuProgressiveOptions}; ++ ++ fn uninitialized(samples: u32, seed: u32) -> PrimaryFilm { ++ let options = CpuProgressiveOptions { samples_per_pixel: samples, seed }; ++ let bytes = PrimaryFilm::required_bytes(4, 1, options, CpuBudget::Compact).unwrap(); ++ PrimaryFilm::new(4, 1, options, bytes, &CancelToken::default(), CpuBudget::Compact).unwrap() ++ } ++ ++ fn ready(samples: u32, seed: u32) -> PrimaryFilm { ++ let mut film = uninitialized(samples, seed); ++ while !film.ready() { ++ film.initialize_one(&CancelToken::default(), &mut || Ok(())).unwrap(); ++ } ++ film ++ } ++ ++ fn observe(film: &PrimaryFilm) -> (PartialFrontier, Vec) { ++ (film.partial_frontier().unwrap(), (0..4).map(|index| film.partial_pixel(index).unwrap()).collect()) ++ } ++ ++ fn sampled(mean: [f64; 3], covered: u32, count: u32) -> PartialPixel { ++ PartialPixel::Sampled { linear_premultiplied: mean, covered, count } ++ } ++ ++ #[test] ++ fn partial_frontier_distinguishes_first_prefix_miss_and_unobserved_pixels() { ++ let mut film = ready(2, 7); ++ assert_eq!(observe(&film), ( ++ PartialFrontier { completed_passes: 0, updated_prefix: 0, pixels: 4 }, ++ vec![PartialPixel::Unknown; 4], ++ )); ++ film.add(0, 0, [2.0, 0.0, 0.0], true, &CancelToken::default(), &mut || Ok(())).unwrap(); ++ film.add(1, 0, [0.0; 3], false, &CancelToken::default(), &mut || Ok(())).unwrap(); ++ assert_eq!(observe(&film), ( ++ PartialFrontier { completed_passes: 0, updated_prefix: 2, pixels: 4 }, ++ vec![sampled([2.0, 0.0, 0.0], 1, 1), sampled([0.0; 3], 0, 1), PartialPixel::Unknown, PartialPixel::Unknown], ++ )); ++ assert!(film.pixel(0).is_err(), "legacy whole-pass reader still rejects the partial pass"); ++ assert!(film.pixel(1).is_err(), "a sampled miss does not imply a uniform pass"); ++ } ++ ++ #[test] ++ fn partial_counts_and_means_follow_real_interior_and_full_pass_frontiers() { ++ let mut film = ready(2, 0); ++ let cancel = CancelToken::default(); ++ for (index, value, covered) in [ ++ (0, [2.0, 0.0, 0.0], true), (1, [0.0; 3], false), ++ (2, [0.0, 0.0, 4.0], true), (3, [0.0; 3], false), ++ ] { ++ film.add(index, 0, value, covered, &cancel, &mut || Ok(())).unwrap(); ++ } ++ assert_eq!(film.partial_frontier().unwrap(), PartialFrontier { completed_passes: 1, updated_prefix: 0, pixels: 4 }); ++ assert_eq!(film.partial_pixel(3).unwrap(), sampled([0.0; 3], 0, 1)); ++ assert_eq!(film.pixel(0).unwrap(), ([2.0, 0.0, 0.0], 1, 1)); ++ ++ film.add(0, 1, [4.0, 0.0, 0.0], true, &cancel, &mut || Ok(())).unwrap(); ++ film.add(1, 1, [0.0, 2.0, 0.0], true, &cancel, &mut || Ok(())).unwrap(); ++ assert_eq!(observe(&film), ( ++ PartialFrontier { completed_passes: 1, updated_prefix: 2, pixels: 4 }, ++ vec![sampled([3.0, 0.0, 0.0], 2, 2), sampled([0.0, 1.0, 0.0], 1, 2), ++ sampled([0.0, 0.0, 4.0], 1, 1), sampled([0.0; 3], 0, 1)], ++ )); ++ assert!(film.pixel(0).is_err()); ++ ++ film.add(2, 1, [0.0, 0.0, 8.0], true, &cancel, &mut || Ok(())).unwrap(); ++ assert_eq!(film.partial_frontier().unwrap().updated_prefix, 3); ++ film.add(3, 1, [0.0; 3], false, &cancel, &mut || Ok(())).unwrap(); ++ assert_eq!(observe(&film), ( ++ PartialFrontier { completed_passes: 2, updated_prefix: 0, pixels: 4 }, ++ vec![sampled([3.0, 0.0, 0.0], 2, 2), sampled([0.0, 1.0, 0.0], 1, 2), ++ sampled([0.0, 0.0, 6.0], 2, 2), sampled([0.0; 3], 0, 2)], ++ )); ++ assert_eq!(film.pixel(2).unwrap(), ([0.0, 0.0, 6.0], 2, 2)); ++ assert!(film.add(0, 2, [0.0; 3], false, &cancel, &mut || Ok(())).is_err()); ++ assert_eq!(film.partial_frontier().unwrap().completed_passes, 2); ++ } ++ ++ #[test] ++ fn partial_access_refuses_uninitialized_storage_and_invalid_indices() { ++ let mut film = uninitialized(2, 7); ++ assert!(film.partial_frontier().is_err()); ++ assert!(film.partial_pixel(0).is_err()); ++ film.initialize_one(&CancelToken::default(), &mut || Ok(())).unwrap(); ++ assert!(film.partial_frontier().is_err(), "allocated prefix is not an initialized film"); ++ assert!(film.partial_pixel(0).is_err()); ++ while !film.ready() { ++ film.initialize_one(&CancelToken::default(), &mut || Ok(())).unwrap(); ++ } ++ assert_eq!(film.partial_pixel(0).unwrap(), PartialPixel::Unknown); ++ assert!(film.partial_pixel(4).is_err()); ++ assert!(film.partial_pixel(usize::MAX).is_err()); ++ assert_eq!(film.partial_frontier().unwrap().updated_prefix, 0); ++ } ++ ++ #[test] ++ fn failed_or_cancelled_updates_preserve_the_observed_partial_frontier() { ++ let mut film = ready(2, 7); ++ film.add(0, 0, [2.0, 0.0, 0.0], true, &CancelToken::default(), &mut || Ok(())).unwrap(); ++ let before = observe(&film); ++ for (index, ordinal, value, covered) in [ ++ (0, 0, [0.0; 3], false), (2, 0, [0.0; 3], false), (1, 1, [0.0; 3], false), ++ (1, 0, [f64::NAN; 3], true), (1, 0, [1.0; 3], false), ++ ] { ++ assert!(film.add(index, ordinal, value, covered, &CancelToken::default(), &mut || Ok(())).is_err()); ++ assert_eq!(observe(&film), before); ++ } ++ assert_eq!(film.add(1, 0, [4.0; 3], true, &CancelToken::default(), &mut || Err(limit("existing job exhausted"))).unwrap_err().code, ++ ErrorCode::LimitExceeded); ++ assert_eq!(observe(&film), before); ++ let cancel = CancelToken::default(); ++ let observer = cancel.clone(); ++ assert_eq!(film.add(1, 0, [4.0; 3], true, &cancel, &mut || { ++ observer.cancel(); ++ Ok(()) ++ }).unwrap_err().code, ErrorCode::Cancelled); ++ assert_eq!(observe(&film), before); ++ film.add(1, 0, [4.0; 3], true, &CancelToken::default(), &mut || Ok(())).unwrap(); ++ assert_eq!(film.partial_frontier().unwrap().updated_prefix, 2, "failed updates did not consume the next ordinal"); ++ } ++ ++ #[test] ++ fn reading_partial_pixels_preserves_default_sum_order_bits_and_charge_count() { ++ for seed in [0, 7, u32::MAX] { ++ let mut observed = ready(4, seed); ++ let mut control = ready(4, seed); ++ let mut observed_charges = 0; ++ let mut control_charges = 0; ++ for ordinal in 0..4 { ++ let red = if ordinal == 0 { 1e12 } else { 2.0_f64.powi(-15) }; ++ for index in 0..4 { ++ let value = [red, red * 0.5, 2.0]; ++ observed.add(index, ordinal, value, true, &CancelToken::default(), &mut || { ++ observed_charges += 1; ++ Ok(()) ++ }).unwrap(); ++ // These uncharged O(1) reads model only the accessor. A future ++ // snapshot caller still owes its own per-read/copy work charge. ++ let _ = observe(&observed); ++ control.add(index, ordinal, value, true, &CancelToken::default(), &mut || { ++ control_charges += 1; ++ Ok(()) ++ }).unwrap(); ++ } ++ } ++ assert_eq!((observed_charges, control_charges), (16, 16)); ++ assert_eq!(observed.samples(), 4); ++ for index in 0..4 { ++ let (actual, covered, count) = observed.pixel(index).unwrap(); ++ let (expected, expected_covered, expected_count) = control.pixel(index).unwrap(); ++ assert_eq!(actual.map(f64::to_bits), expected.map(f64::to_bits)); ++ assert_eq!(actual.map(f64::to_bits), [2.5e11_f64, 1.25e11_f64, 2.0_f64].map(f64::to_bits), ++ "ordered additions keep each sub-half-ULP contribution rounded at its original addition"); ++ assert_eq!((covered, count), (expected_covered, expected_count)); ++ assert_eq!(observed.partial_pixel(index).unwrap(), sampled(actual, 4, 4)); ++ } ++ } ++ } ++} diff --git a/proposals/render/2026-10-30/output-envelope-helpers/README.md b/proposals/render/2026-10-30/output-envelope-helpers/README.md new file mode 100644 index 000000000..816b8901e --- /dev/null +++ b/proposals/render/2026-10-30/output-envelope-helpers/README.md @@ -0,0 +1,7 @@ +# Explicit internal output limits: seven-helper preparation + +Source-only reviewed V2, NOT APPLIED/FORMATTED/COMPILED/RUN. Seven existing helpers share explicitly bounded internal RenderLimits policies for presentation, bloom, photographic effects, EXR encoding/decoding, PNG and regrade. Public GPU wrappers retain their current limits and supported-image behavior. The policy is not a host reservation or a CPU capability. No CPU host caller, raw transport, WorkBudget charging, EXR producer metadata or feature enablement is implemented here. + +Thirteen original proposed tests preserve the nine previous declarations. They include independent linear radiance/coverage and bloom-kernel oracles, narrow8193x1 threading, exact-fit and hostile-policy refusal, default bytes and cancellation/validation ordering. The first source review identified changed legacy PNG cancellation precedence before new retained-capacity checks. V2 restores the original immediate cancel check after the original dimension/length checks; the other six candidates and all tests remain byte-identical. Independent delta review found no new source blocker. No image, compiler, Clippy or runtime result is claimed. + +CPU enablement still requires captured raw scene-linear samples, correct acquired peak-buffer leases and cumulative work, coherent per-request output limits, publication/cancellation and real end-to-end tests. Passing a caller-created policy alone never acquires memory. The implementation rejects policies beyond existing Workstation maxima without raising those maxima. Do not mix this preparatory patch with an unrelated host overlay. diff --git a/proposals/render/2026-10-30/output-envelope-helpers/proposal.patch b/proposals/render/2026-10-30/output-envelope-helpers/proposal.patch new file mode 100644 index 000000000..f64dd29c2 --- /dev/null +++ b/proposals/render/2026-10-30/output-envelope-helpers/proposal.patch @@ -0,0 +1,709 @@ +--- a/crates/render/src/job/presentation.rs ++++ b/crates/render/src/job/presentation.rs +@@ -45,6 +45,11 @@ + pub fn display(self, width: u32, height: u32) -> Result { + self.validate()?; + super::linear_exr::encoded_limit(width, height)?; ++ self.display_with_limits(width, height, super::GPU_PATH_LIMITS) ++ } ++ pub(crate) fn display_with_limits(self, width: u32, height: u32, limits: crate::RenderLimits) -> Result { ++ self.validate()?; ++ super::linear_exr::output_pixels_with_limits(width, height, limits)?; + Ok(Display { + width, + height, +@@ -97,6 +102,19 @@ + return Err(JobError::new(ErrorCode::InvalidRequest, "bloom/display length mismatch")); + } + super::linear_exr::encoded_limit(self.width, self.height)?; ++ self.encode_bloom_at_with_limits(input, output, cancel, offset, bloom, super::GPU_PATH_LIMITS) ++ } ++ pub(crate) fn encode_bloom_at_with_limits( ++ self, input: &[[f32; 4]], output: &mut [u8], cancel: &CancelToken, ++ offset: usize, bloom: Option<&[[f32; 3]]>, limits: crate::RenderLimits, ++ ) -> Result<()> { ++ if bloom.is_some_and(|pixels| pixels.len() != input.len()) { ++ return Err(JobError::new(ErrorCode::InvalidRequest, "bloom/display length mismatch")); ++ } ++ let count = super::linear_exr::output_pixels_with_limits(self.width, self.height, limits)?; ++ super::linear_exr::checked_output_bytes(count, 16, 0, limits)?; ++ super::linear_exr::checked_output_bytes(count, 4, 0, limits)?; ++ if bloom.is_some() { super::linear_exr::checked_output_bytes(count, 12, 0, limits)?; } + self.finishing.validate()?; + if let Some(backdrop) = self.backdrop { + backdrop.validate()?; +@@ -143,3 +161,49 @@ + Ok(()) + } + } ++ ++#[cfg(test)] ++mod tests { ++ use super::*; ++ ++ #[test] ++ fn raw_radiance_ev_and_coverage_have_independent_analytic_display_oracles() { ++ let raw = [[4.0, 1.0, 0.25, 1.0], [2.0, 0.5, 0.125, 0.5]]; ++ let before = raw.map(|pixel| pixel.map(f32::to_bits)); ++ let display = Presentation { exposure_ev: 1.0, background: [0; 3], ..Default::default() }.display(2, 1).unwrap(); ++ let mut output = [0; 8]; ++ display.encode(&raw, &mut output, &CancelToken::default()).unwrap(); ++ let opaque = [8.0 / 9.0, 2.0 / 3.0, 1.0 / 3.0].map(solidcraft_geom::srgb::encode8); ++ let covered = [4.0 / 9.0, 1.0 / 3.0, 1.0 / 6.0].map(solidcraft_geom::srgb::encode8); ++ assert_eq!(&output[..4], &[opaque[0], opaque[1], opaque[2], 255]); ++ assert_eq!(&output[4..], &[covered[0], covered[1], covered[2], 255]); ++ assert_eq!(raw.map(|pixel| pixel.map(f32::to_bits)), before); ++ } ++ ++ #[test] ++ fn wide_display_requires_explicit_policy_on_both_calls_without_allocating_a_frame() { ++ let wide = super::super::CpuBudget::Workstation.image_limits(false); ++ assert!(Presentation::default().display(8193, 1).is_err()); ++ let display = Presentation::default().display_with_limits(8193, 1, wide).unwrap(); ++ let mut output = [0; 4]; ++ let raw = [[1.0, 0.0, 0.0, 1.0]]; ++ assert!(display.encode_at(&raw, &mut output, &CancelToken::default(), 8192).is_err()); ++ display.encode_bloom_at_with_limits(&raw, &mut output, &CancelToken::default(), 8192, None, wide).unwrap(); ++ assert_eq!(output, [solidcraft_geom::srgb::encode8(0.5), 0, 0, 255]); ++ assert!(display.encode_bloom_at_with_limits(&raw, &mut output, &CancelToken::default(), 8193, None, wide).is_err()); ++ } ++ ++ #[test] ++ fn explicit_gpu_display_matches_legacy_and_preserves_validation_before_cancel() { ++ let display = Presentation { exposure_ev: -1.0, ..Default::default() }.display(3, 2).unwrap(); ++ let input = [[0.125, 2.0, 0.5, 1.0]; 6]; ++ let mut legacy = [0; 24]; ++ let mut explicit = [0; 24]; ++ display.encode(&input, &mut legacy, &CancelToken::default()).unwrap(); ++ display.encode_bloom_at_with_limits(&input, &mut explicit, &CancelToken::default(), 0, None, super::super::GPU_PATH_LIMITS).unwrap(); ++ assert_eq!(explicit, legacy); ++ let cancel = CancelToken::default(); cancel.cancel(); ++ assert_eq!(display.encode(&[], &mut explicit, &cancel).unwrap_err().code, ErrorCode::InvalidRequest); ++ assert_eq!(display.encode(&input, &mut explicit, &cancel).unwrap_err().code, ErrorCode::Cancelled); ++ } ++} +--- a/crates/render/src/job/bloom.rs ++++ b/crates/render/src/job/bloom.rs +@@ -39,6 +39,13 @@ + return Ok(0); + } + u64::from(width).checked_mul(u64::from(height)).and_then(|n| n.checked_mul(24)).ok_or_else(|| invalid("bloom scratch overflow")) ++ } ++ pub(crate) fn scratch_bytes_with_limits(self, width: u32, height: u32, limits: crate::RenderLimits) -> Result { ++ self.validate()?; ++ let count = super::linear_exr::output_pixels_with_limits(width, height, limits)?; ++ if !self.active() { return Ok(0); } ++ super::linear_exr::checked_output_bytes(count, 12, 0, limits)?; ++ super::linear_exr::checked_stage_bytes(count, 24, 0, limits) + } + } + fn invalid(message: &str) -> JobError { +@@ -64,21 +71,30 @@ + } + impl BloomTask { + pub fn new(width: u32, height: u32, pixels: Vec<[f32; 4]>, options: Bloom, cancel: CancelToken) -> Result { ++ Self::new_with_limits(width, height, pixels, options, cancel, GPU_PATH_LIMITS) ++ } ++ pub(crate) fn new_with_limits(width: u32, height: u32, pixels: Vec<[f32; 4]>, options: Bloom, cancel: CancelToken, limits: crate::RenderLimits) -> Result { + options.validate()?; + cancel.check()?; + let count = u64::from(width).checked_mul(u64::from(height)).ok_or_else(|| invalid("bloom dimensions overflow"))?; + if width == 0 + || height == 0 +- || u64::from(width) > GPU_PATH_LIMITS.max_dimension +- || u64::from(height) > GPU_PATH_LIMITS.max_dimension +- || count > GPU_PATH_LIMITS.max_pixels ++ || super::linear_exr::output_pixels_with_limits(width, height, limits).is_err() + || usize::try_from(count).ok() != Some(pixels.len()) + || !options.active() + { + return Err(invalid("bloom requires an admitted nonempty image and positive strength")); + } ++ options.scratch_bytes_with_limits(width, height, limits)?; ++ let retained = super::linear_exr::checked_output_bytes(pixels.capacity() as u64, 16, 0, limits)? as u64; ++ super::linear_exr::checked_stage_bytes(count, 24, retained, limits)?; + let horizontal = allocate(pixels.len())?; ++ let horizontal_bytes = super::linear_exr::checked_output_bytes(horizontal.capacity() as u64, 12, 0, limits)? as u64; ++ let retained = retained.checked_add(horizontal_bytes).ok_or_else(|| invalid("bloom retained byte overflow"))?; ++ super::linear_exr::checked_stage_bytes(count, 12, retained, limits)?; + let vertical = allocate(pixels.len())?; ++ super::linear_exr::checked_output_bytes(vertical.capacity() as u64, 12, 0, limits)?; ++ super::linear_exr::checked_stage_bytes(vertical.capacity() as u64, 12, retained, limits)?; + Ok(Self { pixels, horizontal, vertical, width: width as usize, height: height as usize, options, cancel, phase: 0, line: 0 }) + } + pub fn total_lines(&self) -> u64 { +@@ -247,4 +263,36 @@ + assert!(task.step(1).is_err()); + assert!(task.finish().is_err()); + } +-} ++ ++ #[test] ++ fn explicit_bloom_preserves_independent_three_box_kernel_and_quantum() { ++ let mut pixels = vec![[0.0, 0.0, 0.0, 1.0]; 121]; pixels[60][0] = 1.0; ++ let options = Bloom { strength: 1.0, threshold: 0.0, radius: 1 }; ++ let mut work = BloomTask::new_with_limits(11, 11, pixels.clone(), options, CancelToken::default(), GPU_PATH_LIMITS).unwrap(); ++ while !work.step(1).unwrap() {} ++ let (retained, glow) = work.finish().unwrap(); ++ assert_eq!(retained, pixels); ++ let kernel = [1.0, 3.0, 6.0, 7.0, 6.0, 3.0, 1.0]; ++ for y in 0..11 { for x in 0..11 { ++ let expected = if (2..=8).contains(&x) && (2..=8).contains(&y) { kernel[x-2] * kernel[y-2] / 729.0 } else { 0.0 }; ++ assert!((f64::from(glow[y*11+x][0]) - expected).abs() < 2e-7); ++ assert_eq!(&glow[y*11+x][1..], &[0.0, 0.0]); ++ } } ++ assert_eq!(glow, run(pixels, 11, 11, 1, 32)); ++ } ++ ++ #[test] ++ fn wide_bloom_is_explicit_and_legacy_inactive_and_cancel_order_stay_intact() { ++ let wide = super::super::CpuBudget::Workstation.image_limits(false); ++ let options = Bloom { strength: 1.0, ..Default::default() }; ++ assert!(BloomTask::new(8193, 1, vec![], options, CancelToken::default()).is_err()); ++ let cancel = CancelToken::default(); ++ let mut task = BloomTask::new_with_limits(8193, 1, vec![[0.0, 0.0, 0.0, 1.0]; 8193], options, cancel.clone(), wide).unwrap(); ++ cancel.cancel(); ++ assert_eq!(task.step(1).unwrap_err().code, ErrorCode::Cancelled); ++ assert_eq!(Bloom::default().scratch_bytes(0, u32::MAX).unwrap(), 0); ++ assert_eq!(options.scratch_bytes(8193, 1).unwrap(), 8193 * 24, "legacy estimate remains arithmetic-only"); ++ assert_eq!(BloomTask::new(0, 1, vec![], options, cancel.clone()).err().unwrap().code, ErrorCode::Cancelled); ++ assert_eq!(BloomTask::new(0, 1, vec![], Bloom { strength: f64::NAN, ..options }, cancel).err().unwrap().code, ErrorCode::InvalidRequest); ++ } ++} +--- a/crates/render/src/job/photographic.rs ++++ b/crates/render/src/job/photographic.rs +@@ -98,6 +98,12 @@ + } + count.checked_mul(8).and_then(|n| n.checked_add(16_384)).ok_or_else(|| invalid("photographic scratch size overflow")) + } ++ pub(crate) fn scratch_bytes_with_limits(self, width: u32, height: u32, limits: crate::RenderLimits) -> Result { ++ self.validate()?; ++ let count = super::linear_exr::output_pixels_with_limits(width, height, limits)?; ++ if !self.active() { return Ok(0); } ++ super::linear_exr::checked_stage_bytes(count, 8, 16_384, limits) ++ } + } + #[derive(Clone, Copy, Debug, Default)] + struct Highlight { +@@ -114,6 +120,22 @@ + impl PhotographicTask { + pub fn new(width: u32, height: u32, source: Vec, linear: Vec<[f32; 4]>, options: Photographic, cancel: CancelToken) -> Result { + options.scratch_bytes(width, height)?; ++ Self::create(width, height, source, linear, options, cancel, GPU_PATH_LIMITS) ++ } ++ pub(crate) fn new_with_limits(width: u32, height: u32, source: Vec, linear: Vec<[f32; 4]>, options: Photographic, cancel: CancelToken, limits: crate::RenderLimits) -> Result { ++ options.scratch_bytes_with_limits(width, height, limits)?; ++ cancel.check()?; ++ let count = super::linear_exr::output_pixels_with_limits(width, height, limits)?; ++ if usize::try_from(count).ok() != Some(linear.len()) || linear.len().checked_mul(4) != Some(source.len()) || !options.active() { ++ return Err(invalid("photographic stage requires an admitted opaque image, matching source pixels and an active effect")); ++ } ++ let raw_bytes = super::linear_exr::checked_output_bytes(linear.capacity() as u64, 16, 0, limits)? as u64; ++ let source_bytes = super::linear_exr::checked_output_bytes(source.capacity() as u64, 1, 0, limits)? as u64; ++ let retained = raw_bytes.checked_add(source_bytes).and_then(|n| n.checked_add(16_384)).ok_or_else(|| invalid("photographic retained byte overflow"))?; ++ super::linear_exr::checked_stage_bytes(count, 4, retained, limits)?; ++ Self::create(width, height, source, linear, options, cancel, limits) ++ } ++ fn create(width: u32, height: u32, source: Vec, linear: Vec<[f32; 4]>, options: Photographic, cancel: CancelToken, limits: crate::RenderLimits) -> Result { + if std::mem::size_of::() > 16_384 { + return Err(invalid("photographic metadata exceeds its admitted allowance")); + } +@@ -122,7 +144,7 @@ + if state.capacity() != 1 { + return Err(invalid("photographic state exceeds bounded capacity")); + } +- state.push(PhotographicState::new(width, height, source, linear, options, cancel)?); ++ state.push(PhotographicState::new(width, height, source, linear, options, cancel, limits)?); + Ok(Self { state }) + } + pub fn step(&mut self, units: usize) -> Result { +@@ -153,21 +175,23 @@ + ready: bool, + } + impl PhotographicState { +- pub fn new(width: u32, height: u32, source: Vec, linear: Vec<[f32; 4]>, options: Photographic, cancel: CancelToken) -> Result { ++ pub fn new(width: u32, height: u32, source: Vec, linear: Vec<[f32; 4]>, options: Photographic, cancel: CancelToken, limits: crate::RenderLimits) -> Result { + options.validate()?; + cancel.check()?; + let count = u64::from(width) * u64::from(height); + if width == 0 + || height == 0 +- || u64::from(width) > GPU_PATH_LIMITS.max_dimension +- || u64::from(height) > GPU_PATH_LIMITS.max_dimension +- || count > GPU_PATH_LIMITS.max_pixels ++ || super::linear_exr::output_pixels_with_limits(width, height, limits).is_err() + || usize::try_from(count).ok() != Some(linear.len()) + || linear.len().checked_mul(4) != Some(source.len()) + || !options.active() + { + return Err(invalid("photographic stage requires an admitted opaque image, matching source pixels and an active effect")); + } ++ let raw_bytes = super::linear_exr::checked_output_bytes(linear.capacity() as u64, 16, 0, limits)? as u64; ++ let source_bytes = super::linear_exr::checked_output_bytes(source.capacity() as u64, 1, 0, limits)? as u64; ++ let retained = raw_bytes.checked_add(source_bytes).and_then(|n| n.checked_add(16_384)).ok_or_else(|| invalid("photographic retained byte overflow"))?; ++ super::linear_exr::checked_stage_bytes(count, 4, retained, limits)?; + let mut output = Vec::new(); + output.try_reserve_exact(source.len()).map_err(|_| JobError::new(ErrorCode::AllocationFailed, "photographic output allocation failed"))?; + if output.capacity() != source.len() { +@@ -449,4 +473,35 @@ + assert!(task.step(1).is_err()); + assert!(serde_json::from_str::(r#"{"physical_lens":true}"#).is_err()); + } +-} ++ ++ #[test] ++ fn explicit_wide_photographic_keeps_constants_and_legacy_refusal() { ++ let wide = super::super::CpuBudget::Workstation.image_limits(false); ++ let options = Photographic { radial_distortion: 0.1, chromatic_pixels: 2.0, soft_focus: 0.3, sharpening: 0.2, ..Default::default() }; ++ assert!(PhotographicTask::new(8193, 1, vec![], vec![], options, CancelToken::default()).is_err()); ++ let rgba = [128, 128, 128, 255].repeat(8193); ++ let mut task = PhotographicTask::new_with_limits(8193, 1, rgba.clone(), vec![[0.25, 0.25, 0.25, 1.0]; 8193], options, CancelToken::default(), wide).unwrap(); ++ while !task.step(256).unwrap() {} ++ assert_eq!(task.finish().unwrap(), rgba); ++ let cancel = CancelToken::default(); cancel.cancel(); ++ assert_eq!(Photographic::default().scratch_bytes(0, u32::MAX).unwrap(), 0); ++ assert_eq!(PhotographicTask::new(0, 1, vec![], vec![], options, cancel.clone()).err().unwrap().code, ErrorCode::InvalidRequest); ++ assert_eq!(PhotographicTask::new(0, 1, vec![], vec![], Photographic::default(), cancel).err().unwrap().code, ErrorCode::Cancelled); ++ } ++ ++ #[test] ++ fn explicit_gpu_photographic_matches_legacy_and_cancel_never_finishes() { ++ let options = Photographic { grain: 0.03, seed: 37, ..Default::default() }; ++ let rgba = [64, 128, 192, 255].repeat(6); ++ let linear = vec![[0.1, 0.5, 2.0, 1.0]; 6]; ++ let mut legacy = PhotographicTask::new(3, 2, rgba.clone(), linear.clone(), options, CancelToken::default()).unwrap(); ++ let mut explicit = PhotographicTask::new_with_limits(3, 2, rgba.clone(), linear.clone(), options, CancelToken::default(), GPU_PATH_LIMITS).unwrap(); ++ while !legacy.step(1).unwrap() {} while !explicit.step(16).unwrap() {} ++ assert_eq!(legacy.finish().unwrap(), explicit.finish().unwrap()); ++ let cancel = CancelToken::default(); ++ let mut task = PhotographicTask::new_with_limits(3, 2, rgba, linear, options, cancel.clone(), GPU_PATH_LIMITS).unwrap(); ++ cancel.cancel(); ++ assert_eq!(task.step(1).unwrap_err().code, ErrorCode::Cancelled); ++ assert_eq!(task.finish().err().unwrap().code, ErrorCode::Cancelled); ++ } ++} +--- a/crates/render/src/job/linear_exr.rs ++++ b/crates/render/src/job/linear_exr.rs +@@ -14,7 +14,70 @@ + if w == 0 || h == 0 || w > 8192 || h > 8192 || w * h > 16_777_216 { + return Err(invalid("linear EXR requires 1..8192 sides and at most 16777216 pixels")); + } +- Ok(w * h * 16 + h * 16 + 4096) ++ encoded_limit_with_limits(width, height, super::GPU_PATH_LIMITS) ++} ++ ++/// Internal bounded policy, not proof of a host reservation. Future callers must ++/// retain their request's lease and charge work before advancing output stages. ++pub(crate) fn output_pixels_with_limits(width: u32, height: u32, limits: crate::RenderLimits) -> Result { ++ let maximum = super::CpuBudget::Workstation.image_limits(false); ++ if limits.max_dimension > maximum.max_dimension || limits.max_pixels > maximum.max_pixels ++ || limits.max_scratch_bytes > maximum.max_scratch_bytes ++ { ++ return Err(invalid("output policy exceeds the bounded implementation envelope")); ++ } ++ let (w, h) = (u64::from(width), u64::from(height)); ++ if limits.fit(w, h, None) != Some((w, h)) { ++ return Err(invalid("output dimensions exceed the explicit policy")); ++ } ++ let pixels = w.checked_mul(h).ok_or_else(|| invalid("output pixel count overflow"))?; ++ checked_output_bytes(pixels, 1, 0, limits)?; ++ Ok(pixels) ++} ++ ++/// Checked combined live-byte estimate; this is not an individual Vec layout or a lease. ++pub(crate) fn checked_stage_bytes(count: u64, element_bytes: u64, extra: u64, limits: crate::RenderLimits) -> Result { ++ let maximum = super::CpuBudget::Workstation.image_limits(false); ++ if limits.max_dimension > maximum.max_dimension || limits.max_pixels > maximum.max_pixels ++ || limits.max_scratch_bytes > maximum.max_scratch_bytes ++ { ++ return Err(invalid("output policy exceeds the bounded implementation envelope")); ++ } ++ let bytes = count.checked_mul(element_bytes).and_then(|n| n.checked_add(extra)) ++ .ok_or_else(|| invalid("output byte layout overflow"))?; ++ if bytes > limits.max_scratch_bytes { ++ return Err(invalid("output byte layout exceeds its explicit policy")); ++ } ++ Ok(bytes) ++} ++ ++/// Check an individual addressable byte layout separately from combined estimates. ++pub(crate) fn checked_output_bytes(count: u64, element_bytes: u64, extra: u64, limits: crate::RenderLimits) -> Result { ++ let bytes = checked_stage_bytes(count, element_bytes, extra, limits)?; ++ let addressable = usize::try_from(bytes).map_err(|_| invalid("output byte layout exceeds address space"))?; ++ if std::alloc::Layout::array::(addressable).is_err() { ++ return Err(invalid("output byte layout exceeds address space")); ++ } ++ Ok(addressable) ++} ++ ++pub(crate) fn encoded_limit_with_limits(width: u32, height: u32, limits: crate::RenderLimits) -> Result { ++ let pixels = output_pixels_with_limits(width, height, limits)?; ++ let row_bytes = u64::from(width).checked_mul(16).ok_or_else(|| invalid("EXR row overflow"))?; ++ i32::try_from(row_bytes).map_err(|_| invalid("EXR row exceeds scanline representation"))?; ++ i32::try_from(width).and_then(|_| i32::try_from(height)).map_err(|_| invalid("EXR window exceeds integer representation"))?; ++ let extra = u64::from(height).checked_mul(16).and_then(|n| n.checked_add(4096)).ok_or_else(|| invalid("EXR metadata overflow"))?; ++ Ok(checked_output_bytes(pixels, 16, extra, limits)? as u64) ++} ++ ++pub(crate) fn scanline_layout(width: u32, height: u32, header_bytes: usize, limits: crate::RenderLimits) -> Result<(usize, usize)> { ++ let limit = encoded_limit_with_limits(width, height, limits)?; ++ let rows = usize::try_from(height).map_err(|_| invalid("EXR row count exceeds address space"))?; ++ let row = usize::try_from(width).ok().and_then(|n| n.checked_mul(16)).ok_or_else(|| invalid("EXR row layout overflow"))?; ++ let first = rows.checked_mul(8).and_then(|n| n.checked_add(header_bytes)).ok_or_else(|| invalid("EXR offset table overflow"))?; ++ let total = row.checked_add(8).and_then(|n| n.checked_mul(rows)).and_then(|n| n.checked_add(first)).ok_or_else(|| invalid("EXR scanline layout overflow"))?; ++ if total as u64 > limit { return Err(invalid("EXR output exceeds its admission")); } ++ Ok((first, total)) + } + + fn attribute(out: &mut Vec, name: &[u8], kind: &[u8], value: &[u8]) -> Result<()> { +@@ -32,6 +95,12 @@ + } + + pub(super) fn header(width: u32, height: u32) -> Result> { ++ encoded_limit(width, height)?; ++ header_with_limits(width, height, super::GPU_PATH_LIMITS) ++} ++ ++pub(crate) fn header_with_limits(width: u32, height: u32, limits: crate::RenderLimits) -> Result> { ++ encoded_limit_with_limits(width, height, limits)?; + let mut out = Vec::new(); + out.try_reserve_exact(4096).map_err(|_| JobError::new(ErrorCode::AllocationFailed, "EXR header allocation failed"))?; + out.extend_from_slice(&20_000_630_u32.to_le_bytes()); +@@ -83,20 +152,25 @@ + } + impl ExrTask { + pub fn new(width: u32, height: u32, pixels: Vec<[f32; 4]>, cancel: CancelToken) -> Result { +- let limit = encoded_limit(width, height)?; ++ encoded_limit(width, height)?; ++ Self::new_with_limits(width, height, pixels, cancel, super::GPU_PATH_LIMITS) ++ } ++ ++ pub(crate) fn new_with_limits(width: u32, height: u32, pixels: Vec<[f32; 4]>, cancel: CancelToken, limits: crate::RenderLimits) -> Result { ++ let limit = encoded_limit_with_limits(width, height, limits)?; + if pixels.len() as u64 != u64::from(width) * u64::from(height) { + return Err(invalid("EXR pixel count differs from dimensions")); + } + cancel.check()?; +- let mut bytes = header(width, height)?; ++ checked_output_bytes(pixels.capacity() as u64, 16, 0, limits)?; ++ checked_stage_bytes(pixels.capacity() as u64, 16, limit, limits)?; ++ let mut bytes = header_with_limits(width, height, limits)?; + let row_bytes = u64::from(width) * 16; +- let first = bytes.len() as u64 + u64::from(height) * 8; +- let total = first + u64::from(height) * (row_bytes + 8); +- if total > limit { +- return Err(invalid("EXR output exceeds its admission")); +- } +- let additional = usize::try_from(total).ok().and_then(|n| n.checked_sub(bytes.len())).ok_or_else(|| invalid("EXR address space exceeded"))?; ++ let (first, total) = scanline_layout(width, height, bytes.len(), limits)?; ++ let first = first as u64; ++ let additional = total.checked_sub(bytes.len()).ok_or_else(|| invalid("EXR address space exceeded"))?; + bytes.try_reserve_exact(additional).map_err(|_| JobError::new(ErrorCode::AllocationFailed, "EXR output allocation failed"))?; ++ if bytes.capacity() as u64 > limit { return Err(invalid("EXR output exceeds its admission")); } + for y in 0..height { + bytes.extend_from_slice(&(first + u64::from(y) * (row_bytes + 8)).to_le_bytes()); + } +@@ -197,4 +271,43 @@ + cancel.cancel(); + assert_eq!(task.step(1).unwrap_err().code, ErrorCode::Cancelled); + } +-} ++ ++ #[test] ++ fn explicit_output_policy_is_exact_bounded_and_checked_before_allocation() { ++ let wide = super::super::CpuBudget::Workstation.image_limits(false); ++ assert_eq!(output_pixels_with_limits(8193, 1, wide).unwrap(), 8193); ++ assert_eq!(encoded_limit_with_limits(8193, 1, wide).unwrap(), 135200); ++ assert_eq!(checked_output_bytes(8193, 8, 65536, wide).unwrap(), 131080); ++ for (w, h) in [(0, 1), (1, 0), (u32::MAX, u32::MAX)] { ++ assert!(output_pixels_with_limits(w, h, wide).is_err()); ++ } ++ assert!(output_pixels_with_limits(8193, 1, super::super::GPU_PATH_LIMITS).is_err(), "a reduced fit is not acceptance"); ++ for hostile in [ ++ crate::RenderLimits { max_dimension: u64::MAX, ..wide }, ++ crate::RenderLimits { max_pixels: u64::MAX, ..wide }, ++ crate::RenderLimits { max_scratch_bytes: u64::MAX, ..wide }, ++ ] { ++ assert!(output_pixels_with_limits(1, 1, hostile).is_err()); ++ } ++ assert!(checked_output_bytes(u64::MAX, 16, 0, wide).is_err()); ++ assert!(checked_output_bytes(1, 1, u64::MAX, wide).is_err()); ++ assert!(scanline_layout(1, 1, usize::MAX, wide).is_err()); ++ assert!(checked_output_bytes(1, 16, 0, crate::RenderLimits { max_scratch_bytes: 15, ..wide }).is_err()); ++ assert!(checked_output_bytes(isize::MAX as u64 + 1, 1, 0, wide).is_err()); ++ } ++ ++ #[test] ++ fn explicit_gpu_exr_keeps_legacy_bytes_and_dimension_before_cancel_order() { ++ let pixels = vec![[4.0, 1.0, 0.25, 1.0]; 6]; ++ let expected = encode(pixels.clone(), 3, 2); ++ let mut task = ExrTask::new_with_limits(3, 2, pixels, CancelToken::default(), super::super::GPU_PATH_LIMITS).unwrap(); ++ assert!(task.step(2).unwrap()); ++ assert_eq!(task.finish().unwrap().0, expected); ++ let cancel = CancelToken::default(); ++ cancel.cancel(); ++ let error = ExrTask::new(0, 1, vec![], cancel.clone()).err().unwrap(); ++ assert_eq!(error.code, ErrorCode::InvalidRequest); ++ assert!(error.to_string().contains("linear EXR requires 1..8192")); ++ assert_eq!(ExrTask::new(1, 1, vec![], cancel).err().unwrap().code, ErrorCode::InvalidRequest); ++ } ++} +--- a/crates/render/src/job/linear_exr_decode.rs ++++ b/crates/render/src/job/linear_exr_decode.rs +@@ -17,13 +17,24 @@ + impl Decoder { + pub(super) fn new(bytes: &[u8], width: u32, height: u32, cancel: &CancelToken) -> Result { + cancel.check()?; +- let limit = super::linear_exr::encoded_limit(width, height)?; +- let expected = super::linear_exr::header(width, height)?; ++ super::linear_exr::encoded_limit(width, height)?; ++ Self::new_with_limits(bytes, width, height, cancel, super::GPU_PATH_LIMITS) ++ } ++ pub(crate) fn new_with_limits(bytes: &[u8], width: u32, height: u32, cancel: &CancelToken, limits: crate::RenderLimits) -> Result { ++ cancel.check()?; ++ let limit = super::linear_exr::encoded_limit_with_limits(width, height, limits)?; ++ let count = super::linear_exr::output_pixels_with_limits(width, height, limits)?; ++ super::linear_exr::checked_output_bytes(count, 16, 0, limits)?; ++ super::linear_exr::checked_stage_bytes(count, 16, 4096, limits)?; ++ let expected = if limits == super::GPU_PATH_LIMITS { ++ super::linear_exr::header(width, height)? ++ } else { ++ super::linear_exr::header_with_limits(width, height, limits)? ++ }; + if bytes.len() as u64 > limit || !bytes.starts_with(&expected) { + return Err(invalid("master is not the retained native FLOAT32 linear-sRGB/D65 profile")); + } +- let first = expected.len() + height as usize * 8; +- let length = first + height as usize * (width as usize * 16 + 8); ++ let (first, length) = super::linear_exr::scanline_layout(width, height, expected.len(), limits)?; + if bytes.len() != length { + return Err(invalid("native master has missing or trailing scanline bytes")); + } +@@ -79,7 +90,8 @@ + } + } + fn word(bytes: &[u8], offset: usize) -> Result { +- bytes.get(offset..offset + 4).and_then(|s| s.try_into().ok()).map(u32::from_le_bytes).ok_or_else(|| invalid("truncated native master word")) ++ let end = offset.checked_add(4).ok_or_else(|| invalid("native master word offset overflow"))?; ++ bytes.get(offset..end).and_then(|s| s.try_into().ok()).map(u32::from_le_bytes).ok_or_else(|| invalid("truncated native master word")) + } + + #[cfg(test)] +@@ -117,4 +129,22 @@ + assert!(decoder.step(&bytes, &cancel).is_err()); + assert_eq!(decoder.rows(), 0); + } ++ ++ #[test] ++ fn explicit_wide_native_roundtrip_retains_raw_bits_and_legacy_limits() { ++ let wide = super::super::CpuBudget::Workstation.image_limits(false); ++ let raw = vec![[4.0, 1.0, 0.25, 1.0]; 8193]; ++ let cancel = CancelToken::default(); ++ let mut task = super::super::linear_exr::ExrTask::new_with_limits(8193, 1, raw.clone(), cancel.clone(), wide).unwrap(); ++ assert!(task.step(1).unwrap()); ++ let (bytes, unchanged) = task.finish().unwrap(); ++ assert_eq!(unchanged, raw); ++ assert!(Decoder::new(&bytes, 8193, 1, &cancel).is_err()); ++ let mut decoder = Decoder::new_with_limits(&bytes, 8193, 1, &cancel, wide).unwrap(); ++ assert!(decoder.step(&bytes, &cancel).unwrap()); ++ assert_eq!(decoder.finish().unwrap(), raw); ++ cancel.cancel(); ++ assert_eq!(Decoder::new(&[], 0, 0, &cancel).err().unwrap().code, ErrorCode::Cancelled); ++ assert_eq!(Decoder::new_with_limits(&[], 0, 0, &cancel, wide).err().unwrap().code, ErrorCode::Cancelled); ++ } + } +--- a/crates/render/src/job/png.rs ++++ b/crates/render/src/job/png.rs +@@ -51,8 +51,20 @@ + return Err(JobError::new(ErrorCode::InvalidRequest, "invalid PNG dimensions or RGBA length")); + } + cancel.check()?; ++ Self::new_with_limits(request, rgba, cancel, super::GPU_PATH_LIMITS) ++ } ++ pub(crate) fn new_with_limits(request: &ImageRequest, rgba: Vec, cancel: CancelToken, limits: crate::RenderLimits) -> Result { ++ let pixels = super::linear_exr::output_pixels_with_limits(request.width, request.height, limits)?; ++ let rgba_bytes = super::linear_exr::checked_output_bytes(pixels, 4, 0, limits)?; ++ if rgba.len() != rgba_bytes { ++ return Err(JobError::new(ErrorCode::InvalidRequest, "invalid PNG dimensions or RGBA length")); ++ } ++ let limit = super::linear_exr::checked_output_bytes(pixels, 8, 65_536, limits)?; ++ let retained = super::linear_exr::checked_output_bytes(rgba.capacity() as u64, 1, 0, limits)? as u64; ++ super::linear_exr::checked_stage_bytes(1, retained, limit as u64, limits)?; ++ cancel.check()?; + let bytes = Arc::new(Mutex::new(Vec::new())); +- let output = Output { bytes: bytes.clone(), limit: (pixels * 8 + 65_536) as usize, cancel: cancel.clone() }; ++ let output = Output { bytes: bytes.clone(), limit, cancel: cancel.clone() }; + let mut encoder = png::Encoder::new(output, request.width, request.height); + encoder.set_color(png::ColorType::Rgba); + encoder.set_depth(png::BitDepth::Eight); +@@ -85,3 +97,43 @@ + Ok(TaskPoll::Complete(std::mem::take(&mut *bytes))) + } + } ++ ++#[cfg(test)] ++mod tests { ++ use super::*; ++ ++ fn request(width: u32, height: u32) -> ImageRequest { ++ ImageRequest { width, height, camera: Default::default(), integrator: Default::default(), raytrace: None, ++ environment: None, textures: None, studio_weights: None, background: [0; 3], transparent_background: false } ++ } ++ fn finish(mut task: PngTask) -> Vec { ++ loop { if let TaskPoll::Complete(bytes) = task.step(1).unwrap() { return bytes; } } ++ } ++ ++ #[test] ++ fn explicit_png_keeps_default_bytes_and_roundtrips_a_narrow_wide_image() { ++ let small = request(3, 2); let rgba = [20, 40, 60, 255].repeat(6); ++ let legacy = finish(PngTask::new(&small, rgba.clone(), CancelToken::default()).unwrap()); ++ let explicit = finish(PngTask::new_with_limits(&small, rgba, CancelToken::default(), super::super::GPU_PATH_LIMITS).unwrap()); ++ assert_eq!(explicit, legacy); ++ let wide = request(8193, 1); let rgba = [20, 40, 60, 255].repeat(8193); ++ assert!(PngTask::new(&wide, vec![], CancelToken::default()).is_err()); ++ let png = finish(PngTask::new_with_limits(&wide, rgba.clone(), CancelToken::default(), super::super::CpuBudget::Workstation.image_limits(false)).unwrap()); ++ let decoded = image::load_from_memory(&png).unwrap().to_rgba8(); ++ assert_eq!(decoded.dimensions(), (8193, 1)); ++ assert_eq!(decoded.as_raw(), &rgba); ++ } ++ ++ #[test] ++ fn png_dimension_length_and_cancel_precedence_remains_legacy() { ++ let cancel = CancelToken::default(); cancel.cancel(); ++ assert_eq!(PngTask::new(&request(0, 1), vec![], cancel.clone()).err().unwrap().code, ErrorCode::InvalidRequest); ++ assert_eq!(PngTask::new(&request(1, 1), vec![], cancel.clone()).err().unwrap().code, ErrorCode::InvalidRequest); ++ assert_eq!(PngTask::new(&request(1, 1), vec![0; 4], cancel.clone()).err().unwrap().code, ErrorCode::Cancelled); ++ let bad = crate::RenderLimits { max_scratch_bytes: u64::MAX, ..super::super::GPU_PATH_LIMITS }; ++ assert!(PngTask::new_with_limits(&request(1, 1), vec![0; 4], CancelToken::default(), bad).is_err()); ++ let cancel = CancelToken::default(); ++ let mut task = PngTask::new_with_limits(&request(1, 1), vec![0; 4], cancel.clone(), super::super::GPU_PATH_LIMITS).unwrap(); ++ cancel.cancel(); assert_eq!(task.step(1).err().unwrap().code, ErrorCode::Cancelled); ++ } ++} +--- a/crates/render/src/job/regrade.rs ++++ b/crates/render/src/job/regrade.rs +@@ -7,19 +7,29 @@ + pub(super) fn required_bytes(source: &RenderFrame, settings: Presentation) -> Result { + settings.validate()?; + super::linear_exr::encoded_limit(source.info.width, source.info.height)?; ++ required_bytes_with_limits(source, settings, super::GPU_PATH_LIMITS) ++} ++ ++pub(crate) fn required_bytes_with_limits(source: &RenderFrame, settings: Presentation, limits: crate::RenderLimits) -> Result { ++ settings.validate()?; ++ super::linear_exr::encoded_limit_with_limits(source.info.width, source.info.height, limits)?; + if source.linear_exr().is_none() { + return Err(JobError::new(ErrorCode::InvalidRequest, "this completed frame has no retained raw linear master")); + } +- // Includes decoded float4, bloom ping/pong float3 or display bytes, bounded +- // PNG output and codec/header/task metadata. The source keeps its own lease. +- Ok(u64::from(source.info.width) * u64::from(source.info.height) * 48 +- + 1_048_576 +- + settings.finishing.photographic.scratch_bytes(source.info.width, source.info.height)?) ++ output_bytes(source.info.width, source.info.height, settings, limits) ++} ++ ++fn output_bytes(width: u32, height: u32, settings: Presentation, limits: crate::RenderLimits) -> Result { ++ let pixels = super::linear_exr::output_pixels_with_limits(width, height, limits)?; ++ let photo = settings.finishing.photographic.scratch_bytes_with_limits(width, height, limits)?; ++ let extra = photo.checked_add(1_048_576).ok_or_else(|| JobError::new(ErrorCode::LimitExceeded, "regrade byte estimate overflow"))?; ++ super::linear_exr::checked_stage_bytes(pixels, 48, extra, limits) + } + + pub(super) struct RegradeTask { + source: Arc, + settings: Presentation, ++ limits: crate::RenderLimits, + cancel: CancelToken, + decoder: Option, + bloom: Option, +@@ -33,11 +43,20 @@ + impl RegradeTask { + pub(super) fn new(source: Arc, settings: Presentation, cancel: CancelToken) -> Result { + required_bytes(&source, settings)?; ++ Self::new_with_limits(source, settings, cancel, super::GPU_PATH_LIMITS) ++ } ++ pub(crate) fn new_with_limits(source: Arc, settings: Presentation, cancel: CancelToken, limits: crate::RenderLimits) -> Result { ++ required_bytes_with_limits(&source, settings, limits)?; + let raw = source.linear_exr().ok_or_else(|| JobError::new(ErrorCode::InvalidRequest, "linear master disappeared"))?; +- let decoder = Decoder::new(raw, source.info.width, source.info.height, &cancel)?; ++ let decoder = if limits == super::GPU_PATH_LIMITS { ++ Decoder::new(raw, source.info.width, source.info.height, &cancel)? ++ } else { ++ Decoder::new_with_limits(raw, source.info.width, source.info.height, &cancel, limits)? ++ }; + Ok(Self { + source, + settings, ++ limits, + cancel, + decoder: Some(decoder), + bloom: None, +@@ -81,7 +100,7 @@ + background: self.settings.background, + transparent_background: self.settings.transparent_background, + }; +- self.png = Some(PngTask::new(&request, task.finish()?, self.cancel.clone())?); ++ self.png = Some(PngTask::new_with_limits(&request, task.finish()?, self.cancel.clone(), self.limits)?); + return self.pending(0, u64::from(height)); + } + if let Some(mut decoder) = self.decoder.take() { +@@ -93,7 +112,7 @@ + } + let pixels = decoder.finish()?; + if let Some(bloom) = self.settings.finishing.bloom.filter(|b| b.active()) { +- self.bloom = Some(BloomTask::new(width, height, pixels, bloom, self.cancel.clone())?); ++ self.bloom = Some(BloomTask::new_with_limits(width, height, pixels, bloom, self.cancel.clone(), self.limits)?); + return self.pending(0, u64::from(height) * 7); + } + self.linear = Some(pixels); +@@ -124,7 +143,8 @@ + .ok_or_else(|| JobError::new(ErrorCode::Internal, "missing regrade pixels"))?; + let output = self.rgba.get_mut(self.encoded * 4..end * 4).ok_or_else(|| JobError::new(ErrorCode::Internal, "missing regrade output"))?; + let glow = self.glow.as_deref().and_then(|g| g.get(self.encoded..end)); +- self.settings.display(width, height)?.encode_bloom_at(pixels, output, &self.cancel, self.encoded, glow)?; ++ self.settings.display_with_limits(width, height, self.limits)? ++ .encode_bloom_at_with_limits(pixels, output, &self.cancel, self.encoded, glow, self.limits)?; + self.encoded = end; + if end < count { + return self.pending(end as u64, count as u64); +@@ -132,13 +152,14 @@ + self.glow = None; + if self.settings.finishing.photographic.active() { + let pixels = self.linear.take().ok_or_else(|| JobError::new(ErrorCode::Internal, "missing photographic master pixels"))?; +- self.photographic = Some(super::photographic::PhotographicTask::new( ++ self.photographic = Some(super::photographic::PhotographicTask::new_with_limits( + width, + height, + std::mem::take(&mut self.rgba), + pixels, + self.settings.finishing.photographic, + self.cancel.clone(), ++ self.limits, + )?); + return self.pending(0, u64::from(width) * u64::from(height)); + } +@@ -155,7 +176,22 @@ + background: self.settings.background, + transparent_background: self.settings.transparent_background, + }; +- self.png = Some(PngTask::new(&request, std::mem::take(&mut self.rgba), self.cancel.clone())?); ++ self.png = Some(PngTask::new_with_limits(&request, std::mem::take(&mut self.rgba), self.cancel.clone(), self.limits)?); + self.pending(0, u64::from(height)) + } + } ++ ++#[cfg(test)] ++mod tests { ++ use super::*; ++ ++ #[test] ++ fn regrade_size_estimate_is_explicit_checked_and_does_not_grant_a_lease() { ++ let wide = super::super::CpuBudget::Workstation.image_limits(false); ++ assert_eq!(output_bytes(8193, 1, Presentation::default(), wide).unwrap(), 8193 * 48 + 1_048_576); ++ assert!(output_bytes(8193, 1, Presentation::default(), super::super::GPU_PATH_LIMITS).is_err()); ++ assert!(output_bytes(u32::MAX, u32::MAX, Presentation::default(), wide).is_err()); ++ assert!(output_bytes(1, 1, Presentation::default(), crate::RenderLimits { max_scratch_bytes: u64::MAX, ..wide }).is_err()); ++ assert!(output_bytes(1, 1, Presentation::default(), crate::RenderLimits { max_scratch_bytes: 1_048_576, ..wide }).is_err()); ++ } ++}