Preserve every-pass CPU source and reviewed SHA-state recovery; validation pending

This commit is contained in:
selune committed 2026-10-31 10:40:53 +01:00
1 parent dbc6041ba7
commit 7cf392d7c3
33 files changed
+41867 -1

No files matched your search

+21 -1
View File
@@ -214,4 +214,24 @@ The complete API consumer connects captured direct visibility and RGB shading to
preserve the source-reviewed 1,048,576 Workstation ceiling, u32 film resolve and
explicit Interactive target/seed controls. Thirteen new tests are written and
UNRUN. **Producer/host per-pass and u32 adapters are still pending; not adoptable
alone, compiled, installed, ready or merged.** Existing budget limits remain.
alone, compiled, installed, ready or merged.** Existing budget limits remain.
## CPU every-pass composition after C27 — 31 October
[Twenty-five exact post-format source files and portable bindings](../2026-10-31/cpu-every-pass-c27-source/README.md)
preserve the complete CPU proposal and its actual failed-build source. C27
format/check exited 0; combined compilation stopped on the existing 1,024-byte
metadata-size assertion (E0308). All 982 selected cases are UNRUN; the private
layout repair, full CI and native each-pass acceptance remain pending. This
supersedes the earlier nine-file snapshot for continuation, not production readiness.
## C27 metadata recovery: single active SHA state — 31 October
[One exact host-source successor and bindings](../2026-10-31/c27-sha-state-recovery/README.md)
propose serial PNG/EXR hashing with one active SHA state and the completed PNG
digest. The 1,024-byte assertion remains unchanged. Kernel review and actual
compilation are pending at curation; the planned 983 cases are all UNRUN.
Apply only on the exact C27 failed-source composition, not arbitrary main.
The single-host recovery has now been independently source-reviewed and adopted locally. Compilation, all 983 planned cases and native each-pass image acceptance remain pending.
@@ -0,0 +1,52 @@
# C27 recovery proposal: one active PNG/EXR SHA state
31 October 2026. **Source reviewed and adopted locally; not yet formatted,
compiled, tested, installed, ready or merged. Root and independent Kernel
source reviews are closed; ABI fit and execution remain unverified.**
The actual C27 combined build stopped with E0308 at its existing fixed metadata
assertion before any test body. This candidate is a narrow proposed repair,
**not evidence that E0308 is resolved or that the target ABI size is known**.
## Source change
The existing work scans PNG bytes before EXR bytes. The candidate retains one
active `Sha256` state, finalises the PNG output into
`Option<sha2::digest::Output<Sha256>>` (a 32-byte SHA256 digest, not an ABI-size
claim for the Option or surrounding structures), then uses a fresh active state
for EXR. It preserves the original chunk size, bounded advance count, byte order,
cancel/publication guards and payload/lease ownership. It adds no hidden heap
allocation and does not raise the 1,024-byte metadata allowance or either
existing size assertion. Those assertions remain compilation oracles.
One original regression is written in the existing host module:
`sequential_png_and_exr_hashing_preserves_independent_payload_digests`.
It derives expected PNG and EXR hashes independently over distinct whole buffers
larger than one advance; units 1 and 3 exercise transitions between and within
calls. It also covers absent/empty EXR, zero-unit and repeated completed steps.
The test is **UNRUN**. Existing digest, cancellation, late-publication and lease
regressions remain unchanged and need actual-source execution.
The proposed next selection is **983 cases, all UNRUN**: C27's 982 unexecuted
cases plus this one new regression. This is a planned selection, not an actual
inventory or a result from another run. No new compiler, runtime, native image,
physical GPU, full-CI or renderer-parity qualification follows from this patch.
## Receiver and continuation
Apply only after the [exact C27 failed-build 25-file composition](../cpu-every-pass-c27-source/README.md),
whose immediate host bytes hash to
`f775f4e458947b2c402fe97f10b320f7c7f4a9060cf502b5a69975e006eec71e`.
The candidate host hash is
`2c72c307ec49a94b100f4be32ab6a4af4be494199ff7ad5c87bb698e7f13ab4e`.
This single-file successor does not replace the other 24 source files and must
not be applied to arbitrary main or stacked blindly on the older nine-source
high-pass/UI snapshot.
`candidate/` contains exact RAW source, `source-bindings.json` is portable and
`delta-LF-review.patch` contains the full readable change, including removals.
Continue with one fresh serial cached validation and actual artifact/inventory
bindings before tests; source review and local adoption are already complete. Native
per-pass display, final/export quality and the default-change/preference process
remain separate unresolved obligations. Archive preservation is not production
readiness and changes neither production PR #8938 nor the installed app.
@@ -0,0 +1,171 @@
--- a/crates/render/src/job/host.rs
+++ b/crates/render/src/job/host.rs
@@ -725,7 +725,7 @@
hashed: usize,
preview_samples: Option<u32>,
exr: Option<Vec<u8>>,
- exr_digest: Sha256,
+ png_digest: Option<sha2::digest::Output<Sha256>>,
exr_hashed: usize,
}
// Keep the new fixed completion state within the existing metadata allowance
@@ -741,7 +741,7 @@
impl PendingPng {
fn new(png: Vec<u8>) -> Self {
- Self { png, digest: Sha256::new(), hashed: 0, preview_samples: None, exr: None, exr_digest: Sha256::new(), exr_hashed: 0 }
+ Self { png, digest: Sha256::new(), hashed: 0, preview_samples: None, exr: None, png_digest: None, exr_hashed: 0 }
}
#[cfg(feature = "raytrace-cpu")]
@@ -749,20 +749,30 @@
Self { preview_samples: Some(samples), ..Self::new(png) }
}
+ fn finish_png_digest(&mut self) {
+ if self.hashed == self.png.len() && self.png_digest.is_none() {
+ // PNG and EXR are scanned serially. Keep the completed PNG output,
+ // then reuse a fresh digest state for EXR without another allocation.
+ self.png_digest = Some(std::mem::take(&mut self.digest).finalize());
+ }
+ }
+
fn step(&mut self, units: usize, cancel: &CancelToken) -> Result<bool> {
cancel.check()?;
+ self.finish_png_digest();
for _ in 0..units.min(PNG_HASH_CHUNKS_PER_ADVANCE) {
- let (bytes, hashed, digest) = if self.hashed < self.png.len() {
- (&self.png, &mut self.hashed, &mut self.digest)
+ let (bytes, hashed) = if self.hashed < self.png.len() {
+ (&self.png, &mut self.hashed)
} else if let Some(exr) = self.exr.as_ref().filter(|exr| self.exr_hashed < exr.len()) {
- (exr, &mut self.exr_hashed, &mut self.exr_digest)
+ (exr, &mut self.exr_hashed)
} else {
break;
};
let end = hashed.saturating_add(PNG_HASH_CHUNK_BYTES).min(bytes.len());
- digest.update(bytes.get(*hashed..end).ok_or_else(|| JobError::new(ErrorCode::Internal, "missing completed image digest chunk"))?);
+ self.digest.update(bytes.get(*hashed..end).ok_or_else(|| JobError::new(ErrorCode::Internal, "missing completed image digest chunk"))?);
*hashed = end;
cancel.check()?;
+ self.finish_png_digest();
}
Ok(self.hashed == self.png.len() && self.exr.as_ref().is_none_or(|exr| self.exr_hashed == exr.len()))
}
@@ -774,6 +784,65 @@
}
}
}
+
+#[cfg(test)]
+#[test]
+fn sequential_png_and_exr_hashing_preserves_independent_payload_digests() {
+ let quantum_bytes = PNG_HASH_CHUNK_BYTES * PNG_HASH_CHUNKS_PER_ADVANCE;
+ for units in [1, 3] {
+ for exr_length in [None, Some(0), Some(quantum_bytes + 29)] {
+ let png: Vec<u8> = (0..quantum_bytes + 13).map(|index| (index as u8).wrapping_mul(17).wrapping_add(3)).collect();
+ let exr: Option<Vec<u8>> = exr_length.map(|length| (0..length).map(|index| (index as u8).wrapping_mul(29).wrapping_add(101)).collect());
+ let expected_png = Sha256::digest(&png);
+ let expected_exr = exr.as_ref().map(Sha256::digest);
+ if let Some(expected_exr) = &expected_exr {
+ assert_ne!(&expected_png, expected_exr, "the distinct payloads must not share a digest");
+ }
+ let png_length = png.len();
+ let exr_length = exr.as_ref().map_or(0, Vec::len);
+ assert!(png_length > quantum_bytes);
+ assert!(exr_length == 0 || exr_length > quantum_bytes);
+ let chunks = png_length.div_ceil(PNG_HASH_CHUNK_BYTES) + exr_length.div_ceil(PNG_HASH_CHUNK_BYTES);
+ let steps = chunks.div_ceil(units);
+ let mut pending = PendingPng::new(png);
+ pending.exr = exr;
+ let cancel = CancelToken::default();
+ assert!(!pending.step(0, &cancel).unwrap());
+ assert_eq!((pending.hashed, pending.exr_hashed), (0, 0));
+ assert!(pending.png_digest.is_none());
+ let mut crossed_within_step = false;
+ let mut saw_png_only_boundary = false;
+ for step in 0..steps {
+ let before_png = pending.hashed;
+ let before_exr = pending.exr_hashed;
+ let done = pending.step(units, &cancel).unwrap();
+ assert_eq!(done, step + 1 == steps);
+ let advanced = pending.hashed + pending.exr_hashed - before_png - before_exr;
+ assert!(advanced > 0 && advanced <= units * PNG_HASH_CHUNK_BYTES);
+ if pending.hashed == png_length {
+ assert_eq!(pending.png_digest.as_ref(), Some(&expected_png));
+ saw_png_only_boundary |= pending.exr_hashed == 0;
+ }
+ crossed_within_step |= before_png < png_length && pending.hashed == png_length && pending.exr_hashed > 0;
+ assert_eq!(pending.progress().done, (pending.hashed + pending.exr_hashed) as u64);
+ assert_eq!(pending.progress().total, (png_length + exr_length) as u64);
+ }
+ assert_eq!((pending.hashed, pending.exr_hashed), (png_length, exr_length));
+ if exr_length > 0 {
+ assert_eq!(crossed_within_step, units == 3);
+ assert_eq!(saw_png_only_boundary, units == 1);
+ }
+ for extra_units in [0, 1] {
+ assert!(pending.step(extra_units, &cancel).unwrap());
+ assert_eq!(pending.png_digest.as_ref(), Some(&expected_png));
+ let actual_exr = pending.exr.as_ref().map(|_| pending.digest.clone().finalize());
+ assert_eq!(actual_exr, expected_exr, "EXR must start from a fresh SHA state and survive repeated completed steps");
+ assert_eq!((pending.hashed, pending.exr_hashed), (png_length, exr_length));
+ }
+ }
+ }
+}
+
struct Running {
source_master: Option<Arc<RenderFrame>>,
@@ -1247,10 +1316,11 @@
data.progress = progress;
return Ok(true);
}
- let PendingPng { png, digest, preview_samples, exr, exr_digest, .. } =
+ let PendingPng { png, digest, preview_samples, exr, png_digest, .. } =
self.pending_png.take().ok_or_else(|| JobError::new(ErrorCode::Internal, "missing completed PNG digest"))?;
+ let png_digest = png_digest.ok_or_else(|| JobError::new(ErrorCode::Internal, "missing finalized PNG digest"))?;
if self.partial.as_ref().and_then(|slot| slot.0.first()).is_some_and(|partial| partial.pending.is_some()) {
- return self.publish_partial(png, digest);
+ return self.publish_partial(png, png_digest);
}
let info = FrameInfo {
job: self.handle.0.id,
@@ -1262,7 +1332,7 @@
encoding: ColourEncoding::Srgb,
alpha: AlphaConvention::Straight,
png_bytes: png.len() as u64,
- png_sha256: format!("{:x}", digest.finalize()),
+ png_sha256: format!("{:x}", png_digest),
};
// Include the working digest/Vec metadata, completed frame layout,
// actual hex allocation, bounded copied IDs and Arc/header allowance.
@@ -1340,7 +1410,7 @@
let exr = exr.map(|bytes| {
let info = LinearMasterInfo {
bytes: bytes.len() as u64,
- sha256: format!("{:x}", exr_digest.finalize()),
+ sha256: format!("{:x}", digest.finalize()),
encoding: LinearColourEncoding::SceneLinearSrgbD65,
alpha: LinearAlphaConvention::CoveragePremultiplied,
};
@@ -2799,7 +2869,7 @@
self.pending_png = Some(PendingPng::new(png));
Ok(())
}
- fn publish_partial(&mut self, png: Vec<u8>, digest: Sha256) -> Result<bool> {
+ fn publish_partial(&mut self, png: Vec<u8>, digest: sha2::digest::Output<Sha256>) -> Result<bool> {
self.handle.0.cancel.check()?;
let partial = self.partial.as_mut().ok_or_else(|| JobError::new(ErrorCode::Internal, "missing partial publication state"))?.get_mut()?;
let pending = partial.pending.take().ok_or_else(|| JobError::new(ErrorCode::Internal, "missing partial metadata"))?;
@@ -2818,7 +2888,7 @@
encoding: ColourEncoding::Srgb,
alpha: AlphaConvention::Straight,
png_bytes: publication.png.len() as u64,
- png_sha256: format!("{:x}", digest.finalize()),
+ png_sha256: format!("{:x}", digest),
};
let metadata = std::mem::size_of::<RenderPartialPreview>()
.checked_add(64 + 2 * crate::MAX_RENDER_ID_BYTES)
@@ -0,0 +1,27 @@
{
"status": "SOURCE_ONLY_C27_SHA_STATE_RECOVERY_V2_UNFORMATTED_UNCOMPILED_UNRUN",
"required_receiver": "Exact C27 post-format failed-build 25-file composition, with every unrelated file preserved; not arbitrary main or the earlier nine-file checkpoint.",
"receiver_source_manifest_sha256": "a7b088eef563cbba4bfc5f2c26cf2d02ac6e855088710a072fdff35f889c1551",
"files": [
{
"path": "crates/render/src/job/host.rs",
"before_sha256": "f775f4e458947b2c402fe97f10b320f7c7f4a9060cf502b5a69975e006eec71e",
"before_bytes": 131474,
"after_sha256": "2c72c307ec49a94b100f4be32ab6a4af4be494199ff7ad5c87bb698e7f13ab4e",
"after_bytes": 135425
}
],
"production_change": "One retained active SHA256 state plus the finalized 32-byte PNG output; the existing1024-byte metadata allowance/assertions are unchanged. No new heap-backed state is introduced.",
"new_test": "job::host::sequential_png_and_exr_hashing_preserves_independent_payload_digests",
"new_tests_written": 1,
"new_tests_run": 0,
"actual_C27_selected_cases_UNRUN": 982,
"proposed_next_selected_cases": 983,
"all_proposed_cases_state": "UNRUN",
"Kernel_independent_review": "CLOSED_NO_BLOCKING_SOURCE_FINDING_NOT_RUNTIME",
"E0308_resolved_by_compilation": false,
"exact_target_ABI_layout_known": false,
"full_CI_native_or_GPU_acceptance": false,
"local_source_adoption": "COMPLETE_NO_EXECUTION_GRANT",
"local_adopted_source_manifest_sha256": "9a2bfddacbd5a7f38ec4e4aba0e75fb99420d278a483d7ae8c2cf1cf53a359bb"
}
@@ -0,0 +1,70 @@
# CPU progressive every-pass composition — exact C27 failed-build source
31 October 2026. Reviewable source preservation for #6201: **25 composed files,
formatted locally, but not successfully compiled, tested, installed, ready or
merged**. All **982 selected native cases remain UNRUN**. No native per-pass
display, GPU, image-quality/parity or full repository CI pass is claimed.
## Included source
The composed proposal connects complete-pass publication, bounded reusable image
slots and a counted external-retention exception; u32 film/coverage consumers;
the explicit Workstation ceiling of 1,048,576 passes; and Interactive controls
that retain an explicit target/seed. Compact 64, Studio 1024, pixel-times-sample,
ordinary-work and memory limits remain binding. At 1,048,576 passes, Workstation's
unchanged 68,719,476,736 camera-sample cap permits at most 65,536 pixels. This is not
permission to combine every maximum or a promise of perfect physical quality.
Normal production attempts an image at every complete nonfinal pass, then one
final image. If both reusable slots remain externally pinned after host credit
retirement/retry, the real retention-skip counter records the omitted snapshot;
final work continues without an acknowledgement wait or an unbounded PNG list.
Publication and a slower client's physical repaints are different observations.
The final/provisional/export, cancellation, invalidation and Nateaux UI contracts
remain acceptance obligations, not completed fixes established by this archive.
## Actual C27 outcome
Formatting and its check exited 0 and changed 11 of the selected Rust files. The
normal combined-library build then exited 101 with **E0308 at
`crates/render/src/job/host.rs:734`**: a compile-time aggregate metadata-size
assertion for the 1,024-byte admission allowance was false. No exact layout size
was inferred. Raising the assertion allowance is not the accepted repair.
No test binary inventory or test body ran: **0 passed, 0 failed, 982 UNRUN**; there
was no qualified five-library artifact set. Strict affected Clippy, wasm, lists,
the full repository gate and native application acceptance were not reached.
This was a compiler/source failure, not a RAM-admission stop: the pre-build free
RAM sample was 11,556,589,568 bytes against 7,516,192,768 required; the observed
minimum was 11,035,467,776 bytes and no sticky memory-floor fault was reported.
The owned attempt terminated and its reservation was released. A private host
layout/accounting repair is pending and is **not** silently included here.
## Relationship to the earlier checkpoint
This supersedes the [earlier nine-source high-pass/UI snapshot](https://github.com/tangency-labs/solidcraft/blob/dbc6041ba7059ec30b11fa72b5d1abd59f5b104a/proposals/render/2026-10-31/cpu-high-pass-ui-source/README.md)
for continuation of this composed unit; it does not erase that history. That
snapshot's new cooperative UI fixture was later found invalid at the source/API
boundary. Its raw source was retained privately and the new test was explicitly
replaced with request-only coverage plus separate consumer-state coverage. This
does **not** satisfy native each-pass acceptance. The next owned desktop run must
still show real images for passes 1 → 2 → 3 → 4 in a detailed original scene, including
cancel/edit/restart and final/export authority. No synthetic counter or terminal
image may stand in for those observations.
## Applying and continuing
`candidate/` contains all 25 exact C27 post-format RAW files. The portable
`source-bindings.json` binds every immediate before/after byte length and digest;
the new locale has a null before binding. Verify the required receiver first.
`delta-LF-review.patch` is the full readable 25-file change, including removals;
the RAW candidates and hashes are authoritative for mixed line endings. Do not
apply this to arbitrary current main or stack it blindly over another snapshot.
The production draft #8938 remained at
`a077906234972dbbf11e80c54893f85ece97c8b7` at this checkpoint. This archive does
not update that production head or the installed app. Continue with the separately
reviewed metadata/accounting fix, exact source composition, a fresh serial cached
validation and its own actual artifacts/inventories before tests. Default-change
classification/preference handling remains unresolved before production readiness;
source preservation does not waive that process.
@@ -0,0 +1,20 @@
{
"de": {
"render.cpu_pass_progress": "Vollständige Durchgänge: {current} / {target} · vorläufig"
},
"en": {
"render.cpu_pass_progress": "Complete passes: {current} / {target} · provisional"
},
"es": {
"render.cpu_pass_progress": "Pasadas completas: {current} / {target} · provisional"
},
"ja": {
"render.cpu_pass_progress": "完了したパス: {current} / {target} · 暫定"
},
"ko": {
"render.cpu_pass_progress": "완료된 패스: {current} / {target} · 임시"
},
"zh": {
"render.cpu_pass_progress": "完整遍数:{current} / {target} · 临时结果"
}
}
@@ -0,0 +1,179 @@
//! Bounded camera film: linear radiance sums and primary coverage, never display RGB.
//! Exactly one scanline-ordered update per pixel and absolute sample ordinal makes
//! a complete pass a state invariant. Initialization and updates are cancellable
//! single-pixel operations. The owning image job supplies its existing work lease.
use super::{invalid, limit};
use crate::job::{CancelToken, CpuBudget, CpuProgressiveOptions, ErrorCode, JobError, Result};
#[derive(Clone, Copy, Default, Debug, PartialEq)]
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 {
pixels: Vec<Pixel>,
count: usize,
sample_limit: u32,
samples: u32,
next_pixel: usize,
}
impl PrimaryFilm {
pub(crate) fn required_bytes(width: u32, height: u32, options: CpuProgressiveOptions, budget: CpuBudget) -> Result<u64> {
options.validate_image_with_budget(width, height, budget)?;
(u64::from(width) * u64::from(height))
.checked_mul(std::mem::size_of::<Pixel>() as u64)
.and_then(|n| n.checked_add(std::mem::size_of::<Self>() as u64))
.ok_or_else(|| limit("primary film storage overflow"))
}
pub(crate) fn new(
width: u32,
height: u32,
options: CpuProgressiveOptions,
admitted_bytes: u64,
cancel: &CancelToken,
budget: CpuBudget,
) -> Result<Self> {
cancel.check()?;
let required = Self::required_bytes(width, height, options, budget)?;
if admitted_bytes < required {
return Err(limit("primary film is not covered by image admission"));
}
let count = usize::try_from(u64::from(width) * u64::from(height)).map_err(|_| limit("primary film address space exceeded"))?;
let mut pixels = Vec::new();
pixels.try_reserve_exact(count).map_err(|_| JobError::new(ErrorCode::AllocationFailed, "could not reserve primary film"))?;
if pixels.capacity() != count {
return Err(limit("actual primary film capacity exceeds admission"));
}
cancel.check()?;
Ok(Self { pixels, count, sample_limit: options.samples_per_pixel, samples: 0, next_pixel: 0 })
}
pub(crate) fn initialized(&self) -> usize {
self.pixels.len()
}
pub(crate) fn ready(&self) -> bool {
self.pixels.len() == self.count
}
pub(crate) fn initialize_one(&mut self, cancel: &CancelToken, charge: &mut impl FnMut() -> Result<()>) -> Result<()> {
cancel.check()?;
if self.ready() {
return Err(invalid("primary film is already initialized"));
}
charge()?;
cancel.check()?;
self.pixels.push(Pixel::default());
Ok(())
}
pub(crate) fn samples(&self) -> u32 {
self.samples
}
/// Validate everything before the one bounded mutation. Failed/cancelled
/// updates never consume a sample ordinal or partially alter a pixel.
pub(crate) fn add(
&mut self,
index: usize,
ordinal: u32,
radiance: [f64; 3],
covered: bool,
cancel: &CancelToken,
charge: &mut impl FnMut() -> Result<()>,
) -> Result<()> {
cancel.check()?;
if !self.ready() || index != self.next_pixel || ordinal != self.samples || ordinal >= self.sample_limit {
return Err(invalid("primary film requires the next pixel and absolute sample ordinal"));
}
if radiance.into_iter().any(|v| !v.is_finite() || !(0.0..=1e12).contains(&v)) || (!covered && radiance != [0.0; 3]) {
return Err(invalid("invalid primary linear radiance or coverage"));
}
let pixel = self.pixels.get(index).copied().ok_or_else(|| invalid("primary film pixel out of range"))?;
let sum = std::array::from_fn(|i| pixel.sum[i] + radiance[i]);
if sum.iter().any(|v| !v.is_finite() || *v < 0.0 || *v > f64::from(self.sample_limit) * 1e12) {
return Err(invalid("primary film radiance sum exceeds finite range"));
}
let hits = pixel.covered.checked_add(u32::from(covered)).filter(|n| *n <= ordinal + 1).ok_or_else(|| invalid("primary coverage overflow"))?;
charge()?;
cancel.check()?;
*self.pixels.get_mut(index).ok_or_else(|| invalid("primary film pixel disappeared"))? = Pixel { sum, covered: hits };
self.next_pixel += 1;
if self.next_pixel == self.count {
self.next_pixel = 0;
self.samples += 1;
}
Ok(())
}
/// A display consumer can only read a fully completed, immutable pass. The
/// returned radiance is premultiplied by coverage; background is kept separate.
pub(crate) fn pixel(&self, index: usize) -> Result<([f64; 3], u32, u32)> {
if !self.ready() || self.next_pixel != 0 || self.samples == 0 {
return Err(invalid("primary film has no uniform complete pass"));
}
let pixel = self.pixels.get(index).ok_or_else(|| invalid("primary film resolve index out of range"))?;
Ok((pixel.sum.map(|sum| sum / f64::from(self.samples)), pixel.covered, self.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<PartialFrontier> {
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<PartialPixel> {
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 })
}
}
@@ -0,0 +1,632 @@
use super::*;
#[cfg(feature = "raytrace-cpu")]
mod camera_passes {
use super::primary::PrimaryFilm;
use super::*;
use crate::job::CpuProgressiveOptions;
fn primary() -> PrimaryFilm {
let options = CpuProgressiveOptions { samples_per_pixel: 4, seed: 7 };
let bytes = PrimaryFilm::required_bytes(2, 1, options, crate::job::CpuBudget::Compact).unwrap();
let mut film = PrimaryFilm::new(2, 1, options, bytes, &CancelToken::default(), crate::job::CpuBudget::Compact).unwrap();
assert!(!film.ready());
let mut charged = 0;
while !film.ready() {
film.initialize_one(&CancelToken::default(), &mut || {
charged += 1;
Ok(())
})
.unwrap();
}
assert_eq!(charged, 2);
film
}
#[test]
fn camera_film_keeps_linear_sums_coverage_and_uniform_absolute_passes() {
let mut film = primary();
let cancel = CancelToken::default();
assert!(film.pixel(0).is_err());
for ordinal in 0..4 {
film.add(0, ordinal, [2.0, 4.0, 8.0], true, &cancel, &mut || Ok(())).unwrap();
assert!(film.pixel(0).is_err(), "a partial pass cannot be resolved");
assert!(film.add(0, ordinal, [0.0; 3], false, &cancel, &mut || Ok(())).is_err(), "duplicate pixel must not consume a sample");
let covered = ordinal % 2 == 0;
film.add(1, ordinal, if covered { [6.0; 3] } else { [0.0; 3] }, covered, &cancel, &mut || Ok(())).unwrap();
assert_eq!(film.samples(), ordinal + 1);
}
assert_eq!(film.pixel(0).unwrap(), ([2.0, 4.0, 8.0], 4, 4));
assert_eq!(film.pixel(1).unwrap(), ([3.0; 3], 2, 4));
assert!(film.add(0, 4, [1.0; 3], true, &cancel, &mut || Ok(())).is_err());
}
#[test]
fn camera_film_cancellation_invalid_radiance_and_work_failure_are_atomic() {
let mut film = primary();
let cancel = CancelToken::default();
let observer = cancel.clone();
assert_eq!(
film.add(0, 0, [1.0; 3], true, &cancel, &mut || {
observer.cancel();
Ok(())
})
.unwrap_err()
.code,
ErrorCode::Cancelled
);
for (rgb, covered) in [([1.0; 3], false), ([f64::NAN; 3], true), ([-1.0; 3], true)] {
assert!(film.add(0, 0, rgb, covered, &CancelToken::default(), &mut || Ok(())).is_err());
}
assert!(film.add(0, 0, [1.0; 3], true, &CancelToken::default(), &mut || Err(limit("work exhausted"))).is_err());
film.add(0, 0, [4.0; 3], true, &CancelToken::default(), &mut || Ok(())).unwrap();
film.add(1, 0, [0.0; 3], false, &CancelToken::default(), &mut || Ok(())).unwrap();
assert_eq!(film.pixel(0).unwrap(), ([4.0; 3], 1, 1));
assert_eq!(film.pixel(1).unwrap(), ([0.0; 3], 0, 1));
}
}
fn film(width: u32, height: u32, limit: u32) -> FilmAccumulator {
let bytes = FilmAccumulator::required_bytes(width, height, limit).unwrap();
FilmAccumulator::new(width, height, limit, bytes, &CancelToken::default(), &mut |_| Ok(())).unwrap()
}
fn add(film: &mut FilmAccumulator, start: usize, values: &[[f64; 3]]) {
film.add_range(start, values, &CancelToken::default(), &mut |_| Ok(())).unwrap();
}
#[test]
fn constant_and_alternating_samples_have_analytic_statistics() {
let mut film = film(2, 1, 4);
for value in [0.0, 2.0, 0.0, 2.0] {
add(&mut film, 0, &[[7.0, 3.0, 1.0], [value; 3]]);
}
assert_eq!(film.pixel_statistics(0).unwrap(), PixelStatistics { mean: [7.0, 3.0, 1.0], variance: [0.0; 3], count: 4 });
let statistics = film.pixel_statistics(1).unwrap();
assert_eq!(statistics.mean, [1.0; 3]);
assert_eq!(statistics.variance, [4.0 / 3.0; 3]);
}
#[test]
fn complete_pass_refuses_empty_or_uneven_counts_and_keeps_linear_values() {
let mut film = film(2, 1, 3);
assert!(film.complete_pass(&CancelToken::default(), &mut |_| Ok(())).is_err());
add(&mut film, 0, &[[20.0, 2.0, 0.0]]);
assert!(film.complete_pass(&CancelToken::default(), &mut |_| Ok(())).is_err());
add(&mut film, 1, &[[4.0, 8.0, 16.0]]);
let pass = film.complete_pass(&CancelToken::default(), &mut |_| Ok(())).unwrap();
assert_eq!(pass.samples_per_pixel(), 1);
assert_eq!(pass.dimensions(), (2, 1));
assert_eq!(pass.pixels().collect::<Vec<_>>(), vec![[20.0, 2.0, 0.0], [4.0, 8.0, 16.0]]);
}
#[test]
fn invalid_sample_at_end_leaves_entire_update_unchanged() {
for bad in [f64::NAN, f64::INFINITY, f64::NEG_INFINITY, -1.0] {
let mut film = film(2, 1, 3);
add(&mut film, 0, &[[1.0; 3], [2.0; 3]]);
let before = film.pixels.clone();
assert_eq!(film.add_range(0, &[[3.0; 3], [bad; 3]], &CancelToken::default(), &mut |_| Ok(())).unwrap_err().code, ErrorCode::InvalidRequest);
assert_eq!(film.pixels, before);
}
}
#[test]
fn sample_limit_and_numeric_overflow_refuse_atomically() {
let mut limited = film(2, 1, 1);
add(&mut limited, 1, &[[1.0; 3]]);
let before = limited.pixels.clone();
assert_eq!(limited.add_range(0, &[[1.0; 3]; 2], &CancelToken::default(), &mut |_| Ok(())).unwrap_err().code, ErrorCode::LimitExceeded);
assert_eq!(limited.pixels, before);
let mut extreme = film(2, 1, 3);
add(&mut extreme, 0, &[[1.0; 3], [f64::MAX; 3]]);
let before = extreme.pixels.clone();
assert!(extreme.add_range(0, &[[2.0; 3], [0.0; 3]], &CancelToken::default(), &mut |_| Ok(())).is_err());
assert_eq!(extreme.pixels, before);
}
#[test]
fn dimensions_bytes_and_actual_capacity_are_checked() {
for (width, height, samples) in [(0, 1, 1), (1, 0, 1), (u32::MAX, u32::MAX, 1), (1, 1, 0), (1, 1, MAX_SAMPLES + 1)] {
assert!(FilmAccumulator::required_bytes(width, height, samples).is_err());
}
assert!(FilmAccumulator::required_bytes(MAX_DIMENSION, MAX_DIMENSION, 1).is_err());
assert!(bytes_for_capacity(usize::MAX).is_err());
let bytes = FilmAccumulator::required_bytes(2, 2, 1).unwrap();
assert!(FilmAccumulator::new(2, 2, 1, bytes - 1, &CancelToken::default(), &mut |_| Ok(())).is_err());
let film = film(2, 2, 1);
assert!(film.allocated_bytes().unwrap() <= bytes);
assert_eq!(film.allocated_bytes().unwrap(), bytes_for_capacity(film.pixels.capacity()).unwrap());
assert!(film.allocated_bytes().unwrap() >= (std::mem::size_of::<Pixel>() * (4 + MAX_UPDATE)) as u64);
}
#[test]
fn invalid_ranges_and_oversized_updates_preserve_state() {
let mut film = film(2, 1, 1);
for (start, values) in [(0, Vec::new()), (usize::MAX, vec![[1.0; 3]]), (2, vec![[1.0; 3]]), (0, vec![[1.0; 3]; MAX_UPDATE + 1])] {
assert!(film.add_range(start, &values, &CancelToken::default(), &mut |_| Ok(())).is_err());
assert!(film.pixels.iter().all(|p| *p == Pixel::default()));
}
assert!(film.pixel_statistics(2).is_err());
}
#[test]
fn incremental_partitions_preserve_bitwise_results_in_sample_order() {
let mut whole = film(4, 1, 3);
let mut partitioned = film(4, 1, 3);
for values in [
[[1.0; 3], [1e12; 3], [0.25; 3], [4.0; 3]],
[[2.0; 3], [1e12 + 1.0; 3], [0.5; 3], [2.0; 3]],
[[4.0; 3], [1e12 - 1.0; 3], [0.75; 3], [0.0; 3]],
] {
add(&mut whole, 0, &values);
add(&mut partitioned, 0, &values[..1]);
add(&mut partitioned, 1, &values[1..3]);
add(&mut partitioned, 3, &values[3..]);
}
assert_eq!(whole.pixels, partitioned.pixels);
assert_eq!(whole.pixel_statistics(1).unwrap().variance, [1.0; 3]);
}
#[test]
fn cancellation_and_work_failure_preserve_all_pixels() {
let mut film = film(2, 1, 3);
let cancel = CancelToken::default();
let observer = cancel.clone();
assert_eq!(
film.add_range(0, &[[1.0; 3]; 2], &cancel, &mut |_| {
observer.cancel();
Ok(())
})
.unwrap_err()
.code,
ErrorCode::Cancelled
);
assert!(film.pixels.iter().all(|p| *p == Pixel::default()));
let mut charged = 0;
assert_eq!(
film.add_range(0, &[[1.0; 3]; 2], &CancelToken::default(), &mut |units| {
charged += units;
if charged > 2 { Err(limit("job work exhausted")) } else { Ok(()) }
})
.unwrap_err()
.code,
ErrorCode::LimitExceeded
);
assert_eq!(charged, 4);
assert!(film.pixels.iter().all(|p| *p == Pixel::default()));
}
#[test]
fn construction_and_complete_pass_share_caller_work_and_cancel() {
let bytes = FilmAccumulator::required_bytes(2, 1, 1).unwrap();
let cancel = CancelToken::default();
cancel.cancel();
assert!(FilmAccumulator::new(2, 1, 1, bytes, &cancel, &mut |_| panic!("cancelled construction charged work")).is_err());
let mut charged = 0;
let mut film = FilmAccumulator::new(2, 1, 1, bytes, &CancelToken::default(), &mut |n| {
charged += n;
Ok(())
})
.unwrap();
assert_eq!(charged, 2);
add(&mut film, 0, &[[1.0; 3]; 2]);
assert!(film.complete_pass(&CancelToken::default(), &mut |_| Err(limit("job exhausted"))).is_err());
let pass = film
.complete_pass(&CancelToken::default(), &mut |n| {
charged += n;
Ok(())
})
.unwrap();
assert_eq!(charged, 4);
assert_eq!(pass.samples_per_pixel(), 1);
}
#[test]
fn sample_counts_reach_4096_and_the_declared_cap_without_truncation() {
for samples in [4096, MAX_SAMPLES] {
let mut film = film(1, 1, samples);
let cancel = CancelToken::default();
let mut charged = 0u64;
for _ in 0..samples {
film.add_range(0, &[[7.0, 3.0, 1.0]], &cancel, &mut |n| {
charged += n;
Ok(())
})
.unwrap();
}
assert_eq!(charged, u64::from(samples) * 2);
let expected = PixelStatistics { mean: [7.0, 3.0, 1.0], variance: [0.0; 3], count: samples };
assert_eq!(film.pixel_statistics(0).unwrap(), expected);
assert_eq!(film.complete_pass(&cancel, &mut |_| Ok(())).unwrap().samples_per_pixel(), samples);
assert_eq!(film.add_range(0, &[[1.0; 3]], &cancel, &mut |_| Ok(())).unwrap_err().code, ErrorCode::LimitExceeded);
assert_eq!(film.pixel_statistics(0).unwrap(), expected);
}
}
#[test]
fn construction_stops_on_exhausted_caller_work() {
let bytes = FilmAccumulator::required_bytes(4, 1, 1).unwrap();
let mut charged = 0u64;
let result = FilmAccumulator::new(4, 1, 1, bytes, &CancelToken::default(), &mut |n| {
charged += n;
if charged > 2 { Err(limit("existing job budget exhausted")) } else { Ok(()) }
});
assert!(matches!(result, Err(JobError { code: ErrorCode::LimitExceeded, .. })));
assert_eq!(charged, 3);
}
#[cfg(feature = "raytrace-cpu")]
#[test]
fn primary_film_large_profile_keeps_every_sample_and_cancels_before_mutation() {
use crate::film::primary::PrimaryFilm;
use crate::job::{CancelToken, CpuBudget, CpuProgressiveOptions};
let options = CpuProgressiveOptions { samples_per_pixel: 512, seed: 7 };
assert!(PrimaryFilm::required_bytes(1, 1, options, CpuBudget::Compact).is_err());
let bytes = PrimaryFilm::required_bytes(1, 1, options, CpuBudget::Studio).unwrap();
let cancel = CancelToken::default();
let mut film = PrimaryFilm::new(1, 1, options, bytes, &cancel, CpuBudget::Studio).unwrap();
film.initialize_one(&cancel, &mut || Ok(())).unwrap();
for ordinal in 0..512 {
film.add(0, ordinal, [1e12, 2.0, 0.0], true, &cancel, &mut || Ok(())).unwrap();
}
assert_eq!(film.pixel(0).unwrap(), ([1e12, 2.0, 0.0], 512, 512));
cancel.cancel();
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<PartialPixel>) {
(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));
}
}
}
}
#[cfg(feature = "raytrace-cpu")]
mod workstation_primary_counts {
use super::primary::{PartialPixel, PrimaryFilm};
use super::*;
use crate::job::{CpuBudget, CpuProgressiveOptions};
fn primary(target: u32) -> PrimaryFilm {
let options = CpuProgressiveOptions { samples_per_pixel: target, seed: 7 };
let bytes = PrimaryFilm::required_bytes(1, 1, options, CpuBudget::Workstation).unwrap();
let mut film = PrimaryFilm::new(1, 1, options, bytes, &CancelToken::default(), CpuBudget::Workstation).unwrap();
film.initialize_one(&CancelToken::default(), &mut || Ok(())).unwrap();
film
}
#[test]
fn workstation_cap_is_explicit_and_other_profiles_and_defaults_stay_fixed() {
assert_eq!(crate::job::MAX_CPU_SAMPLES_PER_PIXEL, 1_048_576);
assert_eq!(CpuBudget::Workstation.limits().max_samples_per_pixel, 1_048_576);
assert_eq!(CpuBudget::Studio.limits().max_samples_per_pixel, 1024);
assert_eq!(CpuBudget::Compact.limits().max_samples_per_pixel, 64);
assert_eq!(CpuBudget::default(), CpuBudget::Compact);
assert_eq!(CpuProgressiveOptions::default(), CpuProgressiveOptions { samples_per_pixel: 16, seed: 0 });
for samples_per_pixel in [0, 1_048_577, u32::MAX] {
assert!(CpuBudget::Workstation.validate_samples(samples_per_pixel).is_err());
}
for (budget, cap) in [(CpuBudget::Compact, 64), (CpuBudget::Studio, 1024), (CpuBudget::Workstation, 1_048_576)] {
budget.validate_samples(cap).unwrap();
assert!(budget.validate_samples(cap + 1).is_err());
}
let large = CpuProgressiveOptions { samples_per_pixel: 1_048_576, seed: 7 };
assert!(large.validate().is_err(), "the no-profile compatibility check must remain Compact");
assert!(large.validate_image(1, 1).is_err());
}
#[test]
fn high_sample_intent_keeps_camera_resolution_work_and_memory_admission() {
let limits = CpuBudget::Workstation.limits();
assert_eq!(limits.max_camera_samples, 68_719_476_736);
assert_eq!(limits.max_dimension, 16_384);
assert_eq!(limits.max_pixels, 67_108_864);
assert_eq!(limits.max_progressive_pixels, 67_108_864);
assert_eq!(limits.max_job_bytes, 12 * 1024 * 1024 * 1024);
assert_eq!(limits.max_work_units, 16_000_000_000_000);
assert_eq!(crate::job::NATIVE_CPU_POOL_BYTES, 16 * 1024 * 1024 * 1024);
let million = Some(CpuProgressiveOptions { samples_per_pixel: 1_048_576, seed: 7 });
CpuBudget::Workstation.validate_image(256, 256, million).unwrap();
assert!(CpuBudget::Workstation.validate_image(257, 256, million).is_err());
assert!(CpuBudget::Workstation.validate_image(u32::MAX, u32::MAX, million).is_err());
// Pure admission boundaries, no large image or film allocation.
for (width, height, samples) in [(1920, 1080, 33_140), (3840, 2160, 8_285), (7680, 4320, 2_071), (8192, 8192, 1024)] {
CpuBudget::Workstation.validate_image(width, height, Some(CpuProgressiveOptions { samples_per_pixel: samples, seed: 7 })).unwrap();
assert!(
CpuBudget::Workstation
.validate_image(width, height, Some(CpuProgressiveOptions { samples_per_pixel: samples + 1, seed: 7 }))
.is_err()
);
}
for budget in [CpuBudget::Studio, CpuBudget::Workstation] {
assert_eq!(budget.validate_execution().is_err(), cfg!(target_arch = "wasm32") || usize::BITS < 64);
}
CpuBudget::Compact.validate_execution().unwrap();
}
#[test]
fn one_pixel_million_sample_intent_does_not_allocate_a_sample_history() {
let low = CpuProgressiveOptions { samples_per_pixel: 1, seed: 7 };
let high = CpuProgressiveOptions { samples_per_pixel: 1_048_576, seed: 7 };
let bytes = PrimaryFilm::required_bytes(1, 1, high, CpuBudget::Workstation).unwrap();
assert_eq!(PrimaryFilm::required_bytes(1, 1, low, CpuBudget::Workstation).unwrap(), bytes);
assert!(PrimaryFilm::new(1, 1, high, bytes - 1, &CancelToken::default(), CpuBudget::Workstation).is_err());
for samples_per_pixel in [0, 1_048_577, u32::MAX] {
assert!(PrimaryFilm::required_bytes(1, 1, CpuProgressiveOptions { samples_per_pixel, seed: 7 }, CpuBudget::Workstation).is_err());
}
assert!(PrimaryFilm::required_bytes(257, 256, high, CpuBudget::Workstation).is_err());
}
#[test]
fn primary_resolve_keeps_exact_u32_counts_at_65535_65536_and_the_workstation_cap() {
// Real film commits, one pixel only: no ray tracing, PNG, host or million-frame render.
let mut film = primary(1_048_576);
let cancel = CancelToken::default();
let mut charged = 0u64;
for ordinal in 0..1_048_576 {
film.add(0, ordinal, [1.0, 2.0, 4.0], true, &cancel, &mut || {
charged += 1;
Ok(())
})
.unwrap();
let count = ordinal + 1;
if [4096, 65_535, 65_536, 1_048_576].contains(&count) {
let (mean, covered, samples): ([f64; 3], u32, u32) = film.pixel(0).unwrap();
assert_eq!(mean, [1.0, 2.0, 4.0]);
assert_eq!((covered, samples), (count, count));
assert_eq!(film.samples(), count);
assert_eq!(charged, u64::from(count));
assert_eq!(film.partial_pixel(0).unwrap(), PartialPixel::Sampled { linear_premultiplied: mean, covered: count, count });
}
}
let before = film.pixel(0).unwrap();
let frontier = film.partial_frontier().unwrap();
for ordinal in [1_048_576, 1_048_577, u32::MAX] {
assert!(film.add(0, ordinal, [0.0; 3], false, &cancel, &mut || panic!("rejected ordinal charged work")).is_err());
assert_eq!(film.pixel(0).unwrap(), before);
assert_eq!(film.partial_frontier().unwrap(), frontier);
}
}
#[test]
fn high_counts_keep_misses_in_the_mean_and_the_real_coverage_denominator() {
let mut film = primary(65_537);
let cancel = CancelToken::default();
for ordinal in 0..65_537 {
let covered = ordinal % 2 == 0;
film.add(0, ordinal, if covered { [2.0, 4.0, 8.0] } else { [0.0; 3] }, covered, &cancel, &mut || Ok(())).unwrap();
let count = ordinal + 1;
if [65_535, 65_536, 65_537].contains(&count) {
let hits = count.div_ceil(2);
let expected = [2.0, 4.0, 8.0].map(|value| value * f64::from(hits) / f64::from(count));
assert_eq!(film.pixel(0).unwrap(), (expected, hits, count));
assert_eq!(film.partial_pixel(0).unwrap(), PartialPixel::Sampled { linear_premultiplied: expected, covered: hits, count });
}
}
}
#[test]
fn high_count_cancellation_and_work_failure_preserve_the_exact_committed_film() {
let mut film = primary(65_537);
for ordinal in 0..65_536 {
film.add(0, ordinal, [1.0, 2.0, 4.0], true, &CancelToken::default(), &mut || Ok(())).unwrap();
}
let before = film.pixel(0).unwrap();
let frontier = film.partial_frontier().unwrap();
let cancelled = CancelToken::default();
cancelled.cancel();
assert_eq!(
film.add(0, 65_536, [3.0; 3], true, &cancelled, &mut || panic!("cancelled input charged work")).unwrap_err().code,
ErrorCode::Cancelled
);
let cancel = CancelToken::default();
let observer = cancel.clone();
let mut charged = 0;
assert_eq!(
film.add(0, 65_536, [3.0; 3], true, &cancel, &mut || {
charged += 1;
observer.cancel();
Ok(())
})
.unwrap_err()
.code,
ErrorCode::Cancelled
);
assert_eq!(charged, 1);
assert!(film.add(0, 65_536, [3.0; 3], true, &CancelToken::default(), &mut || Err(limit("same cumulative job exhausted"))).is_err());
assert_eq!(film.pixel(0).unwrap(), before);
assert_eq!(film.partial_frontier().unwrap(), frontier);
film.add(0, 65_536, [1.0, 2.0, 4.0], true, &CancelToken::default(), &mut || Ok(())).unwrap();
assert_eq!(film.pixel(0).unwrap(), ([1.0, 2.0, 4.0], 65_537, 65_537));
}
#[test]
fn changing_only_the_target_keeps_old_4096_prefix_bits_and_ordinals() {
let mut old_target = primary(4096);
let mut high_target = primary(1_048_576);
let cancel = CancelToken::default();
for ordinal in 0..4096 {
let covered = ordinal % 3 != 0;
let sample = if covered { [0.25, 2.0, 8.0] } else { [0.0; 3] };
old_target.add(0, ordinal, sample, covered, &cancel, &mut || Ok(())).unwrap();
high_target.add(0, ordinal, sample, covered, &cancel, &mut || Ok(())).unwrap();
let (old_mean, old_covered, old_count) = old_target.pixel(0).unwrap();
let (high_mean, high_covered, high_count) = high_target.pixel(0).unwrap();
assert_eq!(old_mean.map(f64::to_bits), high_mean.map(f64::to_bits));
assert_eq!((old_covered, old_count), (high_covered, high_count));
assert_eq!(old_target.partial_frontier().unwrap(), high_target.partial_frontier().unwrap());
}
}
}
@@ -0,0 +1,176 @@
//! Explicit CPU resource envelopes. Larger profiles are opt-in saved intent, not
//! automatic quality changes or promises about available RAM, speed or convergence.
use serde::{Deserialize, Serialize};
use super::{CpuProgressiveOptions, ErrorCode, JobError, Result};
use crate::RenderLimits;
const MIB: u64 = 1024 * 1024;
const GIB: u64 = 1024 * MIB;
/// Native CPU reservations, including retained frames, share this finite ceiling.
pub const NATIVE_CPU_POOL_BYTES: u64 = 16 * GIB;
/// Hard implementation ceilings; individual requests retain their selected envelope.
pub const MAX_CPU_WORK: u64 = 16_000_000_000_000;
pub const MAX_CPU_TRIANGLES: usize = 8_000_000;
pub const MAX_CPU_BODIES: usize = 262_144;
/// Maximum admitted primary-film samples, shared with the display resolver.
pub const MAX_CPU_SAMPLES_PER_PIXEL: u32 = 1_048_576;
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "snake_case")]
pub enum CpuBudget {
#[default]
Compact,
Studio,
Workstation,
}
#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize)]
pub struct CpuBudgetLimits {
pub max_dimension: u64,
pub max_pixels: u64,
pub max_progressive_pixels: u64,
pub max_samples_per_pixel: u32,
pub max_camera_samples: u64,
pub max_triangles: u64,
pub max_bodies: usize,
pub max_geometry_bytes: u64,
pub max_job_bytes: u64,
pub max_work_units: u64,
}
impl CpuBudget {
pub const ALL: [Self; 3] = [Self::Compact, Self::Studio, Self::Workstation];
pub fn is_compact(&self) -> bool {
*self == Self::Compact
}
pub const fn limits(self) -> CpuBudgetLimits {
match self {
Self::Compact => CpuBudgetLimits {
max_dimension: 4096,
max_pixels: 4_194_304,
max_progressive_pixels: 1_048_576,
max_samples_per_pixel: 64,
max_camera_samples: 16_777_216,
max_triangles: super::image::MAX_TRIANGLES,
max_bodies: 16_384,
max_geometry_bytes: super::image::MAX_GEOMETRY_BYTES,
max_job_bytes: super::image::MAX_JOB_BYTES,
max_work_units: 1_000_000_000,
},
Self::Studio => CpuBudgetLimits {
max_dimension: 8192,
max_pixels: 16_777_216,
max_progressive_pixels: 16_777_216,
max_samples_per_pixel: 1024,
max_camera_samples: 4_294_967_296,
max_triangles: 2_000_000,
max_bodies: 65_536,
max_geometry_bytes: GIB,
max_job_bytes: 3 * GIB,
max_work_units: 1_000_000_000_000,
},
Self::Workstation => CpuBudgetLimits {
max_dimension: 16_384,
max_pixels: 67_108_864,
max_progressive_pixels: 67_108_864,
max_samples_per_pixel: MAX_CPU_SAMPLES_PER_PIXEL,
max_camera_samples: 68_719_476_736,
max_triangles: MAX_CPU_TRIANGLES as u64,
max_bodies: MAX_CPU_BODIES,
max_geometry_bytes: 4 * GIB,
max_job_bytes: 12 * GIB,
max_work_units: MAX_CPU_WORK,
},
}
}
pub fn image_limits(self, progressive: bool) -> RenderLimits {
let limits = self.limits();
RenderLimits {
max_dimension: limits.max_dimension,
max_pixels: if progressive { limits.max_progressive_pixels } else { limits.max_pixels },
max_scratch_bytes: limits.max_job_bytes,
}
}
pub fn validate_samples(self, samples: u32) -> Result<()> {
let maximum = self.limits().max_samples_per_pixel;
if samples == 0 || samples > maximum {
return Err(JobError::new(ErrorCode::InvalidRequest, format!("CPU {self:?} samples_per_pixel must be 1..{maximum}")));
}
Ok(())
}
/// No geometry reads or allocations. This also validates offline saved intent.
pub fn validate_image(self, width: u32, height: u32, progressive: Option<CpuProgressiveOptions>) -> Result<()> {
let (w, h) = (u64::from(width), u64::from(height));
let limits = self.image_limits(progressive.is_some());
let pixels = w.checked_mul(h).ok_or_else(|| JobError::new(ErrorCode::LimitExceeded, "CPU pixel count overflow"))?;
if w == 0 || h == 0 || w > limits.max_dimension || h > limits.max_dimension || pixels > limits.max_pixels {
return Err(JobError::new(
ErrorCode::LimitExceeded,
format!(
"CPU {self:?} accepts dimensions 1..{} and at most {} pixels; select a larger resource profile explicitly",
limits.max_dimension, limits.max_pixels
),
));
}
if let Some(options) = progressive {
self.validate_samples(options.samples_per_pixel)?;
if pixels.checked_mul(u64::from(options.samples_per_pixel)).is_none_or(|n| n > self.limits().max_camera_samples) {
return Err(JobError::new(
ErrorCode::LimitExceeded,
format!("CPU {self:?} exceeds its {} camera-sample admission", self.limits().max_camera_samples),
));
}
}
Ok(())
}
/// A file may preserve large intent on every platform; only execution needs
/// the native 64-bit address space. No implicit downgrade to Compact occurs.
pub fn validate_execution(self) -> Result<()> {
if self != Self::Compact && (cfg!(target_arch = "wasm32") || usize::BITS < 64) {
return Err(JobError::new(ErrorCode::HostUnavailable, "large CPU profiles require a native 64-bit host"));
}
Ok(())
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn large_intent_is_explicit_and_old_intent_remains_compact() {
assert_eq!(CpuBudget::default(), CpuBudget::Compact);
let p = Some(CpuProgressiveOptions { samples_per_pixel: 128, seed: 9 });
assert!(CpuBudget::Compact.validate_image(3840, 2160, p).is_err());
assert!(CpuBudget::Studio.validate_image(3840, 2160, p).is_ok());
assert!(CpuBudget::Studio.validate_image(7680, 4320, p).is_err());
assert!(CpuBudget::Workstation.validate_image(7680, 4320, p).is_ok());
assert_eq!(serde_json::from_str::<CpuBudget>("\"workstation\"").unwrap(), CpuBudget::Workstation);
assert!(serde_json::from_str::<CpuBudget>("\"unlimited\"").is_err());
}
#[test]
fn all_envelopes_have_checked_finite_bounds_and_no_automatic_resize() {
for budget in CpuBudget::ALL {
let limits = budget.limits();
assert!(limits.max_geometry_bytes < limits.max_job_bytes);
assert!(limits.max_job_bytes < NATIVE_CPU_POOL_BYTES);
assert!(limits.max_work_units <= MAX_CPU_WORK);
assert!(budget.validate_image(0, 1, None).is_err());
assert!(budget.validate_image(u32::MAX, u32::MAX, None).is_err());
assert!(budget.validate_samples(0).is_err());
assert!(budget.validate_samples(limits.max_samples_per_pixel + 1).is_err());
assert!(budget.validate_samples(limits.max_samples_per_pixel).is_ok());
}
let p = Some(CpuProgressiveOptions { samples_per_pixel: 4096, seed: 0 });
assert!(CpuBudget::Workstation.validate_image(8192, 8192, p).is_err());
assert!(CpuBudget::Workstation.validate_image(3840, 2160, p).is_ok());
}
}
@@ -0,0 +1,371 @@
//! Transient CPU Interactive scheduling. The UI adapter owns visual revisions;
//! this controller owns cancellation, not document settings or final-image export.
use std::time::Duration;
use super::{CpuProgressiveOptions, ErrorCode, ImageRequest, Integrator, JobError, JobHandle, JobId, Phase, Result};
const SETTLE: Duration = Duration::from_millis(200);
const MAX_EDGE: u32 = 1024;
/// Prepare a separate low-resolution request. Never edits the final request,
/// changes renderer, removes optics/lights, or promises geometry admission.
pub fn cpu_request(final_request: &ImageRequest) -> Result<ImageRequest> {
final_request.validate_raster_request()?;
if final_request.integrator != Integrator::Raytrace || final_request.transparent_background {
return Err(JobError::new(ErrorCode::InvalidRequest, "Interactive CPU requires opaque ray tracing"));
}
let (width, height) = (final_request.width, final_request.height);
if width == 0 || height == 0 {
return Err(JobError::new(ErrorCode::InvalidRequest, "Interactive output dimensions must be positive"));
}
if let Some(options) = &final_request.raytrace {
options.validate()?;
}
let edge = width.max(height);
let fit = |side: u32| {
if edge <= MAX_EDGE { side } else { ((u64::from(side) * u64::from(MAX_EDGE) + u64::from(edge) / 2) / u64::from(edge)).max(1) as u32 }
};
let mut request = final_request.clone();
request.width = fit(width);
request.height = fit(height);
let options = request.raytrace.get_or_insert_default();
options.primary_samples = 1;
// Preserve explicit accumulation intent, including its deterministic seed.
// Fixed-image callers keep the original preview default. Incompatible
// transport remains an error rather than silently removing requested effects.
options.progressive.get_or_insert_with(CpuProgressiveOptions::default);
if let Some(reflections) = &mut options.reflections {
reflections.samples = 1;
}
options.validate()?;
options.budget.validate_image(request.width, request.height, options.progressive)?;
Ok(request)
}
/// Caller increments visual_revision for every camera/draft/appearance/light/HDR
/// or output edit, even if scene_generation did not change. Never use only a CAD
/// revision, a body name, or the selected setup name as the visual identity.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub struct VisualRevision {
pub scene_generation: u64,
pub visual_revision: u64,
}
/// Issued only after the edit group settles. Private fields prevent fabricating
/// a ticket for a newer request from a delayed capture.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub struct CaptureTicket {
session: u64,
serial: u64,
revision: VisualRevision,
}
impl CaptureTicket {
pub fn revision(self) -> VisualRevision {
self.revision
}
/// Submit this identity to the preview host, outside the final-job registry.
pub fn job_id(self) -> JobId {
JobId { session: self.session, serial: self.serial, generation: self.serial }
}
}
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum State {
Off,
Updating,
Refining,
Paused,
TargetReached,
Error,
}
/// One controller per document session. No serialization, clocks, threads, scene
/// extraction or new renderer here. Supply monotonic elapsed time from the host;
/// this keeps both browser integration and deterministic event tests possible.
pub struct Interactive {
session: u64,
serial: u64,
revision: Option<VisualRevision>,
changed_at: Duration,
enabled: bool,
paused: bool,
final_active: bool,
ticket: Option<CaptureTicket>,
active: Option<JobHandle>,
error: Option<JobError>,
}
impl Interactive {
pub fn new(session: u64) -> Self {
Self {
session,
serial: 0,
revision: None,
changed_at: Duration::ZERO,
enabled: false,
paused: false,
final_active: false,
ticket: None,
active: None,
error: None,
}
}
fn cancel(&mut self) -> Result<()> {
// Invalidate first, including when a poisoned host refuses cancellation.
self.ticket = None;
if let Some(job) = self.active.take() {
job.cancel()?;
}
Ok(())
}
/// Explicit user activation. Merely entering Render must not call this.
pub fn enable(&mut self, revision: VisualRevision, now: Duration) -> Result<()> {
self.cancel()?;
self.enabled = true;
self.paused = false;
self.error = None;
self.revision = Some(revision);
self.changed_at = now;
Ok(())
}
/// Workspace/document departure uses disable; manually started final jobs
/// are deliberately outside this controller and are never cancelled here.
pub fn disable(&mut self) -> Result<()> {
self.enabled = false;
self.paused = false;
self.error = None;
self.cancel()
}
pub fn edit(&mut self, revision: VisualRevision, now: Duration) -> Result<()> {
if self.revision != Some(revision) {
self.revision = Some(revision);
self.changed_at = now;
self.error = None;
self.cancel()?;
}
Ok(())
}
/// A view may retain an identified immutable PNG before pausing, but must
/// label it paused/stale. It is never a current or exportable final image.
pub fn pause(&mut self) -> Result<()> {
self.paused = true;
self.cancel()
}
pub fn resume(&mut self, now: Duration) -> Result<()> {
self.cancel()?;
self.paused = false;
self.error = None;
self.changed_at = now;
Ok(())
}
pub fn set_final_active(&mut self, active: bool, now: Duration) -> Result<()> {
if self.final_active != active {
self.final_active = active;
self.changed_at = now;
self.cancel()?;
}
Ok(())
}
/// At most one unacknowledged capture; no queue of obsolete requests.
pub fn capture(&mut self, now: Duration) -> Result<Option<CaptureTicket>> {
if !self.enabled
|| self.paused
|| self.final_active
|| self.ticket.is_some()
|| self.error.is_some()
|| now.checked_sub(self.changed_at).is_none_or(|elapsed| elapsed < SETTLE)
{
return Ok(None);
}
let Some(revision) = self.revision else { return Ok(None) };
self.serial = self.serial.checked_add(1).ok_or_else(|| JobError::new(ErrorCode::LimitExceeded, "Interactive capture identity exhausted"))?;
let ticket = CaptureTicket { session: self.session, serial: self.serial, revision };
self.ticket = Some(ticket);
Ok(Some(ticket))
}
/// Recheck before expensive capture/admission, including after a worker delay.
/// A ticket is not permission to prepare an obsolete or already adopted job.
pub fn accepts_capture(&self, ticket: CaptureTicket) -> bool {
self.enabled && !self.paused && !self.final_active && self.error.is_none() && self.ticket == Some(ticket) && self.active.is_none()
}
/// Attach an admitted preview-only job after immutable capture. Delayed jobs
/// are cancelled, including a previous ticket for the same visual revision.
/// Use a separate engine job session/registry from final-image export.
pub fn attach(&mut self, ticket: CaptureTicket, job: JobHandle) -> Result<bool> {
// A misrouted callback must never cancel another document's work or a
// manual final job. Only our dedicated preview session is ours to stop.
if job.id().session != self.session {
self.capture_failed(ticket, JobError::new(ErrorCode::WrongOwner, "Interactive job belongs to another session"));
return Ok(false);
}
if self.ticket != Some(ticket) || ticket.session != self.session {
// Protect an admitted current capture even before acknowledgement.
// Once accepted, only the same record (not merely its JobId) is ours.
let current = match &self.active {
Some(active) => active.same_record(&job),
None => self.ticket.is_some_and(|ticket| ticket.job_id() == job.id()),
};
if !current {
job.cancel()?;
}
return Ok(false);
}
let status = job.status()?;
if status.job != ticket.job_id() || status.scene_generation != ticket.revision.scene_generation {
job.cancel()?;
self.capture_failed(ticket, JobError::new(ErrorCode::WrongOwner, "Interactive job capture identity mismatch"));
return Ok(false);
}
if status.request.integrator != Integrator::Raytrace || status.request.raytrace.as_ref().is_none_or(|options| options.progressive.is_none()) {
job.cancel()?;
self.capture_failed(ticket, JobError::new(ErrorCode::InvalidRequest, "Interactive requires a CPU progressive job"));
return Ok(false);
}
// A ticket is acknowledged exactly once, even if the same capture is
// delivered twice while an earlier attached job is still running.
if self.active.is_some() {
if self.active.as_ref().is_none_or(|active| !active.same_record(&job)) {
job.cancel()?;
}
return Ok(false);
}
self.active = Some(job);
Ok(true)
}
pub fn capture_failed(&mut self, ticket: CaptureTicket, error: JobError) {
if self.ticket == Some(ticket) && self.active.is_none() {
self.ticket = None;
self.error = Some(error);
}
}
/// Access only the current capture. The adapter reads checkpoint/final bytes
/// through this handle, displaying both as Interactive/provisional content.
pub fn current(&self) -> Option<&JobHandle> {
self.active.as_ref()
}
pub fn error(&self) -> Option<&JobError> {
self.error.as_ref()
}
pub fn state(&self) -> Result<State> {
if !self.enabled {
return Ok(State::Off);
}
if self.paused || self.final_active {
return Ok(State::Paused);
}
if self.error.is_some() {
return Ok(State::Error);
}
if let Some(job) = &self.active {
return Ok(match job.status()?.progress.phase {
Phase::Completed => State::TargetReached,
Phase::Cancelled | Phase::Failed => State::Error,
_ => State::Refining,
});
}
Ok(State::Updating)
}
}
impl Drop for Interactive {
fn drop(&mut self) {
let _ = self.cancel();
}
}
#[cfg(test)]
mod tests {
use super::*;
use crate::job::{CpuBudget, RaytraceOptions};
fn request(options: RaytraceOptions) -> ImageRequest {
ImageRequest {
raster_punctual_lights: None,
raster_area_lights: None,
raster_exposure_ev: 0.0,
raster_lights: None,
studio_weights: None,
integrator: Integrator::Raytrace,
raytrace: Some(options),
textures: None,
environment: None,
camera: Default::default(),
width: 81,
height: 53,
background: [40, 80, 120],
transparent_background: false,
}
}
#[test]
fn explicit_progressive_target_and_seed_survive_interactive_conversion() {
for (budget, samples) in [(CpuBudget::Compact, 31), (CpuBudget::Studio, 997), (CpuBudget::Workstation, 1_048_576)] {
let mut source = request(RaytraceOptions {
budget,
progressive: Some(CpuProgressiveOptions { samples_per_pixel: samples, seed: u32::MAX }),
primary_samples: 1,
exposure_ev: -2.0,
shadows: false,
..Default::default()
});
// The high target still obeys P*SPP admission; no implicit resize/profile.
if budget == CpuBudget::Workstation {
source.width = 3840;
source.height = 1;
}
let before = serde_json::to_value(&source).unwrap();
let converted = cpu_request(&source).unwrap();
let mut expected = source.clone();
if budget == CpuBudget::Workstation {
expected.width = 1024;
}
assert_eq!(serde_json::to_value(converted).unwrap(), serde_json::to_value(expected).unwrap());
assert_eq!(serde_json::to_value(&source).unwrap(), before);
}
}
#[test]
fn fixed_interactive_keeps_original_default_and_invalid_explicit_intent_refuses() {
let source = request(RaytraceOptions { primary_samples: 16, ..Default::default() });
let converted = cpu_request(&source).unwrap();
let options = converted.raytrace.unwrap();
assert_eq!(options.progressive, Some(CpuProgressiveOptions { samples_per_pixel: 16, seed: 0 }));
assert_eq!(options.primary_samples, 1);
assert!(source.raytrace.as_ref().unwrap().progressive.is_none());
for (budget, samples) in [(CpuBudget::Compact, 65), (CpuBudget::Studio, 1025), (CpuBudget::Workstation, 1_048_577)] {
let invalid = request(RaytraceOptions {
budget,
primary_samples: 1,
progressive: Some(CpuProgressiveOptions { samples_per_pixel: samples, seed: 741 }),
..Default::default()
});
let before = serde_json::to_value(&invalid).unwrap();
assert!(cpu_request(&invalid).is_err());
assert_eq!(serde_json::to_value(&invalid).unwrap(), before);
}
let mut over_work = request(RaytraceOptions {
primary_samples: 1,
progressive: Some(CpuProgressiveOptions { samples_per_pixel: 64, seed: 741 }),
..Default::default()
});
over_work.width = 1024;
over_work.height = 1024;
assert!(cpu_request(&over_work).is_err(), "do not reduce the explicit target to fit the profile");
}
}
@@ -0,0 +1,309 @@
use super::*;
use crate::lighting::{HdrSource, environment_input::EnvironmentInput};
use solidcraft_geom::{Aabb3, Mesh};
use std::sync::Arc;
fn input() -> EnvironmentInput {
let mut bytes = b"#?RADIANCE\nFORMAT=32-bit_rle_rgbe\nPRIMARIES=0.64 0.33 0.30 0.60 0.15 0.06 0.3127 0.3290\n\n-Y 2 +X 4\n".to_vec();
for _ in 0..8 {
bytes.extend_from_slice(&[128, 64, 32, 129]);
}
EnvironmentInput::new(HdrSource::new(bytes).unwrap(), 0.0, 1.0, 64).unwrap()
}
fn scene() -> ProductScene {
let mesh = Arc::new(Mesh {
positions: vec![Vec3::new(-10.0, -10.0, 0.0), Vec3::new(10.0, -10.0, 0.0), Vec3::new(10.0, 10.0, 0.0), Vec3::new(-10.0, 10.0, 0.0)],
normals: vec![Vec3::Z; 4],
triangles: vec![[0, 1, 2], [0, 2, 3]],
tri_face: vec![0, 0],
..Default::default()
});
ProductScene {
bounds: mesh.bounds(),
meshes: vec![crate::ProductMesh {
transmission: None,
name: "Original conductor plate".into(),
mesh,
color: [255; 3],
opacity: 1.0,
surface: Some(OpaqueSurface::new(Vec3::new(1.0, 1.0, 1.0), 1.0, 1.0, 1.5).unwrap()),
faces: Vec::new(),
}],
}
}
fn request() -> ImageRequest {
let mut camera = crate::Camera { distance: 50.0, ..Default::default() };
camera.set_view(crate::StandardView::Top);
ImageRequest {
raster_punctual_lights: None,
raster_area_lights: None,
raster_exposure_ev: 0.0,
raster_lights: None,
studio_weights: None,
environment: None,
textures: None,
integrator: job::Integrator::Raytrace,
raytrace: Some(RaytraceOptions { lights: Some(Vec::new()), ..Default::default() }),
camera,
width: 9,
height: 9,
background: [13, 27, 41],
transparent_background: false,
}
}
fn png(source: ProductScene, environment: Option<EnvironmentInput>) -> Vec<u8> {
let request = request();
let options = request.raytrace.clone().unwrap();
let mut task = ImageTask::new_with_environment(source, request, CancelToken::default(), options, environment).unwrap();
for _ in 0..200_000 {
if let TaskPoll::Complete(png) = task.step(16384).unwrap() {
return png;
}
}
panic!("bounded environment fixture did not complete");
}
#[test]
fn real_cpu_png_conductor_matches_independent_environment_quadrature_once() {
let baseline = ::image::load_from_memory(&png(scene(), None)).unwrap().to_rgba8();
let rendered = png(scene(), Some(input()));
assert_eq!(rendered, png(scene(), Some(input())));
let image = ::image::load_from_memory(&rendered).unwrap().to_rgba8();
// Independent roughness-one white-conductor f*cos= z/(2*pi*(1+z)).
// The fixed 8x8 solid-angle strata integrate 4 positive z rows, each 8 samples.
let factor = [0.125, 0.375, 0.625, 0.875].into_iter().map(|z| z / (1.0 + z)).sum::<f64>() / 4.0;
let expected = [factor, factor * 0.5, factor * 0.25].map(|r| encode8(r / (1.0 + r)));
assert_eq!(image.get_pixel(4, 4).0, [expected[0], expected[1], expected[2], 255]);
assert_eq!(baseline.get_pixel(4, 4).0, [0, 0, 0, 255]);
let empty = ProductScene { meshes: Vec::new(), bounds: Aabb3::EMPTY };
let background = ::image::load_from_memory(&png(empty, Some(input()))).unwrap().to_rgba8();
assert!(background.pixels().all(|p| p.0 == [13, 27, 41, 255]));
}
struct ProgressiveHdrResult {
previews: Vec<(u32, Vec<u8>)>,
png: Vec<u8>,
work: u64,
}
fn progressive_hdr_png(samples_per_pixel: u32, seed: u32, quantum: usize, environment: Option<EnvironmentInput>) -> ProgressiveHdrResult {
let mut request = request();
let mut options = request.raytrace.clone().unwrap();
options.progressive = Some(job::CpuProgressiveOptions { samples_per_pixel, seed });
options.reflections = Some(job::ReflectionOptions {
bodies: vec![job::ReflectionBody { body: "Original conductor plate".into(), mode: job::ReflectionMode::RoughSpecular }],
samples: 1,
max_bounces: 2,
});
request.raytrace = Some(options.clone());
let mut task = ImageTask::new_with_environment(scene(), request, CancelToken::default(), options, environment).unwrap();
let mut previews = Vec::new();
for _ in 0..300_000 {
match task.step_with_previews(quantum).unwrap() {
ImagePoll::Pending(_) => {}
ImagePoll::Preview { png, samples_per_pixel } => previews.push((samples_per_pixel, png)),
ImagePoll::Complete(png) => return ProgressiveHdrResult { previews, png, work: task.work.used() },
}
}
panic!("bounded progressive HDR fixture did not finish");
}
fn progressive_hdr_expected(samples: u32, seed: u32) -> [u8; 4] {
// Independent normal-view, white-conductor reference at roughness one.
// The centre pixel (40) stays inside the plate for every camera jitter.
// GGX gives z = 1 - 2*u and weight = 2*z/(1+z) for z > 0; other
// attempts are null events, not replacement samples. Only the variate
// sequence is shared with production: no BSDF, PDF or film code is used.
let sum: f64 = (0..samples)
.map(|ordinal| {
let z = 1.0 - 2.0 * progressive::variates(seed, 40, ordinal, 0x100)[0];
if z > 0.0 { 2.0 * z / (1.0 + z) } else { 0.0 }
})
.sum();
let mean = sum / f64::from(samples);
// The original HDR is constant linear RGB (1, 0.5, 0.25). Average in
// linear space over ALL attempts, then apply the display response once.
let rgb = [mean, mean * 0.5, mean * 0.25].map(|r| encode8(r / (1.0 + r)));
[rgb[0], rgb[1], rgb[2], 255]
}
fn centre(png: &[u8]) -> [u8; 4] {
::image::load_from_memory(png).unwrap().to_rgba8().get_pixel(4, 4).0
}
#[test]
fn progressive_hdr_and_rough_reflections_keep_the_same_absolute_prefix_at_every_quantum() {
for (target, checkpoints) in [(3, vec![1, 2]), (7, vec![1, 2, 3, 4, 5, 6])] {
let result = progressive_hdr_png(target, 82, 1, Some(input()));
assert_eq!(result.previews.iter().map(|(n, _)| *n).collect::<Vec<_>>(), checkpoints);
let other = progressive_hdr_png(target, 82, 16384, Some(input()));
assert_eq!(result.previews, other.previews);
assert_eq!(result.png, other.png);
assert_eq!(result.work, other.work);
for (samples, checkpoint) in result.previews {
assert_eq!(progressive_hdr_png(samples, 82, 3, Some(input())).png, checkpoint);
assert_eq!(centre(&checkpoint), progressive_hdr_expected(samples, 82));
}
assert_eq!(centre(&result.png), progressive_hdr_expected(target, 82));
}
}
#[test]
fn progressive_hdr_rough_reflections_count_null_events_in_the_linear_mean() {
// Preserve the previously failing seed rather than picking a brighter one:
// its first three attempts are all null, and later attempts receive HDR.
assert_eq!(progressive_hdr_expected(3, 82), [0, 0, 0, 255]);
assert_ne!(progressive_hdr_expected(7, 82), [0, 0, 0, 255]);
for seed in [0, 82, u32::MAX] {
for samples in [1, 3, 7] {
let result = progressive_hdr_png(samples, seed, 37, Some(input()));
assert_eq!(centre(&result.png), progressive_hdr_expected(samples, seed), "seed={seed}, samples={samples}");
let image = ::image::load_from_memory(&result.png).unwrap().to_rgba8();
assert_eq!(image.get_pixel(0, 0).0, [13, 27, 41, 255], "HDR must not replace the display background");
let unlit = progressive_hdr_png(samples, seed, 37, None);
assert_eq!(centre(&unlit.png), [0, 0, 0, 255], "no direct lights or environment means zero radiance");
}
}
}
#[test]
fn environment_decode_and_secondary_visibility_share_cancellation_and_work_budget() {
for during_visibility in [false, true] {
let request = request();
let options = request.raytrace.clone().unwrap();
let cancel = CancelToken::default();
let mut task = ImageTask::new_with_environment(scene(), request, cancel.clone(), options, Some(input())).unwrap();
if during_visibility {
for _ in 0..100_000 {
assert!(matches!(task.step(1).unwrap(), TaskPoll::Pending(_)));
if task.pending.as_ref().is_some_and(|p| p.environment_cursor.is_some()) {
break;
}
}
assert!(task.pending.as_ref().is_some_and(|p| p.environment_cursor.is_some()));
}
// Cancellation must win before any image publication, including decode preparation.
cancel.cancel();
assert_eq!(task.step(1).err().unwrap().code, ErrorCode::Cancelled);
}
let request = request();
let options = request.raytrace.clone().unwrap();
let mut task = ImageTask::new_with_environment(scene(), request, CancelToken::default(), options, Some(input())).unwrap();
task.work = WorkBudget::new(1).unwrap();
assert!(matches!(task.step(1).unwrap(), TaskPoll::Pending(_)));
assert_eq!(task.step(1).err().unwrap().code, ErrorCode::LimitExceeded);
}
#[cfg(not(target_arch = "wasm32"))]
#[test]
fn native_host_captured_source_completes_and_releases_work_lease() {
let host = job::CpuHost::for_platform().unwrap();
assert!(host.descriptor_for(job::Integrator::Raytrace).unwrap().profiles[0].features.contains(&crate::RenderFeature::Hdri));
assert!(!host.descriptor_for(job::Integrator::Raster).unwrap().profiles[0].features.contains(&crate::RenderFeature::Hdri));
let handle = host.submit_with_environment(job::JobId { session: 1693, serial: 1, generation: 1 }, 1, scene(), request(), Some(input())).unwrap();
assert_eq!(handle.wait_timeout(std::time::Duration::from_secs(60)).unwrap().progress.phase, Phase::Completed);
let frame = handle.frame().unwrap().unwrap();
assert!(host.admitted_bytes() >= frame.png().len() as u64 + 1024);
drop(host);
drop(frame);
drop(handle);
}
#[test]
fn environment_visibility_respects_four_work_units_per_quantum_and_cancel() {
let request = request();
let options = request.raytrace.clone().unwrap();
let cancel = CancelToken::default();
let mut task = ImageTask::new_with_environment(scene(), request, cancel.clone(), options, Some(input())).unwrap();
for _ in 0..100_000 {
assert!(matches!(task.step(1).unwrap(), TaskPoll::Pending(_)));
if task.pending.as_ref().is_some_and(|p| p.environment_cursor.is_some()) {
break;
}
}
assert!(task.pending.as_ref().is_some_and(|p| p.environment_cursor.is_some()));
for _ in 0..32 {
let before = task.work.used();
assert!(matches!(task.step(4).unwrap(), TaskPoll::Pending(_)));
assert!(task.work.used() - before <= 4, "visibility continuation double-charged shading and traversal");
}
cancel.cancel();
assert_eq!(task.step(4).err().unwrap().code, ErrorCode::Cancelled);
}
#[test]
fn all_pixel_traversal_to_shading_transitions_debit_at_most_one_unit() {
for (directional, shadows) in [(false, true), (true, true), (true, false)] {
let mut request = request();
let mut options = request.raytrace.clone().unwrap();
options.shadows = shadows;
if directional {
options.lights = Some(vec![job::DirectionalLightOptions { direction: [0.0, 0.0, 1.0], color: [1.0; 3], intensity: 1.0 }]);
}
request.raytrace = Some(options.clone());
let cancel = CancelToken::default();
let mut task = ImageTask::new_with_environment(scene(), request, cancel.clone(), options, Some(input())).unwrap();
while task.bvh.is_none() {
assert!(matches!(task.step(1).unwrap(), TaskPoll::Pending(_)));
}
let mut primary_transitions = 0;
let mut directional_transitions = 0;
for _ in 0..200_000 {
if task.pixel == 81 {
break;
}
let primary = task.pending.as_ref().is_some_and(|p| p.hit.is_none());
let light_before = task.pending.as_ref().map(|p| p.light);
let before = task.work.used();
task.pixel_one().unwrap();
assert!(task.work.used() - before <= 1, "traversal completion must yield before shading/sample debit");
if primary && task.pending.as_ref().is_some_and(|p| p.hit.is_some()) {
primary_transitions += 1;
}
if light_before == Some(0) && task.pending.as_ref().is_some_and(|p| p.light == 1) {
directional_transitions += 1;
}
}
assert_eq!(task.pixel, 81);
assert!(primary_transitions > 0);
if directional && shadows {
assert!(directional_transitions > 0);
}
cancel.cancel();
assert_eq!(task.step(4).err().unwrap().code, ErrorCode::Cancelled);
}
}
#[test]
fn explicit_cpu_profiles_admit_large_images_without_allocating_a_film() {
let empty = ProductScene { meshes: Vec::new(), bounds: Aabb3::EMPTY };
let mut request = request();
request.width = 3840;
request.height = 2160;
let mut options = request.raytrace.clone().unwrap();
options.progressive = Some(job::CpuProgressiveOptions { samples_per_pixel: 128, seed: 9 });
request.raytrace = Some(options.clone());
assert!(admit(&empty, &request, &options).is_err());
if usize::BITS < 64 || cfg!(target_arch = "wasm32") {
return;
}
options.budget = job::CpuBudget::Studio;
request.raytrace = Some(options.clone());
let studio = admit(&empty, &request, &options).unwrap();
assert!(studio.estimated_total_bytes > 384 * 1024 * 1024);
assert!(studio.estimated_total_bytes < options.budget.limits().max_job_bytes);
request.width = 7680;
request.height = 4320;
assert!(admit(&empty, &request, &options).is_err());
options.budget = job::CpuBudget::Workstation;
request.raytrace = Some(options.clone());
let workstation = admit(&empty, &request, &options).unwrap();
assert!(workstation.estimated_total_bytes > studio.estimated_total_bytes);
assert!(workstation.estimated_total_bytes < options.budget.limits().max_job_bytes);
for budget in [job::CpuBudget::Studio, job::CpuBudget::Workstation] {
let count = budget.limits().max_triangles as usize;
let bytes = BvhBuilder::required_bytes(count, count, limits(budget)).unwrap();
assert!(bytes < budget.limits().max_job_bytes);
}
assert!(BvhBuilder::required_bytes(2_000_000, 2_000_000, limits(job::CpuBudget::Compact)).is_err());
}
@@ -0,0 +1,456 @@
//! Optional original CPU visibility core and opaque direct-image integration.
//!
//! Original Rust implementation from elementary slab, barycentric and binary-tree
//! mathematics. Geometry is already world-space, in millimetres. No B-rep kernel
//! or third-party ray-tracer implementation is used. See `docs/render-raytrace-core.md`.
use crate::job::CancelToken;
use solidcraft_geom::Vec3;
mod anisotropic_faces;
pub mod area;
mod bvh;
pub mod dielectric;
pub mod emission;
pub mod image;
pub mod lighting;
pub mod prepared;
mod progressive;
pub mod punctual;
pub mod reflection;
pub use bvh::{BuildLimits, BuildProgress, Bvh, BvhBuilder, MAX_DEPTH, MAX_MEMORY_BYTES, MAX_TRIANGLES};
/// Finite coordinate admission, not a CAD accuracy guarantee.
pub const MAX_COORDINATE_MM: f64 = 1e12;
/// Maximum finite ray interval endpoint in millimetres.
pub const MAX_DISTANCE_MM: f64 = 4e12;
/// Maximum work charged to one explicitly owned budget.
pub const MAX_WORK: u64 = 1_000_000_000;
/// Maximum incremental builder operations in one call.
pub const MAX_BUILD_STEP: usize = 4096;
/// Structured failures; exhausting work never returns a truncated hit result.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum TraceError {
InvalidInput(&'static str),
MemoryLimit,
AllocationFailed,
WorkLimit,
Cancelled,
BuildIncomplete,
Internal(&'static str),
}
impl std::fmt::Display for TraceError {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
match self {
Self::InvalidInput(reason) => write!(f, "invalid ray tracing input: {reason}"),
Self::MemoryLimit => f.write_str("ray tracing memory admission exceeded"),
Self::AllocationFailed => f.write_str("ray tracing allocation failed"),
Self::WorkLimit => f.write_str("ray tracing work budget exhausted"),
Self::Cancelled => f.write_str("ray tracing cancelled"),
Self::BuildIncomplete => f.write_str("ray tracing BVH build is incomplete"),
Self::Internal(reason) => write!(f, "invalid ray tracing internal state: {reason}"),
}
}
}
impl std::error::Error for TraceError {}
pub type Result<T> = std::result::Result<T, TraceError>;
fn check_cancel(cancel: &CancelToken) -> Result<()> {
if cancel.is_cancelled() { Err(TraceError::Cancelled) } else { Ok(()) }
}
/// Caller-owned cumulative work; can span many rays in one image job.
#[derive(Debug)]
pub struct WorkBudget {
limit: u64,
used: u64,
protected: Option<ProtectedWork>,
}
/// One owned ledger, not another spendable budget. Keeping the policy and actual
/// counters here preserves the final report after the image task drops its film.
#[derive(Debug)]
struct ProtectedWork {
plan: crate::job::ProtectedPreviewPlan,
ordinary_used: u64,
presentation_used: u64,
presentation_limit: u64,
aggregate_limit: u64,
accepted_snapshots: u32,
next_milestone_index: u32,
}
impl WorkBudget {
pub fn new(limit: u64) -> Result<Self> {
if limit == 0 || limit > crate::job::MAX_CPU_WORK {
return Err(TraceError::InvalidInput("work limit outside 1..=MAX_WORK"));
}
Ok(Self { limit, used: 0, protected: None })
}
pub(crate) fn new_protected(plan: crate::job::ProtectedPreviewPlan) -> Result<Self> {
plan.validate().map_err(|_| TraceError::InvalidInput("invalid protected feedback plan"))?;
let presentation_limit = plan.presentation_limit().map_err(|_| TraceError::WorkLimit)?;
let aggregate_limit = plan.aggregate_limit().map_err(|_| TraceError::WorkLimit)?;
if aggregate_limit > crate::job::MAX_PROTECTED_CPU_WORK {
return Err(TraceError::WorkLimit);
}
Ok(Self {
limit: plan.ordinary_limit(),
used: 0,
protected: Some(ProtectedWork {
plan,
ordinary_used: 0,
presentation_used: 0,
presentation_limit,
aggregate_limit,
accepted_snapshots: 0,
next_milestone_index: 0,
}),
})
}
pub fn used(&self) -> u64 {
self.used
}
/// Legacy meaning is unchanged. Protected ordinary callers retain B-O;
/// presentation and aggregate capacity have separate, explicit getters.
pub fn remaining(&self) -> u64 {
self.ordinary_remaining()
}
pub(crate) fn ordinary_remaining(&self) -> u64 {
self.limit - self.protected.as_ref().map_or(self.used, |state| state.ordinary_used)
}
pub(crate) fn presentation_remaining(&self) -> u64 {
self.protected.as_ref().map_or(0, |state| state.presentation_limit - state.presentation_used)
}
pub(crate) fn aggregate_remaining(&self) -> u64 {
self.protected.as_ref().map_or(self.limit, |state| state.aggregate_limit) - self.used
}
pub(crate) fn protected_report(&self) -> Option<crate::job::ProtectedPreviewReport> {
let state = self.protected.as_ref()?;
let quota_limit = state.plan.quota_limit();
Some(crate::job::ProtectedPreviewReport {
policy_version: 1,
ordinary_limit: self.limit,
presentation_limit: state.presentation_limit,
aggregate_limit: state.aggregate_limit,
ordinary_used: state.ordinary_used,
presentation_used: state.presentation_used,
accepted_snapshots: state.accepted_snapshots,
quota_limit,
next_milestone_index: state.next_milestone_index,
quota_exhausted: state.accepted_snapshots == quota_limit,
milestones_complete: state.next_milestone_index == quota_limit,
})
}
/// Read-only eligibility at a real committed camera frontier. Source progress
/// is not a work credit: it selects a milestone, never reserves ordinary work.
fn protected_ready(&self, committed: u64) -> Result<bool> {
let state = self.protected.as_ref().ok_or(TraceError::InvalidInput("protected feedback policy missing"))?;
if committed >= state.plan.total_commits()
|| state.accepted_snapshots >= state.plan.quota_limit()
|| state.next_milestone_index >= state.plan.quota_limit()
{
return Ok(false);
}
let milestone = state.plan.milestone(state.next_milestone_index).map_err(|_| TraceError::Internal("invalid protected milestone"))?;
let cost = state.plan.snapshot_work().map_err(|_| TraceError::WorkLimit)?;
Ok(committed >= milestone && self.presentation_remaining() >= cost && self.aggregate_remaining() >= cost)
}
/// Debit ONE W and coalesce all reached milestones in the same transaction.
/// A wait/refusal changes no counters. Cancellation after a debit is not a refund.
fn charge_presentation(&mut self, committed: u64, cancel: &CancelToken) -> Result<bool> {
check_cancel(cancel)?;
if !self.protected_ready(committed)? {
return Ok(false);
}
let state = self.protected.as_ref().ok_or(TraceError::InvalidInput("protected feedback policy missing"))?;
let cost = state.plan.snapshot_work().map_err(|_| TraceError::WorkLimit)?;
let presentation_used = state.presentation_used.checked_add(cost).filter(|v| *v <= state.presentation_limit).ok_or(TraceError::WorkLimit)?;
let used = self.used.checked_add(cost).filter(|v| *v <= state.aggregate_limit).ok_or(TraceError::WorkLimit)?;
let accepted = state.accepted_snapshots.checked_add(1).filter(|n| *n <= state.plan.quota_limit()).ok_or(TraceError::WorkLimit)?;
let next = state.plan.reached_milestones(committed).map_err(|_| TraceError::Internal("invalid protected reached frontier"))?;
check_cancel(cancel)?;
let state = self.protected.as_mut().ok_or(TraceError::Internal("protected ledger disappeared"))?;
state.presentation_used = presentation_used;
state.accepted_snapshots = accepted;
state.next_milestone_index = next;
self.used = used;
Ok(true)
}
fn tick(&mut self, cancel: &CancelToken) -> Result<()> {
self.charge(1, cancel)
}
fn charge(&mut self, units: u64, cancel: &CancelToken) -> Result<()> {
check_cancel(cancel)?;
if let Some(state) = &mut self.protected {
let ordinary = state.ordinary_used.checked_add(units).filter(|v| *v <= self.limit).ok_or(TraceError::WorkLimit)?;
let used = self.used.checked_add(units).filter(|v| *v <= state.aggregate_limit).ok_or(TraceError::WorkLimit)?;
state.ordinary_used = ordinary;
self.used = used;
} else {
self.used = self.used.checked_add(units).filter(|used| *used <= self.limit).ok_or(TraceError::WorkLimit)?;
}
Ok(())
}
/// Private test boundary only: the ordinary allowance is fixed before any
/// real task work, preserving Q and the same O/V ledger. No production caller.
#[cfg(test)]
fn new_protected_for_test(plan: crate::job::ProtectedPreviewPlan, ordinary: u64) -> Result<Self> {
let mut work = Self::new_protected(plan)?;
if ordinary == 0 || ordinary > work.limit {
return Err(TraceError::InvalidInput("test ordinary limit outside profile"));
}
let state = work.protected.as_mut().ok_or(TraceError::Internal("test protected policy missing"))?;
state.aggregate_limit =
ordinary.checked_add(state.presentation_limit).filter(|v| *v <= crate::job::MAX_PROTECTED_CPU_WORK).ok_or(TraceError::WorkLimit)?;
work.limit = ordinary;
Ok(work)
}
}
fn bounded(point: Vec3) -> bool {
point.is_finite() && [point.x, point.y, point.z].into_iter().all(|v| v.abs() <= MAX_COORDINATE_MM)
}
fn unit(vector: Vec3) -> Option<Vec3> {
let scale = vector.x.abs().max(vector.y.abs()).max(vector.z.abs());
if !vector.is_finite() || scale == 0.0 {
return None;
}
let scaled = vector / scale;
Some(scaled / scaled.len2().sqrt())
}
fn component(vector: Vec3, axis: usize) -> f64 {
match axis {
0 => vector.x,
1 => vector.y,
_ => vector.z,
}
}
/// Admitted ray with a unit direction and closed finite distance interval.
/// No implicit origin offset, back-face culling or fixed world-space epsilon.
#[derive(Clone, Copy, Debug)]
pub struct Ray {
origin: Vec3,
direction: Vec3,
min: f64,
max: f64,
}
impl Ray {
pub fn new(origin: Vec3, direction: Vec3, min: f64, max: f64) -> Result<Self> {
if !bounded(origin) || !min.is_finite() || !max.is_finite() || min < 0.0 || min > max || max > MAX_DISTANCE_MM {
return Err(TraceError::InvalidInput("ray origin or distance interval"));
}
let direction = unit(direction).ok_or(TraceError::InvalidInput("finite nonzero ray direction required"))?;
Ok(Self { origin, direction, min, max })
}
pub fn origin(self) -> Vec3 {
self.origin
}
pub fn direction(self) -> Vec3 {
self.direction
}
pub fn interval(self) -> [f64; 2] {
[self.min, self.max]
}
pub fn at(self, distance: f64) -> Result<Vec3> {
if !distance.is_finite() || distance < self.min || distance > self.max {
return Err(TraceError::InvalidInput("distance outside admitted ray interval"));
}
Ok(self.origin + self.direction * distance)
}
}
/// Conservative world-space box; empty boxes exist only inside the builder.
#[derive(Clone, Copy, Debug)]
pub struct Bounds {
min: Vec3,
max: Vec3,
}
impl Bounds {
pub fn new(min: Vec3, max: Vec3) -> Result<Self> {
if !bounded(min) || !bounded(max) || min.x > max.x || min.y > max.y || min.z > max.z {
return Err(TraceError::InvalidInput("finite ordered bounding box required"));
}
Ok(Self { min, max })
}
pub fn min(self) -> Vec3 {
self.min
}
pub fn max(self) -> Vec3 {
self.max
}
fn empty() -> Self {
Self { min: Vec3::new(f64::INFINITY, f64::INFINITY, f64::INFINITY), max: Vec3::new(f64::NEG_INFINITY, f64::NEG_INFINITY, f64::NEG_INFINITY) }
}
fn include(self, other: Self) -> Self {
Self { min: self.min.min(other.min), max: self.max.max(other.max) }
}
fn point(point: Vec3) -> Self {
Self { min: point, max: point }
}
/// Closed slab overlap. Parallel (including signed-zero) components never divide.
pub fn intersect(self, ray: &Ray) -> Option<[f64; 2]> {
self.clip(ray, ray.max)
}
fn clip(self, ray: &Ray, maximum: f64) -> Option<[f64; 2]> {
let (mut near, mut far) = (ray.min, ray.max.min(maximum));
for axis in 0..3 {
let (lo, hi, origin, direction) =
(component(self.min, axis), component(self.max, axis), component(ray.origin, axis), component(ray.direction, axis));
if direction == 0.0 {
if origin < lo || origin > hi {
return None;
}
} else {
// Division may produce infinity for an almost-parallel ray; the
// finite caller interval clips it. No reciprocal times zero.
let a = (lo - origin) / direction;
let b = (hi - origin) / direction;
near = near.max(a.min(b));
far = far.min(a.max(b));
if near > far {
return None;
}
}
}
Some([near, far])
}
}
/// Validated triangle. Coincident/collinear vertices are retained but never hit.
#[derive(Clone, Copy, Debug)]
pub struct Triangle {
vertices: [Vec3; 3],
normal: Option<Vec3>,
}
impl Triangle {
pub fn new(vertices: [Vec3; 3]) -> Result<Self> {
if !vertices.into_iter().all(bounded) {
return Err(TraceError::InvalidInput("triangle vertex coordinates"));
}
let [a, b, c] = vertices;
let ab = b - a;
let ac = c - a;
let scale = [ab.x, ab.y, ab.z, ac.x, ac.y, ac.z].into_iter().map(f64::abs).fold(0.0, f64::max);
let normal = if scale == 0.0 { None } else { unit((ab / scale).cross(ac / scale)) };
Ok(Self { vertices, normal })
}
pub fn vertices(self) -> [Vec3; 3] {
self.vertices
}
pub fn geometric_normal(self) -> Option<Vec3> {
self.normal
}
pub fn bounds(self) -> Bounds {
let [a, b, c] = self.vertices;
let min = a.min(b).min(c);
let max = a.max(b).max(c);
// One representable outward step, not a fixed millimetre epsilon.
Bounds {
min: Vec3::new(min.x.next_down(), min.y.next_down(), min.z.next_down()),
max: Vec3::new(max.x.next_up(), max.y.next_up(), max.z.next_up()),
}
}
fn centroid(self) -> Vec3 {
let [a, b, c] = self.vertices;
a / 3.0 + b / 3.0 + c / 3.0
}
/// Two-sided closed-edge barycentric intersection by dominant-direction shear.
/// At equal distance the BVH's input ordinal resolves the tie. Zero projected
/// area is a miss, including geometry collapsed by f64 arithmetic.
pub fn intersect(self, ray: &Ray) -> Option<TriangleHit> {
let normal = self.normal?;
let d = ray.direction;
let kz = if d.x.abs() >= d.y.abs() && d.x.abs() >= d.z.abs() {
0
} else if d.y.abs() >= d.z.abs() {
1
} else {
2
};
let kx = (kz + 1) % 3;
let ky = (kx + 1) % 3;
let dominant = component(d, kz);
let sx = component(d, kx) / dominant;
let sy = component(d, ky) / dominant;
let projected = self.vertices.map(|v| {
let delta = v - ray.origin;
let z = component(delta, kz);
[component(delta, kx) - sx * z, component(delta, ky) - sy * z, z / dominant]
});
let [[ax, ay, az], [bx, by, bz], [cx, cy, cz]] = projected;
let weights = [bx * cy - by * cx, cx * ay - cy * ax, ax * by - ay * bx];
let [u, v, w] = weights;
if (u < 0.0 || v < 0.0 || w < 0.0) && (u > 0.0 || v > 0.0 || w > 0.0) {
return None;
}
let determinant = u + v + w;
if determinant == 0.0 {
return None;
}
let barycentric = weights.map(|value| value / determinant);
let [u, v, w] = barycentric;
// Divide before multiplying by depth: very small triangle areas need not
// underflow their otherwise well-represented hit distance.
// An exact coordinate plane has a direct depth equation. Summing
// depths along another dominant ray axis can cancel large tangential
// terms into a false positive. No interval or edge policy changes.
let axis_plane = (0..3).find_map(|axis| {
let [a, b, c] = self.vertices.map(|point| component(point, axis));
(a == b && b == c).then_some((axis, a))
});
let distance = if let Some((axis, coordinate)) = axis_plane {
(coordinate - component(ray.origin, axis)) / component(d, axis)
} else {
u * az + v * bz + w * cz
};
if !distance.is_finite() || distance < ray.min || distance > ray.max {
return None;
}
Some(TriangleHit { distance, barycentric, geometric_normal: normal, front_face: d.dot(normal) < 0.0 })
}
}
/// Geometric hit, without material/shading-normal or persistent topology identity.
#[derive(Clone, Copy, Debug, PartialEq)]
pub struct TriangleHit {
pub distance: f64,
pub barycentric: [f64; 3],
pub geometric_normal: Vec3,
pub front_face: bool,
}
/// Captured input ordinal, not a CAD face identifier. RT2 owns the appearance mapping.
#[derive(Clone, Copy, Debug, PartialEq)]
pub struct Hit {
pub primitive_index: usize,
pub geometry: TriangleHit,
}
#[cfg(test)]
mod planar_shadow_tests;
#[cfg(test)]
mod tests;
@@ -0,0 +1,95 @@
//! Deterministic counter sampling and owned camera-film continuation.
//! No target sample count, work quantum or preview cadence enters the sampler.
use crate::{film::primary::PrimaryFilm, job::CpuProgressiveOptions};
pub(super) struct Progressive {
pub film: PrimaryFilm,
pub options: CpuProgressiveOptions,
pub resolving: bool,
pub resolve_pixel: usize,
pub partial_plan: Option<crate::job::PartialPreviewPlan>,
pub partial: Option<PartialResolve>,
pub last_partial: Option<crate::film::primary::PartialFrontier>,
}
pub(super) struct PartialResolve {
pub plan: crate::job::PartialPreviewPlan,
pub frontier: crate::film::primary::PartialFrontier,
pub resume_pixel: usize,
pub next: usize,
pub covered: Vec<u32>,
}
/// Read-only O(1) test for new represented data; no scan over the source film.
/// A completed global pass is meaningful even if its last source pixels are
/// not representatives: the receiver's global Unknown authority changes then.
pub(super) fn represented_changed(
plan: crate::job::PartialPreviewPlan,
before: Option<crate::film::primary::PartialFrontier>,
now: crate::film::primary::PartialFrontier,
) -> crate::job::Result<bool> {
use crate::job::{ErrorCode, JobError};
plan.validate()?;
let source_pixels = u64::from(plan.source_width()) * u64::from(plan.source_height());
if u64::try_from(now.pixels).ok() != Some(source_pixels) || now.updated_prefix >= now.pixels {
return Err(JobError::new(ErrorCode::InvalidScene, "partial film frontier differs from its source plan"));
}
let Some(before) = before else { return Ok(now.completed_passes != 0 || now.updated_prefix != 0) };
if before.pixels != now.pixels
|| before.completed_passes > now.completed_passes
|| (before.completed_passes == now.completed_passes && before.updated_prefix > now.updated_prefix)
{
return Err(JobError::new(ErrorCode::InvalidScene, "partial film frontier went backwards"));
}
if before.completed_passes != now.completed_passes {
return Ok(true);
}
if before.updated_prefix == now.updated_prefix {
return Ok(false);
}
let w = u64::from(plan.source_width());
let h = u64::from(plan.source_height());
let pw = u64::from(plan.width());
let ph = u64::from(plan.height());
let lower = u64::try_from(before.updated_prefix).map_err(|_| JobError::new(ErrorCode::LimitExceeded, "partial source index overflow"))?;
let x = lower % w;
let y = lower / w;
let mut v = y.checked_mul(ph).ok_or_else(|| JobError::new(ErrorCode::LimitExceeded, "partial row mapping overflow"))?.div_ceil(h);
if v >= ph {
return Ok(false);
}
let mut u = if v * h / ph == y {
x.checked_mul(pw).ok_or_else(|| JobError::new(ErrorCode::LimitExceeded, "partial column mapping overflow"))?.div_ceil(w)
} else {
0
};
if u >= pw {
v += 1;
u = 0;
}
if v >= ph {
return Ok(false);
}
let display =
v.checked_mul(pw).and_then(|n| n.checked_add(u)).ok_or_else(|| JobError::new(ErrorCode::LimitExceeded, "partial display index overflow"))?;
let display = usize::try_from(display).map_err(|_| JobError::new(ErrorCode::LimitExceeded, "partial display address overflow"))?;
Ok(plan.source_index(display)? < now.updated_prefix)
}
/// Integer-only mixing before conversion to exactly representable 53-bit unit
/// variates. Domains separate camera, BSDF and environment choices at each bounce.
pub(super) fn variates(seed: u32, pixel: u64, ordinal: u32, domain: u64) -> [f64; 2] {
fn mix(mut value: u64) -> u64 {
value ^= value >> 30;
value = value.wrapping_mul(0xbf58_476d_1ce4_e5b9);
value ^= value >> 27;
value = value.wrapping_mul(0x94d0_49bb_1331_11eb);
value ^ (value >> 31)
}
let key = mix(u64::from(seed) ^ 0x4350_5546_494c_4d00)
^ mix(pixel.wrapping_add(0x9e37_79b9_7f4a_7c15))
^ mix(u64::from(ordinal).wrapping_add(0xd1b5_4a32_d192_ed03))
^ mix(domain.wrapping_add(0x94d0_49bb_1331_11eb));
[0_u64, 1].map(|axis| (mix(key ^ mix(axis.wrapping_add(0x632b_e59b_d9b4_e019))) >> 11) as f64 / 9_007_199_254_740_992.0)
}
@@ -0,0 +1,455 @@
use super::*;
fn triangle(z: f64) -> Triangle {
Triangle::new([Vec3::new(0., 0., z), Vec3::new(2., 0., z), Vec3::new(0., 2., z)]).unwrap()
}
fn ray(origin: Vec3, direction: Vec3) -> Ray {
Ray::new(origin, direction, 0., 100.).unwrap()
}
fn build(triangles: Vec<Triangle>, limits: BuildLimits, chunk: usize) -> Bvh {
let cancel = CancelToken::default();
let mut builder = BvhBuilder::new(triangles, limits, &cancel).unwrap();
while !builder.step(chunk, &cancel).unwrap().complete {}
builder.finish().unwrap()
}
fn closest(bvh: &Bvh, ray: &Ray) -> Option<Hit> {
bvh.closest_hit(ray, &mut WorkBudget::new(MAX_WORK).unwrap(), &CancelToken::default()).unwrap()
}
fn brute(triangles: &[Triangle], ray: &Ray) -> Option<Hit> {
let mut best: Option<Hit> = None;
for (primitive_index, triangle) in triangles.iter().enumerate() {
if let Some(geometry) = triangle.intersect(ray)
&& best.is_none_or(|old| {
geometry.distance < old.geometry.distance || (geometry.distance == old.geometry.distance && primitive_index < old.primitive_index)
})
{
best = Some(Hit { primitive_index, geometry });
}
}
best
}
fn close(actual: f64, expected: f64) {
assert!((actual - expected).abs() <= 1e-12 * expected.abs().max(f64::MIN_POSITIVE), "{actual} != {expected}");
}
#[test]
fn ray_admission_normalizes_without_overflow_or_tiny_vector_cutoff() {
for scale in [f64::from_bits(1), 1e-200, 1., 1e200, f64::MAX] {
let r = ray(Vec3::ZERO, Vec3::new(scale, 0., 0.));
assert_eq!(r.direction(), Vec3::X);
assert_eq!(r.at(2.).unwrap(), Vec3::new(2., 0., 0.));
}
for direction in [Vec3::ZERO, Vec3::new(f64::NAN, 0., 1.), Vec3::new(0., f64::INFINITY, 1.)] {
assert!(Ray::new(Vec3::ZERO, direction, 0., 1.).is_err());
}
for (min, max) in [(-1., 1.), (2., 1.), (0., f64::INFINITY), (f64::NAN, 1.), (0., MAX_DISTANCE_MM.next_up())] {
assert!(Ray::new(Vec3::ZERO, Vec3::Z, min, max).is_err());
}
assert!(Ray::new(Vec3::new(MAX_COORDINATE_MM.next_up(), 0., 0.), Vec3::Z, 0., 1.).is_err());
assert!(ray(Vec3::ZERO, Vec3::Z).at(f64::NAN).is_err());
}
#[test]
fn analytic_triangle_distance_barycentrics_normal_and_two_sides() {
let t = triangle(0.);
let hit = t.intersect(&ray(Vec3::new(0.5, 0.5, 2.), -Vec3::Z)).unwrap();
assert_eq!(hit.distance, 2.);
assert_eq!(hit.barycentric, [0.5, 0.25, 0.25]);
assert_eq!(hit.geometric_normal, Vec3::Z);
assert!(hit.front_face);
let back = t.intersect(&ray(Vec3::new(0.5, 0.5, -2.), Vec3::Z)).unwrap();
assert_eq!(back.distance, 2.);
assert!(!back.front_face);
let boundary = Ray::new(Vec3::new(0.5, 0.5, 2.), -Vec3::Z, 2., 2.).unwrap();
assert!(t.intersect(&boundary).is_some());
assert!(t.intersect(&Ray::new(boundary.origin(), boundary.direction(), 0., 1.99).unwrap()).is_none());
assert!(t.intersect(&ray(Vec3::new(2., 2., 2.), -Vec3::Z)).is_none());
}
#[test]
fn tiny_and_huge_geometry_have_no_fixed_world_epsilon() {
for scale in [1e-120, 1e-12, 1., 1e11] {
let t = Triangle::new([Vec3::ZERO, Vec3::X * (2. * scale), Vec3::Y * (2. * scale)]).unwrap();
let r = Ray::new(Vec3::new(0.5 * scale, 0.5 * scale, 2. * scale), -Vec3::Z, 0., 4. * scale).unwrap();
let hit = t.intersect(&r).unwrap();
close(hit.distance, 2. * scale);
close(hit.barycentric[0], 0.5);
let bvh = build(vec![t], BuildLimits::default(), 1);
assert_eq!(closest(&bvh, &r).unwrap().geometry, hit);
}
}
#[test]
fn shared_edges_vertices_and_equal_distance_use_lowest_input_ordinal() {
let a = Triangle::new([Vec3::ZERO, Vec3::X, Vec3::Y]).unwrap();
let b = Triangle::new([Vec3::new(1., 1., 0.), Vec3::Y, Vec3::X]).unwrap();
for triangles in [vec![a, b], vec![b, a], vec![a, a]] {
let bvh = build(triangles.clone(), BuildLimits { leaf_size: 1, ..Default::default() }, 1);
for point in [Vec3::new(0.5, 0.5, 1.), Vec3::new(1., 0., 1.)] {
let r = ray(point, -Vec3::Z);
assert_eq!(closest(&bvh, &r), brute(&triangles, &r));
assert_eq!(closest(&bvh, &r).unwrap().primitive_index, 0);
}
}
}
#[test]
fn degenerate_parallel_coplanar_and_grazing_cases_are_explicit() {
for vertices in [[Vec3::ZERO; 3], [Vec3::ZERO, Vec3::X, Vec3::X * 2.]] {
let t = Triangle::new(vertices).unwrap();
assert!(t.geometric_normal().is_none());
assert!(t.intersect(&ray(Vec3::new(0., 0., 1.), -Vec3::Z)).is_none());
}
let t = triangle(0.);
assert!(t.intersect(&ray(Vec3::new(0.5, 0.5, 1.), Vec3::X)).is_none());
assert!(t.intersect(&ray(Vec3::new(0.5, 0.5, 0.), Vec3::X)).is_none());
let hit = t.intersect(&ray(Vec3::new(-1., 0.25, 1e-9), Vec3::new(1., 0., -1e-9))).unwrap();
close(hit.distance, 1.);
assert!(t.intersect(&ray(Vec3::new(0.5, 0.5, 0.), Vec3::Z)).is_some(), "closed t=0 is a caller policy, not silently offset");
}
#[test]
fn slab_intervals_handle_signed_zero_boundaries_and_almost_parallel_components() {
let b = Bounds::new(Vec3::new(1., 1., 1.), Vec3::new(2., 2., 2.)).unwrap();
assert_eq!(b.intersect(&ray(Vec3::new(1., 1., 0.), Vec3::new(-0., 0., 1.))), Some([1., 2.]));
assert!(b.intersect(&ray(Vec3::new(0., 1., 0.), Vec3::Z)).is_none());
assert_eq!(b.intersect(&ray(Vec3::new(1.5, 1.5, 0.), Vec3::new(f64::from_bits(1), 0., 1.))), Some([1., 2.]));
assert!(b.intersect(&ray(Vec3::new(0., 1.5, 0.), Vec3::new(f64::from_bits(1), 0., 1.))).is_none());
assert!(Bounds::new(Vec3::X, Vec3::ZERO).is_err());
assert!(Bounds::new(Vec3::new(f64::NAN, 0., 0.), Vec3::X).is_err());
}
#[test]
fn builder_steps_are_bounded_and_results_do_not_depend_on_chunk_size() {
let triangles = (0..31).map(|i| triangle(f64::from(i))).collect::<Vec<_>>();
let cancel = CancelToken::default();
let limits = BuildLimits { leaf_size: 1, ..Default::default() };
let mut builder = BvhBuilder::new(triangles.clone(), limits, &cancel).unwrap();
let mut used = 0;
loop {
let progress = builder.step(1, &cancel).unwrap();
assert!(progress.work_used - used <= 1);
used = progress.work_used;
if progress.complete {
break;
}
}
let a = builder.finish().unwrap();
let b = build(triangles.clone(), limits, MAX_BUILD_STEP);
assert_eq!(a.node_count(), b.node_count());
assert!(a.node_count() < 2 * triangles.len());
assert!(a.retained_bytes().unwrap() <= limits.max_memory_bytes);
for z in [0.5, 5.5, 50.] {
let r = ray(Vec3::new(0.5, 0.5, z), -Vec3::Z);
assert_eq!(closest(&a, &r), brute(&triangles, &r));
assert_eq!(closest(&a, &r), closest(&b, &r));
}
}
#[test]
fn coincident_centroids_and_depth_cap_terminate_without_recursion() {
let triangles = vec![triangle(0.); 129];
for depth in [1, MAX_DEPTH] {
let bvh = build(triangles.clone(), BuildLimits { max_depth: depth, leaf_size: 1, ..Default::default() }, 3);
let r = ray(Vec3::new(0.5, 0.5, 1.), -Vec3::Z);
assert_eq!(closest(&bvh, &r), brute(&triangles, &r));
assert_eq!(closest(&bvh, &r).unwrap().primitive_index, 0);
}
}
#[test]
fn empty_scene_and_incomplete_build_are_distinct() {
let empty = build(Vec::new(), BuildLimits::default(), 1);
assert_eq!(empty.primitive_count(), 0);
assert_eq!(empty.node_count(), 0);
assert!(closest(&empty, &ray(Vec3::ZERO, Vec3::Z)).is_none());
let builder = BvhBuilder::new(vec![triangle(0.)], BuildLimits::default(), &CancelToken::default()).unwrap();
assert!(matches!(builder.finish(), Err(TraceError::BuildIncomplete)));
}
#[test]
fn work_limit_is_an_error_not_a_partial_hit_and_can_span_many_rays() {
let bvh = build(vec![triangle(0.)], BuildLimits::default(), 1);
let cancel = CancelToken::default();
let r = ray(Vec3::new(0.5, 0.5, 1.), -Vec3::Z);
assert_eq!(bvh.closest_hit(&r, &mut WorkBudget::new(1).unwrap(), &cancel), Err(TraceError::WorkLimit));
let mut work = WorkBudget::new(2).unwrap();
assert!(bvh.any_hit(&r, &mut work, &cancel).unwrap());
assert_eq!(work.used(), 2);
assert_eq!(work.remaining(), 0);
assert_eq!(bvh.any_hit(&r, &mut work, &cancel), Err(TraceError::WorkLimit));
let mut builder = BvhBuilder::new(vec![triangle(0.); 20], BuildLimits { max_work: 1, ..Default::default() }, &cancel).unwrap();
assert_eq!(builder.step(2, &cancel), Err(TraceError::WorkLimit));
}
#[test]
fn cancellation_covers_admission_mid_build_and_both_traversals() {
let cancel = CancelToken::default();
let mut builder = BvhBuilder::new(vec![triangle(0.); 20], BuildLimits::default(), &cancel).unwrap();
builder.step(2, &cancel).unwrap();
cancel.cancel();
assert_eq!(builder.step(1, &cancel), Err(TraceError::Cancelled));
assert!(matches!(BvhBuilder::new(vec![triangle(0.)], BuildLimits::default(), &cancel), Err(TraceError::Cancelled)));
let bvh = build(vec![triangle(0.)], BuildLimits::default(), 1);
let r = ray(Vec3::new(0.5, 0.5, 1.), -Vec3::Z);
assert_eq!(bvh.closest_hit(&r, &mut WorkBudget::new(10).unwrap(), &cancel), Err(TraceError::Cancelled));
assert_eq!(bvh.any_hit(&r, &mut WorkBudget::new(10).unwrap(), &cancel), Err(TraceError::Cancelled));
}
#[test]
fn memory_counts_input_capacity_and_hostile_limits_refuse_before_own_allocations() {
let defaults = BuildLimits::default();
let normal = BvhBuilder::required_bytes(1, 1, defaults).unwrap();
assert!(BvhBuilder::required_bytes(1, 100, defaults).unwrap() > normal);
assert_eq!(BvhBuilder::required_bytes(1, usize::MAX, defaults), Err(TraceError::MemoryLimit));
assert_eq!(BvhBuilder::required_bytes(1, 1, BuildLimits { max_memory_bytes: 1, ..defaults }), Err(TraceError::MemoryLimit));
for limits in [
BuildLimits { max_depth: MAX_DEPTH + 1, ..defaults },
BuildLimits { leaf_size: 0, ..defaults },
BuildLimits { max_triangles: MAX_TRIANGLES + 1, ..defaults },
BuildLimits { max_memory_bytes: MAX_MEMORY_BYTES + 1, ..defaults },
BuildLimits { max_work: crate::job::MAX_CPU_WORK + 1, ..defaults },
] {
assert!(BvhBuilder::required_bytes(1, 1, limits).is_err());
}
assert!(WorkBudget::new(0).is_err());
let mut builder = BvhBuilder::new(vec![triangle(0.)], defaults, &CancelToken::default()).unwrap();
assert!(builder.step(0, &CancelToken::default()).is_err());
assert!(builder.step(MAX_BUILD_STEP + 1, &CancelToken::default()).is_err());
}
struct Seed(u64);
impl Seed {
fn next(&mut self) -> u64 {
self.0 = self.0.wrapping_mul(6364136223846793005).wrapping_add(1442695040888963407);
self.0
}
fn scalar(&mut self) -> f64 {
(self.next() >> 11) as f64 / ((1_u64 << 53) as f64)
}
fn point(&mut self) -> Vec3 {
Vec3::new(self.scalar() * 20. - 10., self.scalar() * 20. - 10., self.scalar() * 20. - 10.)
}
}
#[test]
fn seeded_bvh_vs_brute_force_closest_and_any_hit() {
let mut seed = Seed(0x1368_0001);
for _ in 0..16 {
let triangles = (0..64).map(|_| Triangle::new([seed.point(), seed.point(), seed.point()]).unwrap()).collect::<Vec<_>>();
let bvh = build(triangles.clone(), BuildLimits { leaf_size: 2, ..Default::default() }, 7);
for _ in 0..128 {
let r = ray(seed.point(), seed.point());
let expected = brute(&triangles, &r);
assert_eq!(closest(&bvh, &r), expected);
let any = bvh.any_hit(&r, &mut WorkBudget::new(MAX_WORK).unwrap(), &CancelToken::default()).unwrap();
assert_eq!(any, expected.is_some());
}
}
}
#[test]
fn seeded_hostile_float_admission_never_publishes_nonfinite_geometry() {
let mut seed = Seed(0x1368_badd);
for _ in 0..2048 {
let value = f64::from_bits(seed.next());
let p = Vec3::new(value, 0., 0.);
let accepted = value.is_finite() && value.abs() <= MAX_COORDINATE_MM;
assert_eq!(Ray::new(p, Vec3::Z, 0., 1.).is_ok(), accepted);
assert_eq!(Triangle::new([p; 3]).is_ok(), accepted);
}
}
#[test]
fn protected_ledger_keeps_ordinary_profiles_and_requires_the_explicit_new_envelope() {
use crate::job::{CpuBudget, MAX_CPU_WORK, MAX_PROTECTED_CPU_WORK, ProtectedPreviewPlan};
assert_eq!(MAX_CPU_WORK, 16_000_000_000_000);
assert_eq!(MAX_PROTECTED_CPU_WORK, 31_462_813_335_678);
assert!(WorkBudget::new(MAX_CPU_WORK + 1).is_err());
assert!(WorkBudget::new(MAX_PROTECTED_CPU_WORK).is_err());
for budget in CpuBudget::ALL {
let plan = ProtectedPreviewPlan::new(1024, 1024, 2, budget).unwrap();
let work = WorkBudget::new_protected(plan).unwrap();
let report = work.protected_report().unwrap();
assert_eq!(report.ordinary_limit, budget.limits().max_work_units);
assert_eq!(report.presentation_limit, 958_464_130);
assert_eq!(report.aggregate_limit, report.ordinary_limit + report.presentation_limit);
assert_eq!(work.remaining(), report.ordinary_limit);
assert_eq!(work.ordinary_remaining(), report.ordinary_limit);
assert_eq!(work.presentation_remaining(), report.presentation_limit);
assert_eq!(work.aggregate_remaining(), report.aggregate_limit);
assert_eq!((report.ordinary_used, report.presentation_used, work.used()), (0, 0, 0));
}
let max = ProtectedPreviewPlan::new(1024, 1024, 2, CpuBudget::Workstation).unwrap();
assert_eq!(max.aggregate_limit().unwrap(), MAX_CPU_WORK + 958_464_130);
assert!(WorkBudget::new(100).unwrap().protected_report().is_none());
assert!(ProtectedPreviewPlan::new(u32::MAX, u32::MAX, u32::MAX, CpuBudget::Workstation).is_err());
}
#[test]
fn protected_ledger_exact_ordinary_and_aggregate_boundaries_do_not_steal_or_refund() {
use crate::job::{CpuBudget, ProtectedPreviewPlan};
let plan = ProtectedPreviewPlan::new(1, 1, 2, CpuBudget::Compact).unwrap();
let cost = plan.snapshot_work().unwrap();
let cancel = CancelToken::default();
let mut work = WorkBudget::new_protected_for_test(plan, 7).unwrap();
work.charge(6, &cancel).unwrap();
assert!(work.charge_presentation(1, &cancel).unwrap());
let before = work.protected_report().unwrap();
assert_eq!((before.ordinary_used, before.presentation_used), (6, cost));
assert_eq!(work.remaining(), 1, "presentation did not consume the last ordinary tick");
assert_eq!(work.presentation_remaining(), 0);
assert_eq!(work.aggregate_remaining(), 1);
assert_eq!(work.charge(2, &cancel), Err(TraceError::WorkLimit));
assert_eq!(work.protected_report().unwrap(), before);
work.tick(&cancel).unwrap();
let complete = work.protected_report().unwrap();
assert_eq!((complete.ordinary_used, complete.presentation_used, work.used()), (7, cost, 7 + cost));
assert_eq!(work.aggregate_remaining(), 0);
assert_eq!(work.charge(u64::MAX, &cancel), Err(TraceError::WorkLimit));
assert!(!work.charge_presentation(1, &cancel).unwrap());
assert_eq!(work.protected_report().unwrap(), complete);
}
#[test]
fn protected_milestones_coalesce_without_fabricating_accepted_snapshots_or_spent_quota() {
use crate::job::{CpuBudget, ProtectedPreviewPlan};
let plan = ProtectedPreviewPlan::new(4, 1, 5, CpuBudget::Compact).unwrap();
let mut work = WorkBudget::new_protected(plan).unwrap();
let initial = work.protected_report().unwrap();
assert!(!work.charge_presentation(0, &CancelToken::default()).unwrap());
assert_eq!(work.protected_report().unwrap(), initial);
assert!(work.charge_presentation(19, &CancelToken::default()).unwrap());
let coalesced = work.protected_report().unwrap();
assert_eq!((coalesced.accepted_snapshots, coalesced.next_milestone_index, coalesced.quota_limit), (1, 7, 7));
assert_eq!(coalesced.presentation_used, plan.snapshot_work().unwrap());
assert!(coalesced.presentation_used < coalesced.presentation_limit);
assert!(coalesced.milestones_complete);
assert!(!coalesced.quota_exhausted);
for progress in [19, 20, u64::MAX] {
assert!(!work.protected_ready(progress).unwrap());
assert!(!work.charge_presentation(progress, &CancelToken::default()).unwrap());
assert_eq!(work.protected_report().unwrap(), coalesced);
}
}
#[test]
fn protected_zero_and_one_milestone_policies_are_real_boundaries() {
use crate::job::{CpuBudget, ProtectedPreviewPlan};
let cancel = CancelToken::default();
let zero = ProtectedPreviewPlan::new(1, 1, 1, CpuBudget::Compact).unwrap();
let mut work = WorkBudget::new_protected(zero).unwrap();
let report = work.protected_report().unwrap();
assert_eq!((report.quota_limit, report.presentation_limit), (0, 0));
assert_eq!(report.aggregate_limit, report.ordinary_limit);
assert!(report.quota_exhausted && report.milestones_complete);
assert!(!work.charge_presentation(0, &cancel).unwrap());
assert!(zero.milestone(0).is_err());
let one = ProtectedPreviewPlan::new(1, 1, 2, CpuBudget::Compact).unwrap();
assert_eq!(one.quota_limit(), 1);
assert_eq!(one.milestone(0).unwrap(), 1);
assert!(one.milestone(1).is_err());
let mut work = WorkBudget::new_protected(one).unwrap();
assert!(!work.charge_presentation(0, &cancel).unwrap());
assert!(work.charge_presentation(1, &cancel).unwrap());
assert!(work.protected_report().unwrap().quota_exhausted);
}
#[test]
fn protected_quota_exhaustion_leaves_the_entire_ordinary_allowance_available() {
use crate::job::{CpuBudget, ProtectedPreviewPlan};
let plan = ProtectedPreviewPlan::new(32, 32, 64, CpuBudget::Compact).unwrap();
let cancel = CancelToken::default();
let mut work = WorkBudget::new_protected_for_test(plan, 17).unwrap();
for index in 0..127 {
assert!(work.charge_presentation(plan.milestone(index).unwrap(), &cancel).unwrap());
}
let exhausted = work.protected_report().unwrap();
assert_eq!((exhausted.accepted_snapshots, exhausted.next_milestone_index), (127, 127));
assert_eq!(exhausted.presentation_used, exhausted.presentation_limit);
assert!(exhausted.quota_exhausted && exhausted.milestones_complete);
assert_eq!(work.ordinary_remaining(), 17);
assert!(!work.charge_presentation(plan.total_commits() - 1, &cancel).unwrap());
work.charge(17, &cancel).unwrap();
let final_report = work.protected_report().unwrap();
assert_eq!(work.used(), final_report.aggregate_limit);
assert_eq!(final_report.ordinary_used, 17);
}
#[test]
fn protected_cancel_before_debit_is_atomic_and_after_debit_is_never_refunded() {
use crate::job::{CpuBudget, ProtectedPreviewPlan};
let plan = ProtectedPreviewPlan::new(4, 1, 5, CpuBudget::Compact).unwrap();
let mut work = WorkBudget::new_protected(plan).unwrap();
let before = work.protected_report().unwrap();
let cancelled = CancelToken::default();
cancelled.cancel();
assert_eq!(work.charge_presentation(1, &cancelled), Err(TraceError::Cancelled));
assert_eq!(work.protected_report().unwrap(), before);
let cancel = CancelToken::default();
assert!(work.charge_presentation(1, &cancel).unwrap());
let paid = work.protected_report().unwrap();
cancel.cancel();
assert_eq!(work.tick(&cancel), Err(TraceError::Cancelled));
assert_eq!(work.charge_presentation(2, &cancel), Err(TraceError::Cancelled));
assert_eq!(work.protected_report().unwrap(), paid);
assert_eq!(work.used(), plan.snapshot_work().unwrap());
}
#[test]
fn protected_private_test_boundary_is_chosen_before_work_and_never_changes_the_production_plan() {
use crate::job::{CpuBudget, ProtectedPreviewPlan};
let plan = ProtectedPreviewPlan::new(4, 1, 5, CpuBudget::Compact).unwrap();
assert!(WorkBudget::new_protected_for_test(plan, 0).is_err());
assert!(WorkBudget::new_protected_for_test(plan, plan.ordinary_limit() + 1).is_err());
let mut first = WorkBudget::new_protected(plan).unwrap();
first.charge_presentation(19, &CancelToken::default()).unwrap();
let paid = first.protected_report().unwrap();
// A distinct admitted job starts a new ledger; it does not restore/transfer
// any state in the first job. Repeated report reads do not reset either one.
let second = WorkBudget::new_protected(plan).unwrap();
for _ in 0..4 {
assert_eq!(first.protected_report().unwrap(), paid);
}
assert_eq!(second.protected_report().unwrap().presentation_used, 0);
assert_eq!(first.protected_report().unwrap(), paid);
}
#[test]
fn protected_reached_milestones_match_literal_small_and_first_pass_boundaries() {
use crate::job::{CpuBudget, ProtectedPreviewPlan};
for (pixels, samples, cases) in [
(1, 1, vec![(0, 0), (1, 0)]),
(1, 7, vec![(0, 0), (1, 1), (5, 5), (6, 6), (7, 6)]),
(2, 4, vec![(0, 0), (1, 1), (2, 2), (3, 2), (4, 3), (5, 3), (6, 4), (7, 4), (8, 4)]),
(3, 4, vec![(0, 0), (1, 1), (2, 2), (3, 3), (4, 3), (5, 3), (6, 4), (8, 4), (9, 5), (11, 5), (12, 5)]),
(65, 3, vec![(0, 0), (63, 63), (64, 64), (65, 65), (129, 65), (130, 66), (194, 66), (195, 66)]),
(66, 3, vec![(0, 0), (64, 63), (65, 64), (66, 65), (131, 65), (132, 66), (197, 66), (198, 66)]),
(67, 3, vec![(0, 0), (65, 63), (66, 64), (67, 65), (133, 65), (134, 66), (200, 66), (201, 66)]),
] {
let plan = ProtectedPreviewPlan::new(pixels, 1, samples, CpuBudget::Compact).unwrap();
for (committed, expected) in cases {
assert_eq!(plan.reached_milestones(committed).unwrap(), expected, "P={pixels} S={samples} c={committed}");
}
assert!(plan.reached_milestones(plan.total_commits() + 1).is_err());
assert!(plan.reached_milestones(u64::MAX).is_err());
}
}
#[test]
fn protected_large_delayed_frontier_coalesces_once_without_allocating_a_film_or_spending_ordinary_work() {
use crate::job::{CpuBudget, ProtectedPreviewPlan};
let plan = ProtectedPreviewPlan::new(1, 1, 1_048_576, CpuBudget::Workstation).unwrap();
assert_eq!(plan.quota_limit(), 1_048_575);
assert_eq!(plan.reached_milestones(65_536).unwrap(), 65_536);
assert_eq!(plan.reached_milestones(1_048_575).unwrap(), 1_048_575);
assert_eq!(plan.reached_milestones(1_048_576).unwrap(), 1_048_575);
let mut work = WorkBudget::new_protected_for_test(plan, 17).unwrap();
assert!(work.charge_presentation(1_048_575, &CancelToken::default()).unwrap());
let report = work.protected_report().unwrap();
assert_eq!((report.accepted_snapshots, report.next_milestone_index), (1, 1_048_575));
assert_eq!(report.presentation_used, 65_552);
assert_eq!(report.ordinary_used, 0);
assert_eq!(work.ordinary_remaining(), 17);
assert!(report.milestones_complete && !report.quota_exhausted);
}
@@ -0,0 +1,857 @@
//! Transient CPU image controls; engine commands own file capture and admission.
use serde_json::{Value, json};
use solidcraft_engine::render::job::{CpuBudget, CpuDielectricTransport, RaytraceEnvironmentOptions, ReflectionBody, ReflectionMode};
use super::hdr;
use crate::{SolveApp, ui_kit};
pub(super) fn validate_progressive_image(app: &SolveApp) -> Result<(), String> {
if app.render_workspace.view.method == super::ImageMethod::CpuRaytrace {
let view = &app.render_workspace.view;
view.raytrace.budget.validate_image(view.draft.width, view.draft.height, view.raytrace.progressive).map_err(|error| error.to_string())?;
}
Ok(())
}
pub(super) fn image_limits(app: &SolveApp) -> solidcraft_engine::render::RenderLimits {
if app.render_workspace.view.method == super::ImageMethod::GpuRaytrace {
return solidcraft_engine::render::job::GPU_PATH_LIMITS;
}
if app.render_workspace.view.method != super::ImageMethod::CpuRaytrace {
return Default::default();
}
let options = &app.render_workspace.view.raytrace;
let mut limits = options.budget.image_limits(options.progressive.is_some());
if let Some(progressive) = options.progressive {
limits.max_pixels = limits.max_pixels.min(options.budget.limits().max_camera_samples / u64::from(progressive.samples_per_pixel.max(1)));
}
limits
}
fn budget_key(budget: CpuBudget) -> &'static str {
match budget {
CpuBudget::Compact => "render.children.compact",
CpuBudget::Studio => "render.children.studio",
CpuBudget::Workstation => "render.children.workstation",
}
}
fn budget_controls(app: &mut SolveApp, ui: &mut egui::Ui) {
let budgets = CpuBudget::ALL;
let mut selected = budgets.iter().position(|b| *b == app.render_workspace.view.raytrace.budget).unwrap_or(0);
let labels = budgets.map(|b| app.tr(budget_key(b)).to_string());
let response = ui.scope(|ui| {
ui_kit::segmented(
ui,
&mut selected,
&labels.iter().map(String::as_str).collect::<Vec<_>>(),
ui_kit::Segments {
compact: true,
targets: &["render.cpu_budget_compact", "render.cpu_budget_studio", "render.cpu_budget_workstation"],
..Default::default()
},
)
});
crate::scenario::publish_rect("render:cpu-budget", response.response.rect);
if response.inner
&& let Some(budget) = budgets.get(selected)
{
app.render_workspace.view.raytrace.budget = *budget;
app.render_workspace.view.dirty = true;
}
let limits = app.render_workspace.view.raytrace.budget.limits();
let note = format!(
"{}: {:.2} GiB · {}: {} · {}: {} · {}: {}. {}",
app.tr("render.cpu_budget_memory"),
limits.max_job_bytes as f64 / 1_073_741_824.0,
app.tr("render.cpu_budget_triangles"),
limits.max_triangles,
app.tr("render.cpu_budget_bodies"),
limits.max_bodies,
app.tr("render.cpu_progressive_spp"),
limits.max_samples_per_pixel,
app.tr("render.cpu_budget_not_guarantee")
);
ui_kit::text(ui, &note, ui_kit::Text::Note("render.cpu_budget_help"));
}
fn set_progressive(app: &mut SolveApp, enabled: bool) {
let options = &mut app.render_workspace.view.raytrace;
if enabled {
options.progressive.get_or_insert_default();
options.primary_samples = 1;
} else {
options.progressive = None;
}
app.render_workspace.view.dirty = true;
}
/// The saved CPU choice is independent of sampling, profiles and material bindings.
fn set_dielectric_transport(app: &mut SolveApp, policy: CpuDielectricTransport) -> bool {
let view = &mut app.render_workspace.view;
if view.raytrace.dielectric_transport == policy {
return false;
}
view.raytrace.dielectric_transport = policy;
view.dirty = true;
true
}
fn dielectric_controls(app: &mut SolveApp, ui: &mut egui::Ui) {
let mut selected = usize::from(app.render_workspace.view.raytrace.dielectric_transport == CpuDielectricTransport::StrictTir);
let labels = [app.tr("render.cpu_glass_standard").to_string(), app.tr("render.cpu_glass_continue").to_string()];
let label = app.tr("render.cpu_glass_label").to_string();
if ui_kit::row(ui, &label, |ui| {
ui_kit::segmented(
ui,
&mut selected,
&labels.iter().map(String::as_str).collect::<Vec<_>>(),
ui_kit::Segments { compact: true, targets: &["render:cpu-glass-standard", "render:cpu-glass-continue"], ..Default::default() },
)
}) {
set_dielectric_transport(app, if selected == 1 { CpuDielectricTransport::StrictTir } else { CpuDielectricTransport::LegacyBounded });
}
ui_kit::text(ui, app.tr("render.cpu_glass_help"), ui_kit::Text::Note("render.cpu_glass_help"));
}
pub(super) fn progressive_controls(app: &mut SolveApp, ui: &mut egui::Ui) -> bool {
budget_controls(app, ui);
dielectric_controls(app, ui);
let mut selected = usize::from(app.render_workspace.view.raytrace.progressive.is_some());
let labels = [app.tr("render.children.single_image").to_string(), app.tr("render.cpu_progressive").to_string()];
let response = ui.scope(|ui| {
ui_kit::row(ui, app.tr("render.children.sampling"), |ui| {
ui_kit::segmented(
ui,
&mut selected,
&labels.iter().map(String::as_str).collect::<Vec<_>>(),
ui_kit::Segments { compact: true, targets: &["render:cpu-fixed", "render:cpu-progressive"], ..Default::default() },
)
})
});
crate::scenario::publish_target("render:cpu-sampling", response.response.rect);
if response.inner {
set_progressive(app, selected == 1);
}
let enabled = app.render_workspace.view.raytrace.progressive.is_some();
let mut options = app.render_workspace.view.raytrace.progressive.unwrap_or_default();
if !enabled {
ui_kit::text(ui, app.tr("render.children.progressive_reason"), ui_kit::Text::Note("render.children.progressive_reason"));
}
ui.add_enabled_ui(enabled, |ui| {
let response = ui_kit::row(ui, app.tr("render.cpu_progressive_spp"), |ui| {
ui_kit::number_field(ui, &mut options.samples_per_pixel, 1..=solidcraft_engine::render::job::MAX_CPU_SAMPLES_PER_PIXEL, 1.0, "")
});
app.render_workspace.view.dirty |= response.changed();
crate::scenario::publish_target("render:cpu-spp", response.rect);
let response =
ui_kit::row(ui, app.tr("render.cpu_progressive_seed"), |ui| ui_kit::number_field(ui, &mut options.seed, 0..=u32::MAX, 1.0, ""));
app.render_workspace.view.dirty |= response.changed();
crate::scenario::publish_target("render:cpu-seed", response.rect);
});
if enabled {
app.render_workspace.view.raytrace.progressive = Some(options);
}
ui_kit::text(ui, app.tr("render.cpu_progressive_help"), ui_kit::Text::Note("render.cpu_progressive_help"));
enabled
}
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
pub(super) enum Environment {
#[default]
None,
Constant,
Hdr,
}
#[derive(Clone, Debug)]
pub(super) struct View {
#[cfg(test)]
pub selected_body: Option<String>,
#[cfg(test)]
pub body_filter: String,
pub environment: Environment,
pub hdr: hdr::Input,
pub rotation_rad: f64,
pub intensity: f64,
pub samples: u32,
pub color: [f64; 3],
pub checked: Option<Checked>,
/// Request-local, explicitly selected certified-box nesting; never inferred from GPU state.
pub nested_media: bool,
bindings: std::collections::BTreeMap<String, Binding>,
}
#[derive(Clone, Debug, PartialEq, Eq)]
struct Target {
ordinal: usize,
feature: u64,
component: u64,
}
#[derive(Clone, Debug)]
struct Binding {
target: Target,
revision: u64,
document: std::sync::Weak<solidcraft_engine::doc::Document>,
// Interactive may follow appearance/render-only edits only while this exact
// evaluated world survives in the same open document. Weak ownership avoids
// retaining old geometry and prevents pointer reuse after the world drops.
session_uid: u64,
world: std::sync::Weak<solidcraft_engine::doc::ModelState>,
}
#[derive(Clone, Debug)]
pub(super) struct Checked {
pub request: Value,
pub revision: u64,
pub environment: Value,
document: std::sync::Weak<solidcraft_engine::doc::Document>,
}
impl Default for View {
fn default() -> Self {
Self {
#[cfg(test)]
selected_body: None,
#[cfg(test)]
body_filter: String::new(),
environment: Environment::None,
hdr: hdr::Input::default(),
rotation_rad: 0.0,
intensity: 1.0,
samples: 16,
color: [1.0; 3],
checked: None,
nested_media: false,
bindings: Default::default(),
}
}
}
fn valid_name(name: &str) -> bool {
!name.is_empty() && name.len() <= 128 && !name.chars().any(char::is_control)
}
fn target(app: &SolveApp, name: &str) -> Option<Target> {
if !valid_name(name) || app.session.model.is_stale() {
return None;
}
let world = app.session.world_state();
let mut matches = world.bodies.iter().filter(|body| app.session.body_visible(&body.name)).enumerate().filter(|(_, body)| body.name == name);
let (ordinal, body) = matches.next()?;
if matches.next().is_some() {
return None;
}
Some(Target { ordinal, feature: body.feature, component: body.component })
}
fn unique_visible_body(app: &SolveApp, name: &str) -> bool {
target(app, name).is_some()
}
fn binding_current(app: &SolveApp, name: &str) -> bool {
app.render_workspace.view.cpu.bindings.get(name).is_some_and(|binding| {
binding.revision == app.session.revision
&& std::sync::Weak::ptr_eq(&binding.document, &std::sync::Arc::downgrade(&app.session.doc))
&& target(app, name).as_ref() == Some(&binding.target)
})
}
// Unlike final Check/Start, Interactive may refresh harmless appearance/render
// edits. The engine retains the exact world Arc for those edits (refresh_render).
// No geometry extraction, cold meshing, name-only rebinding or revision stamping.
fn binding_interactive_world_current(app: &SolveApp, name: &str) -> bool {
app.render_workspace.view.cpu.bindings.get(name).is_some_and(|binding| {
binding.session_uid == app.session.uid
&& !app.session.model.is_stale()
&& app
.session
.interactive_cached_world_state()
.is_some_and(|world| std::sync::Weak::ptr_eq(&binding.world, &std::sync::Arc::downgrade(&world)))
})
}
fn binding_interactive_current(app: &SolveApp, name: &str) -> bool {
binding_interactive_world_current(app, name)
&& app.render_workspace.view.cpu.bindings.get(name).is_some_and(|binding| target(app, name).as_ref() == Some(&binding.target))
}
pub(super) fn revalidate(app: &mut SolveApp, name: &str) -> Result<(), String> {
let current = target(app, name).ok_or_else(|| app.tr("render.cpu_body_missing").to_string())?;
if app.render_workspace.view.cpu.bindings.get(name).is_none_or(|binding| binding.target != current) {
return Err(app.tr("render.cpu_body_missing").to_string());
}
let revision = app.session.revision;
let document = std::sync::Arc::downgrade(&app.session.doc);
let world = std::sync::Arc::downgrade(&app.session.world_state());
let session_uid = app.session.uid;
if let Some(binding) = app.render_workspace.view.cpu.bindings.get_mut(name) {
binding.revision = revision;
binding.document = document;
binding.session_uid = session_uid;
binding.world = world;
}
Ok(())
}
/// A removed, hidden or ambiguous body never silently becomes a different target.
pub(super) fn set_reflection(app: &mut SolveApp, name: &str, mode: Option<ReflectionMode>) -> Result<(), String> {
let selected = if mode.is_some() { Some(target(app, name).ok_or_else(|| app.tr("render.cpu_body_missing").to_string())?) } else { None };
// Changing the mode of an existing row is not a new body selection. Only an
// explicit confirmation of the same target, or Off followed by Add, may
// establish a fresh binding after the document or body identity changes.
if mode.is_some()
&& app.render_workspace.view.raytrace.reflections.as_ref().is_some_and(|r| r.bodies.iter().any(|entry| entry.body == name))
&& !binding_current(app, name)
{
return Err(app.tr("render.cpu_binding_stale").to_string());
}
let message = app.tr("render.cpu_reflection_limit").to_string();
let options = &mut app.render_workspace.view.raytrace;
if let Some(mode) = mode {
let mut reflections = options.reflections.clone().unwrap_or_default();
if let Some(entry) = reflections.bodies.iter_mut().find(|entry| entry.body == name) {
entry.mode = mode;
} else {
if reflections.bodies.len() >= 64 {
return Err(message);
}
reflections.bodies.try_reserve_exact(1).map_err(|_| message.clone())?;
if reflections.bodies.capacity() > 64 {
return Err(message);
}
reflections.bodies.push(ReflectionBody { body: name.to_string(), mode });
}
options.reflections = Some(reflections);
} else if let Some(reflections) = &mut options.reflections {
reflections.bodies.retain(|entry| entry.body != name);
if reflections.bodies.is_empty() {
options.reflections = None;
}
}
if let Some(target) = selected {
app.render_workspace.view.cpu.bindings.insert(
name.to_string(),
Binding {
target,
revision: app.session.revision,
document: std::sync::Arc::downgrade(&app.session.doc),
session_uid: app.session.uid,
world: std::sync::Arc::downgrade(&app.session.world_state()),
},
);
} else {
app.render_workspace.view.cpu.bindings.remove(name);
}
Ok(())
}
/// Shared by the parent Check and Start builder. This does not read an HDR file.
pub(super) fn params(app: &SolveApp, params: &mut Value) -> Result<(), String> {
params_with_binding_policy(app, params, binding_current)
}
/// Interactive-only wire lowering. This does not requalify final Check/Start,
/// change a stored binding or read an HDR file; the engine still captures and admits it.
pub(super) fn params_interactive(app: &SolveApp, params: &mut Value) -> Result<(), String> {
// runtime_image_request composes the explicit material DTO immediately
// after these numerical controls, exactly once. The engine then converts
// the separate Interactive request to progressive sampling and admits its
// complete optics; a Fixed editor never licenses dropping that intent.
// Refuse unproved bound worlds before shared lowering checks visibility via
// target()/world_state(). Empty reflections never require a warm world.
if app
.render_workspace
.view
.raytrace
.reflections
.as_ref()
.is_some_and(|r| r.bodies.iter().any(|entry| !binding_interactive_world_current(app, &entry.body)))
{
return Err(app.tr("render.cpu_binding_stale").to_string());
}
params_with_binding_policy(app, params, binding_interactive_current)
}
fn params_with_binding_policy(app: &SolveApp, params: &mut Value, current: fn(&SolveApp, &str) -> bool) -> Result<(), String> {
let base = &app.render_workspace.view.raytrace;
if base.anisotropic_faces.iter().any(Option::is_some)
|| !base.dielectrics.is_empty()
|| base.environment.is_some()
|| base.surface_effects.is_some()
|| base.emissions.is_some()
{
return Err(app.tr("render.cpu_options_pending").to_string());
}
if base.reflections.as_ref().is_some_and(|r| r.bodies.iter().any(|entry| !unique_visible_body(app, &entry.body))) {
return Err(app.tr("render.cpu_body_missing").to_string());
}
if base.reflections.as_ref().is_some_and(|r| r.bodies.iter().any(|entry| !current(app, &entry.body))) {
return Err(app.tr("render.cpu_binding_stale").to_string());
}
let view = &app.render_workspace.view.cpu;
let mut options = base.clone();
if options.area_samples.is_some_and(|n| !matches!(n, 1 | 4 | 16 | 64)) {
return Err(crate::i18n::tr("render.error_area_samples").into());
}
if options.area_lights.as_ref().is_none_or(Vec::is_empty) {
options.area_samples = None;
options.seed = None;
}
options.exposure_ev = app.render_workspace.view.draft.exposure_ev;
// Runtime CPU requests keep the same single saved EV authority as typed jobs.
params["settings"]["exposure_ev"] = json!(0.0);
if view.environment != Environment::None {
if !view.intensity.is_finite() || !(0.0..=64.0).contains(&view.intensity) {
return Err(app.tr("render.cpu_environment_bounds").to_string());
}
match view.environment {
Environment::Constant => options.environment = Some(RaytraceEnvironmentOptions { color: view.color, intensity: view.intensity }),
Environment::Hdr => {
if !view.rotation_rad.is_finite() || view.rotation_rad.abs() > 1e6 || !matches!(view.samples, 1 | 4 | 16 | 64) {
return Err(app.tr("render.cpu_environment_bounds").to_string());
}
let mut environment = hdr::request(app, hdr::Target::Cpu)?;
environment["rotation_radians"] = json!(view.rotation_rad);
environment["intensity"] = json!(view.intensity);
environment["samples"] = json!(view.samples);
params["environment"] = environment;
}
Environment::None => {}
}
}
options.validate().map_err(|error| error.to_string())?;
params["integrator"] = json!("raytrace");
params["raytrace"] = json!(options);
Ok(())
}
#[cfg(test)]
pub(super) fn controls(app: &mut SolveApp, ui: &mut egui::Ui) {
for (id, key, section) in [
("render_cpu_reflections", "render.cpu_reflections", 0),
("render_cpu_environment", "render.cpu_environment", 1),
("render_cpu_lights", "render.cpu_lights", 2),
] {
let title = app.tr(key).to_string();
ui_kit::section(ui, id, &title, false, |ui| match section {
0 => reflection_controls(app, ui),
1 => environment_controls(app, ui),
_ => light_controls(app, ui),
});
}
ui.small(app.tr("render.cpu_runtime_help"));
}
#[cfg(test)]
pub(super) fn reflection_controls(app: &mut SolveApp, ui: &mut egui::Ui) {
ui.small(app.tr("render.cpu_reflection_help"));
let entries = app.render_workspace.view.raytrace.reflections.as_ref().map(|r| r.bodies.clone()).unwrap_or_default();
for entry in entries {
ui.label(&entry.body);
if !binding_current(app, &entry.body) {
ui.small(app.tr("render.cpu_binding_stale"));
if ui_kit::button(ui, app.tr("render.cpu_binding_confirm"), ui_kit::Button::Normal).clicked()
&& let Err(error) = revalidate(app, &entry.body)
{
app.set_status(error, true);
}
}
let selected = match entry.mode {
ReflectionMode::Mirror => "render.cpu_reflection_mirror",
ReflectionMode::RoughSpecular => "render.cpu_reflection_rough",
};
let label = app.tr(selected).to_string();
let mode_control = ui_kit::dropdown_menu(ui, ("cpu_reflection_mode", &entry.body), &label, |ui| {
for (mode, key) in [
(None, "render.cpu_reflection_off"),
(Some(ReflectionMode::Mirror), "render.cpu_reflection_mirror"),
(Some(ReflectionMode::RoughSpecular), "render.cpu_reflection_rough"),
] {
let enabled = mode.is_none() || binding_current(app, &entry.body);
if ui.add_enabled_ui(enabled, |ui| ui_kit::list_picker(ui, key, app.tr(key), mode == Some(entry.mode))).inner.clicked() {
if let Err(error) = set_reflection(app, &entry.body, mode) {
app.set_status(error, true);
}
ui.close();
}
}
});
crate::scenario::publish_handle(&format!("render:cpu-reflection-mode:{}", entry.body), mode_control.rect.center());
}
let hint = app.tr("render.cpu_body_filter").to_string();
ui_kit::bounded_cell_editor(ui, ui.id().with("cpu_body_filter"), &mut app.render_workspace.view.cpu.body_filter, &hint, false, 128);
let selected = app.render_workspace.view.cpu.selected_body.clone();
let label = selected.clone().unwrap_or_else(|| app.tr("render.cpu_body_choose").to_string());
let world = app.session.world_state();
let filter = app.render_workspace.view.cpu.body_filter.to_lowercase();
let candidates: Vec<_> = world
.bodies
.iter()
.filter(|body| app.session.body_visible(&body.name) && body.name.to_lowercase().contains(&filter))
.take(257)
.map(|body| body.name.as_str())
.collect();
let dropdown = ui_kit::dropdown_menu(ui, "cpu_reflection_body", &label, |ui| {
egui::ScrollArea::vertical().max_height(240.0).show(ui, |ui| {
for (shown, name) in candidates.iter().enumerate() {
if shown == 256 {
ui.small(app.tr("render.cpu_body_filter_more"));
break;
}
let response =
ui.add_enabled_ui(valid_name(name), |ui| ui_kit::list_picker(ui, name, name, selected.as_deref() == Some(*name))).inner;
if response.clicked() {
app.render_workspace.view.cpu.selected_body = Some((*name).to_string());
ui.close();
}
}
});
});
crate::scenario::publish_handle("render:cpu-reflection-body", dropdown.rect.center());
let can_add = selected.as_ref().is_some_and(|name| unique_visible_body(app, name))
&& app.render_workspace.view.raytrace.reflections.as_ref().is_none_or(|r| r.bodies.len() < 64);
let add = ui_kit::button(ui, app.tr("render.cpu_reflection_add"), ui_kit::Button::Enabled(can_add));
crate::scenario::publish_handle("render:cpu-reflection-add", add.rect.center());
if add.clicked()
&& let Some(name) = selected
&& let Err(error) = set_reflection(app, &name, Some(ReflectionMode::RoughSpecular))
{
app.set_status(error, true);
}
reflection_sampling_controls(app, ui);
}
/// Existing global reflection budget, shared during the Sampling-editor migration.
pub(super) fn reflection_sampling_controls(app: &mut SolveApp, ui: &mut egui::Ui) {
let depth = app.tr("render.cpu_reflection_depth").to_string();
let samples = app.tr("render.cpu_reflection_samples").to_string();
if let Some(reflections) = &mut app.render_workspace.view.raytrace.reflections {
ui_kit::row(ui, &depth, |ui| ui_kit::number_field(ui, &mut reflections.max_bounces, 1..=8, 1.0, ""));
ui_kit::row(ui, &samples, |ui| ui_kit::number_field(ui, &mut reflections.samples, 1..=64, 1.0, ""));
} else {
ui.small(app.tr("render.cpu_reflection_empty"));
}
}
#[cfg(test)]
pub(super) fn environment_controls(app: &mut SolveApp, ui: &mut egui::Ui) {
let selected = app.render_workspace.view.cpu.environment;
let key = match selected {
Environment::None => "render.cpu_environment_none",
Environment::Constant => "render.cpu_environment_constant",
Environment::Hdr => "render.studio_hdr",
};
let label = app.tr(key).to_string();
ui_kit::dropdown_menu(ui, "cpu_environment_kind", &label, |ui| {
for (value, key) in [
(Environment::None, "render.cpu_environment_none"),
(Environment::Constant, "render.cpu_environment_constant"),
(Environment::Hdr, "render.studio_hdr"),
] {
if ui_kit::list_picker(ui, key, app.tr(key), value == selected).clicked() {
app.render_workspace.view.cpu.environment = value;
ui.close();
}
}
});
if app.render_workspace.view.cpu.environment == Environment::None {
return;
}
if app.render_workspace.view.cpu.environment == Environment::Constant {
let color = app.tr("render.cpu_linear_color").to_string();
vector(ui, &color, &mut app.render_workspace.view.cpu.color, 0.0..=1.0, 0.01, "");
ui.small(app.tr("render.cpu_constant_help"));
} else {
hdr::controls(app, ui, hdr::Target::Cpu);
ui.small(app.tr("render.cpu_hdr_help"));
ui.label(app.tr("render.studio_rotation"));
let mut degrees = app.render_workspace.view.cpu.rotation_rad.to_degrees();
if ui_kit::number_field(ui, &mut degrees, -1e6_f64.to_degrees()..=1e6_f64.to_degrees(), 1.0, "°").changed() {
app.render_workspace.view.cpu.rotation_rad = degrees.to_radians();
}
ui.label(app.tr("render.cpu_environment_samples"));
let samples = app.render_workspace.view.cpu.samples;
ui_kit::dropdown_menu(ui, "cpu_hdr_samples", &samples.to_string(), |ui| {
for value in [1, 4, 16, 64] {
if ui_kit::list_picker(ui, &value.to_string(), &value.to_string(), value == samples).clicked() {
app.render_workspace.view.cpu.samples = value;
ui.close();
}
}
});
ui.small(app.tr("render.cpu_hdr_reflection_help"));
}
ui.label(app.tr("render.studio_intensity"));
ui_kit::number_field(ui, &mut app.render_workspace.view.cpu.intensity, 0.0..=64.0, 0.1, "");
ui.small(app.tr("render.cpu_environment_background"));
}
#[cfg(test)]
fn vector(ui: &mut egui::Ui, label: &str, value: &mut [f64; 3], range: std::ops::RangeInclusive<f64>, speed: f64, suffix: &str) {
ui.label(label);
ui.horizontal(|ui| {
for component in value {
ui_kit::number_field(ui, component, range.clone(), speed, suffix);
}
});
}
#[cfg(test)]
pub(super) fn light_controls(app: &mut SolveApp, ui: &mut egui::Ui) {
super::light::lighting(app, ui);
}
pub(super) fn record_checked(app: &mut SolveApp, params: &Value, reply: &Value) {
if params["integrator"] == "raytrace" || params["settings"]["job"]["method"] == "cpu_raytrace" {
app.render_workspace.view.cpu.checked = Some(Checked {
request: params.clone(),
revision: app.session.revision,
environment: reply["environment"].clone(),
document: std::sync::Arc::downgrade(&app.session.doc),
});
}
}
fn metadata(app: &SolveApp, ui: &mut egui::Ui, info: &Value) {
let Some(hash) = info["source_sha256"].as_array().filter(|hash| hash.len() == 32) else { return };
let digest: Option<Vec<_>> = hash.iter().map(|byte| byte.as_u64().and_then(|n| u8::try_from(n).ok())).collect();
let Some(digest) = digest else { return };
let digest: String = digest.into_iter().map(|byte| format!("{byte:02x}")).collect();
let width = info["header"]["width"].as_u64().unwrap_or(0);
let height = info["header"]["height"].as_u64().unwrap_or(0);
ui.label(format!("{width} × {height} px"));
ui.label(format!("{}: {}", app.tr("render.cpu_environment_samples"), info["samples"].as_u64().unwrap_or(0)));
ui.label(format!("{}: {:.2}", app.tr("render.studio_intensity"), info["intensity"].as_f64().unwrap_or(0.0)));
ui.label(format!("{}: {:.1}°", app.tr("render.studio_rotation"), info["rotation_radians"].as_f64().unwrap_or(0.0).to_degrees()));
ui.label(format!("SHA-256: {digest}"));
}
pub(super) fn checked_status(app: &SolveApp, ui: &mut egui::Ui, params: Option<&Value>) {
if app.render_workspace.view.method != super::ImageMethod::CpuRaytrace {
return;
}
if let Some(checked) = &app.render_workspace.view.cpu.checked {
let title = app.tr("render.cpu_last_check").to_string();
ui_kit::section(ui, "cpu_last_check", &title, false, |ui| {
if params != Some(&checked.request)
|| checked.revision != app.session.revision
|| !std::sync::Weak::ptr_eq(&checked.document, &std::sync::Arc::downgrade(&app.session.doc))
{
ui.small(app.tr("render.cpu_check_changed"));
}
metadata(app, ui, &checked.environment);
ui.small(app.tr("render.cpu_check_capture_help"));
});
}
}
pub(super) fn captured_status(app: &SolveApp, ui: &mut egui::Ui, status: &Value) {
if status["request"]["integrator"] == "raytrace" && status["environment"]["source_sha256"].is_array() {
let title = app.tr("render.cpu_captured_hdr").to_string();
ui_kit::section(ui, "cpu_captured_hdr", &title, false, |ui| metadata(app, ui, &status["environment"]));
}
}
#[cfg(test)]
fn dielectric_policy_harness() -> crate::scenario::Harness {
let mut h = crate::scenario::Harness::new();
h.app.ui.tab = "RENDER".into();
h.app.render_workspace.view.method = super::ImageMethod::CpuRaytrace;
h.app.render_workspace.view.result = false;
h.app.render_workspace.view.name = "Policy".into();
h.app.render_workspace.view.draft.width = 1;
h.app.render_workspace.view.draft.height = 1;
h.app.render_workspace.view.draft.exposure_ev = 0.0;
h.app.render_workspace.view.raytrace = Default::default();
h.app.render_workspace.view.cpu = View::default();
h
}
#[cfg(test)]
#[test]
fn cpu_glass_policy_no_binding_ui_snapshot_save_reopen_load_preserves_portable_choice() {
use solidcraft_engine::doc::render_settings::RenderJob;
let mut h = dielectric_policy_harness();
assert!(!set_dielectric_transport(&mut h.app, CpuDielectricTransport::LegacyBounded));
assert!(set_dielectric_transport(&mut h.app, CpuDielectricTransport::StrictTir));
assert!(h.app.render_workspace.view.dirty);
assert!(!super::setups::has_runtime_inputs(&h.app), "the choice itself is portable");
let saved = super::setups::snapshot(&h.app).unwrap();
let Some(RenderJob::CpuRaytrace { options }) = &saved.job else { panic!("CPU draft changed method") };
assert_eq!(options.dielectric_transport, CpuDielectricTransport::StrictTir);
let wire = super::image_request(&h.app).unwrap();
assert_eq!(wire["settings"]["job"]["options"]["dielectric_transport"], "strict_tir");
super::setups::save(&mut h.app).unwrap();
let document = solidcraft_engine::doc::Document::from_json(&h.app.session.doc.to_json()).unwrap();
h.app.session = solidcraft_engine::Session::new(document);
h.app.render_workspace.view.raytrace.dielectric_transport = CpuDielectricTransport::LegacyBounded;
super::setups::load(&mut h.app);
assert_eq!(h.app.render_workspace.view.raytrace.dielectric_transport, CpuDielectricTransport::StrictTir);
assert_eq!(super::setups::snapshot(&h.app).unwrap(), saved);
assert_eq!(super::image_request(&h.app).unwrap()["settings"]["job"]["options"]["dielectric_transport"], "strict_tir");
assert!(set_dielectric_transport(&mut h.app, CpuDielectricTransport::LegacyBounded));
assert!(serde_json::to_value(super::setups::snapshot(&h.app).unwrap()).unwrap()["job"]["options"].get("dielectric_transport").is_none());
}
#[cfg(test)]
#[test]
fn cpu_glass_policy_numeric_lowering_and_active_light_filter_preserve_the_exact_choice() {
use solidcraft_engine::render::job::DirectionalLightOptions;
let mut h = dielectric_policy_harness();
h.app.render_workspace.view.raytrace.lights = Some(vec![DirectionalLightOptions { direction: [0.0, 0.0, 1.0], color: [1.0; 3], intensity: 2.0 }]);
h.app.render_workspace.view.lights.visibility.muted.insert("directional:0".into());
for policy in [CpuDielectricTransport::LegacyBounded, CpuDielectricTransport::StrictTir] {
set_dielectric_transport(&mut h.app, policy);
let source = h.app.render_workspace.view.raytrace.clone();
for interactive in [false, true] {
let mut wire = json!({"settings":{"job":null}});
if interactive {
params_interactive(&h.app, &mut wire).unwrap();
} else {
params(&h.app, &mut wire).unwrap();
}
super::materials::params(&h.app, &mut wire).unwrap();
let wire = super::light::filter_request(&h.app, wire).unwrap();
let options: solidcraft_engine::render::job::RaytraceOptions = serde_json::from_value(wire["raytrace"].clone()).unwrap();
assert_eq!(options.dielectric_transport, policy);
assert_eq!(options.lights.as_ref().unwrap()[0].intensity, 0.0);
assert_eq!(h.app.render_workspace.view.raytrace, source, "transient visibility must not rewrite authored input");
}
let portable = super::image_request(&h.app).unwrap();
let options: solidcraft_engine::doc::render_settings::CpuJob =
serde_json::from_value(portable["settings"]["job"]["options"].clone()).unwrap();
assert_eq!(options.dielectric_transport, policy);
}
}
#[cfg(test)]
#[test]
fn cpu_glass_policy_selection_preserves_unsupported_opaque_reflection_and_advanced_intent() {
use solidcraft_engine::render::job::{EmissionSides, SurfaceEmission};
let mut h = dielectric_policy_harness();
h.app.session.execute("solid.box", &json!({"length":20,"width":20,"height":10})).unwrap();
h.app.session.execute("render.scene", &json!({})).unwrap();
let target = super::materials::read_targets(&mut h.app).unwrap().remove(0);
set_reflection(&mut h.app, &target.name, Some(ReflectionMode::Mirror)).unwrap();
let authored = h.app.render_workspace.view.raytrace.clone();
set_dielectric_transport(&mut h.app, CpuDielectricTransport::StrictTir);
assert_eq!(h.app.render_workspace.view.raytrace.reflections, authored.reflections);
assert!(super::image_request(&h.app).is_err());
assert!(super::interactive_request(&h.app).is_err());
assert_eq!(h.app.render_workspace.view.raytrace.reflections, authored.reflections);
assert_eq!(h.app.render_workspace.view.raytrace.dielectric_transport, CpuDielectricTransport::StrictTir);
h.app.render_workspace.view.raytrace.reflections = None;
h.app.render_workspace.view.raytrace.emissions = Some(vec![SurfaceEmission {
body_index: target.ordinal,
body: target.name,
color: [1.0, 0.5, 0.25],
strength: 1.0,
sides: EmissionSides::Front,
}]);
let authored = h.app.render_workspace.view.raytrace.clone();
assert!(super::image_request(&h.app).is_err());
assert!(super::interactive_request(&h.app).is_err());
assert_eq!(h.app.render_workspace.view.raytrace, authored);
}
#[cfg(all(test, not(target_arch = "wasm32")))]
#[test]
fn native_cpu_glass_policy_public_ui_check_start_and_interactive_preserve_real_material_and_visibility() {
use solidcraft_engine::render::job::interactive::VisualRevision;
use solidcraft_engine::render::job::{CpuHost, CpuProgressiveOptions, DirectionalLightOptions, HostKind, Integrator, JobId, Phase};
use solidcraft_engine::schema::render_ui::Action;
use std::time::Duration;
let host = CpuHost::for_platform().unwrap();
assert_eq!(host.kind(), HostKind::NativeWorker);
host.validate_integrator(Integrator::Raytrace).unwrap();
eprintln!("CPU_GLASS_POLICY_UI_BRANCH cpu_supported=true");
for policy in [CpuDielectricTransport::LegacyBounded, CpuDielectricTransport::StrictTir] {
let mut h = dielectric_policy_harness();
h.app.session.set_render_job_host(Some(host.clone())).unwrap();
h.app.session.execute("solid.box", &json!({"length":20,"width":20,"height":10})).unwrap();
h.app.session.execute("render.scene", &json!({})).unwrap();
set_dielectric_transport(&mut h.app, policy);
h.app.render_workspace.view.raytrace.lights =
Some(vec![DirectionalLightOptions { direction: [0.0, 0.0, 1.0], color: [1.0; 3], intensity: 2.0 }]);
h.app.render_workspace.view.lights.visibility.muted.insert("directional:0".into());
let target = super::materials::read_targets(&mut h.app).unwrap().remove(0);
let mut binding = super::materials::Binding::new(target, &h.app);
binding.glass_enabled = true;
binding.cpu_optics = true;
// Explicit index-matched certified box: this is capture/consumer
// acceptance, not a new oracle for general reflective glass quality.
binding.glass.ior = 1.0;
binding.glass.boundary = super::materials::Boundary::Box;
binding.glass.thickness = 0.0;
h.app.render_workspace.view.materials.enabled = true;
h.app.render_workspace.view.materials.bindings.push(binding);
assert!(super::setups::snapshot(&h.app).is_err(), "captured body bindings remain runtime-only");
for progressive in [false, true] {
h.app.render_workspace.view.raytrace.progressive = progressive.then_some(CpuProgressiveOptions { samples_per_pixel: 3, seed: 411 });
let wire = super::image_request(&h.app).unwrap();
assert_eq!(wire["raytrace"]["dielectrics"].as_array().unwrap().len(), 1);
let checked = h.app.session.execute("render.preflight", &wire).unwrap();
record_checked(&mut h.app, &wire, &checked);
let revision = h.app.session.revision;
let other =
if policy == CpuDielectricTransport::StrictTir { CpuDielectricTransport::LegacyBounded } else { CpuDielectricTransport::StrictTir };
set_dielectric_transport(&mut h.app, other);
assert_ne!(Some(&super::image_request(&h.app).unwrap()), h.app.render_workspace.view.cpu.checked.as_ref().map(|c| &c.request));
assert_eq!(h.app.session.revision, revision);
set_dielectric_transport(&mut h.app, policy);
let started = h.app.session.execute("render.start", &wire).unwrap();
let id: JobId = serde_json::from_value(started["job"].clone()).unwrap();
let final_handle = h.app.session.render_job_handle(id).unwrap();
let final_status = final_handle.wait_timeout(Duration::from_secs(60)).unwrap();
assert_eq!(final_status.progress.phase, Phase::Completed, "{:?}", final_status.error);
assert_eq!(json!(final_status.request), checked["request"]);
assert_eq!(final_status.request.raytrace.as_ref().unwrap().dielectric_transport, policy);
assert!(final_handle.frame().unwrap().is_some());
let preview_wire = super::interactive_request(&h.app).unwrap();
let context = h.app.session.interactive_render().unwrap();
context.enable(VisualRevision { scene_generation: revision, visual_revision: 1 }, Duration::ZERO).unwrap();
let ticket = context.capture(Duration::from_millis(201)).unwrap().unwrap();
assert!(context.snapshot(&h.app.session, ticket, &preview_wire).unwrap().run().unwrap());
let preview_handle = context.current().unwrap().unwrap();
let status = preview_handle.wait_timeout(Duration::from_secs(60)).unwrap();
assert_eq!(status.progress.phase, Phase::Completed, "{:?}", status.error);
let captured = status.request.raytrace.as_ref().unwrap();
assert_eq!(captured.dielectric_transport, policy);
assert_eq!(captured.dielectrics, final_status.request.raytrace.as_ref().unwrap().dielectrics);
assert_eq!(captured.lights.as_ref().unwrap()[0].intensity, 0.0);
assert_ne!(status.job, final_status.job);
assert!(final_handle.frame().unwrap().is_some(), "Interactive cannot replace the final source");
context.disable().unwrap();
}
// Exercise actual UI intent observation while paused, without a fake
// receiver or a second capture worker. No timer result is asserted.
super::interactive::apply_command(&mut h.app, Action::On).unwrap();
let before = super::interactive::inspect(&h.app)["visual_revision"].as_u64().unwrap();
super::interactive::apply_command(&mut h.app, Action::Pause).unwrap();
let revision = h.app.session.revision;
set_dielectric_transport(
&mut h.app,
if policy == CpuDielectricTransport::StrictTir { CpuDielectricTransport::LegacyBounded } else { CpuDielectricTransport::StrictTir },
);
super::interactive::apply_command(&mut h.app, Action::Resume).unwrap();
assert!(super::interactive::inspect(&h.app)["visual_revision"].as_u64().unwrap() > before);
assert_eq!(h.app.session.revision, revision);
super::interactive::apply_command(&mut h.app, Action::Off).unwrap();
h.app.render_workspace.view.materials.bindings[0].glass.shadows = true;
let shadow_wire = super::image_request(&h.app).unwrap();
let shadow_options: solidcraft_engine::render::job::RaytraceOptions = serde_json::from_value(shadow_wire["raytrace"].clone()).unwrap();
assert!(shadow_options.directional_shadow_transmission);
assert!(shadow_options.shadows);
assert_eq!(shadow_options.dielectric_transport, h.app.render_workspace.view.raytrace.dielectric_transport);
assert_eq!(shadow_options.dielectrics[0].ior, 1.0);
let shadow_check = h.app.session.execute("render.preflight", &shadow_wire).unwrap();
let shadow_request: solidcraft_engine::render::job::ImageRequest = serde_json::from_value(shadow_check["request"].clone()).unwrap();
assert_eq!(shadow_request.raytrace.as_ref(), Some(&shadow_options));
assert!(!h.app.render_workspace.view.raytrace.directional_shadow_transmission, "the bridge is request-local");
assert!(h.app.render_workspace.view.materials.bindings[0].glass.shadows);
h.app.render_workspace.view.materials.bindings[0].glass.shadows = false;
h.app.render_workspace.view.materials.bindings[0].maps_enabled = true;
assert!(super::interactive_request(&h.app).is_err());
assert!(h.app.render_workspace.view.materials.bindings[0].maps_enabled);
}
}
@@ -0,0 +1,228 @@
# CPU progressive camera sampling
The limits below describe the compatibility **Compact** profile. Explicit Studio and Workstation envelopes are documented in [CPU resource profiles](render-cpu-resource-profiles.md); their implementation batch still requires consolidated validation.
The every-pass cadence and bounded snapshot policy below describe a composed
source proposal awaiting integration and validation, not a new native display or
CI result. The earlier published policy used powers-of-two checkpoints. This is
an intentional requested behavior change; its default-change classification and
preference handling remain unresolved before production readiness. This document
does not settle that process question.
CPU progressive rendering repeatedly traces fresh camera samples into a bounded
linear-light film. Each complete nonfinal pass, 1 through the requested count
minus one, is a checkpoint boundary. Normal consumption publishes each boundary;
the diagnosed external-retention exception is defined below. The exact requested
count produces one final PNG, including non-powers of two such as 3 or 5. A
one-sample job has no nonfinal complete-pass checkpoint. Optional first-pass
partial-coverage feedback is separate from a uniform checkpoint. Publication
does not guarantee that a slower client physically repaints every image.
This mode uses the native `cpu-raytrace` executor and its existing direct-light
and selected-reflection transport. It does not add diffuse global illumination,
caustics, adaptive convergence, a denoiser, or general glass path tracing.
## Request and saved intent
The CPU option is nested inside `raytrace`. The top-level `progressive: true`
request continues to select the registered GPU path executor.
```json
{
"integrator": "raytrace",
"settings": { "width": 512, "height": 512 },
"raytrace": {
"progressive": { "samples_per_pixel": 32, "seed": 81 },
"primary_samples": 1,
"exposure_ev": 0,
"shadows": true
}
}
```
Both `render.preflight` and `render.start` use this request. Missing or null
`raytrace.progressive` preserves the existing fixed 1/4/16 spatial AA route.
An explicit empty progressive object defaults to 16 samples and seed 0. The
seed is an unsigned 32-bit integer. Unknown fields are rejected.
The corresponding portable setup is:
```json
{
"name": "CPU film",
"set": {
"width": 512,
"height": 512,
"exposure_ev": 1,
"job": {
"method": "cpu_raytrace",
"options": {
"progressive": { "samples_per_pixel": 32, "seed": 81 },
"primary_samples": 1
}
}
}
}
```
This is a `render.settings.set` request. Exposure is stored once in the setup;
normalization transfers it into the CPU request. Film storage, checkpoint PNGs,
job identities, cancellation state and host reservations are never serialized
into the design. Saving validates pixel and camera-sample bounds even when no
render host is installed.
## Supported combinations and limits
| Control | CPU progressive contract |
| --- | --- |
| Dimensions | Each side 1..4096; at most 1,048,576 pixels |
| Samples per pixel | 1..64 |
| Total camera samples | At most 16,777,216 (`width × height × samples_per_pixel`) |
| Fixed spatial AA | `primary_samples` must be 1 |
| Selected mirror / isotropic rough reflection | Existing bounded depth; `reflections.samples` must be 1 when bodies are selected |
| Directional / point / spot sources | Existing CPU light contracts and limits |
| Constant / captured HDR environment | Existing CPU contracts; HDR plus rough reflections still requires certified fully metallic selected bodies and effective faces |
| Surface emission / isotropic surface effects | Existing CPU appearance contracts; emission is visible radiance |
| Area / LED sources | Existing bounded rectangle direct-light transport; continuous LED recipes lower to the same sources |
| Dielectric overrides | Smooth `thin_sheet` / `closed_box` intent retained; capture certifies geometry, identity and supported combinations |
| Anisotropic face overrides | Explicitly rejected in progressive mode; use fixed sampling |
| Output | Opaque PNG with the existing display background |
An incompatible request fails; it does not remove settings or switch methods.
The fixed CPU route retains its existing area, dielectric and anisotropy support.
Numerically valid dielectric selectors also survive progressive and Interactive
lowering for capture-time certification. Successful lowering is not scene or job
admission: existing boundary tessellation, captured identity, opacity, camera,
medium and transport-policy limits still apply. The same dielectric body cannot
also select opaque reflection, anisotropy, surface emission or nonidentity surface
effects. Unsupported combinations remain errors; no general glass path is added.
Progressive area/LED uses at most four shared rectangle slots, with
`area_samples` of 1/4/16/64 (default 16) and the existing combined light caps.
Each film pass uses the existing area-power normalization and cumulative work
budget; increasing emitter samples does not multiply emitted power. The area
pattern uses `raytrace.seed`, separately from the camera-jitter seed
`raytrace.progressive.seed`. One emitter sample still uses its centre. This is
direct lighting, with no MIS or diffuse GI; general glass and anisotropic
progressive transport remain unsupported. Host-pool and profile limits are unchanged.
At 1024 × 1024 the camera-sample cap allows at most 16 samples per pixel; at
512 × 512 it allows 64. Requests are also subject to the selected CPU resource profile's geometry,
job-memory and shared-host pool limits; see [CPU resource profiles](render-cpu-resource-profiles.md). Traversal,
shading, film updates and ordinary output work retain the selected profile's
cumulative work ceiling: Compact 1,000,000,000, Studio 1,000,000,000,000 and
Workstation 16,000,000,000,000. The count is not reset at a pass boundary.
Presentation has a separate finite precharge for the bounded early feedback and
nonfinal complete-pass opportunities; increasing the target is not an unbounded
codec/work grant. The camera-sample limit is a cold upper bound, not a promise
that every scene will finish below cumulative work or host-memory limits.
## Sampling, linear film and display
Camera jitter is a deterministic counter sequence keyed by the u32 seed, pixel
index and absolute sample ordinal. Reflection and HDR-direct variates use
separate domains of the same counter. Target sample count, worker quantum and
checkpoint cadence are not keys. Consequently, for an unchanged captured
request and scene, a checkpoint at N samples has exactly the same sample prefix
and PNG bytes as a job whose final target is N.
Each pixel stores three f64 sums and a primary coverage count. Only complete,
uniform passes can be resolved. Camera misses add zero scene radiance and zero
coverage. The resolve computes the mean scene radiance, applies exposure and
the existing tone curve once to covered radiance, composites the display-linear
backplate by coverage, and encodes sRGB once. The background is not illuminated
or exposed. Averaging already tone-mapped sample pixels is not equivalent and
is not used.
`film::primary::PrimaryFilm` is a compact camera-specific accumulator alongside
the existing statistical `FilmAccumulator`. It has incremental initialization
and requires the exact next scanline pixel and absolute ordinal on every update.
The existing general `FilmAccumulator`/borrowed `FilmPngTask` APIs are retained;
the owned image job uses the shared `PngEncoding` pipeline without a
self-referential borrowed task or a second independent pool.
## Preview publication and final export
`JobStatus.preview`, when present, contains:
```text
PreviewInfo {
frame_sequence: u32,
samples_per_pixel: u32,
frame: FrameInfo
}
```
`JobHandle::preview()` returns an `Arc<RenderPreview>` whose `png()` is the
immutable encoded snapshot. The first checkpoint has sequence 1. The job's
`JobId { session, serial, generation }` and captured `scene_generation` remain
unchanged across every pass. `frame_sequence` counts actual publications, not
samples or skipped boundaries. Clients cache previews by `(JobId, frame_sequence)`
and may retain an older snapshot without mutating it. For example, publications
SPP1/sequence1 and SPP2/sequence2 can be followed by a diagnosed retained-slot
skip at SPP3, then SPP4/sequence3 when a slot returns. The producer still processes
each real pass in order; this exception does not license a fabricated producer
jump from pass1 to pass3.
The runtime `JobStatus.cpu_preview_retention_skips: u32` counts nonfinal uniform
boundaries whose snapshot could not be published because both reusable slots
were externally retained. Retire an obsolete host-owned snapshot and retry the
credit before diagnosing that condition. Count that boundary once, not each
poll or a later retry of the same boundary. Closed pools, in-flight buffers,
unrequested feedback or an exhausted optional feedback quota are not themselves
evidence of external retention. Cancellation is checked before the diagnostic
update. This counter is runtime metadata, never saved
intent, and does not count frames physically displayed by a client.
The preview slot is separate from `JobStatus.frame`/`JobHandle::frame()`. A
preview cannot be exported through `render.export`, cannot become the session's
last completed image, and does not release the running task or film. The final
PNG is published only after its digest is complete; it clears the preview slot
and is the only new exportable result. `render.export` writes those exact PNG
bytes and does not render or re-encode them.
Cancellation clears the preview slot immediately. Failure and completion also
clear it. Publication checks the cancellation token while holding the same
record lock used for cancellation, including after the final digest chunk.
The worker cannot publish a late checkpoint into a cancelled or replaced job.
An externally retained preview remains an immutable snapshot of its original
job, but cannot replace a previous successfully completed final frame.
## Allocation and retained snapshots
Admission reserves the working film, existing RGBA/encoder/final-PNG capacity,
and at most two reusable immutable checkpoint slots with their metadata. It no
longer reserves a separate PNG for every possible pass. Protected feedback uses
its existing two partial-snapshot slots. Actual film, sidecar and PNG capacities
remain checked against admitted capacities after fallible allocation; there is
no full-film clone or growing production list of checkpoint PNGs.
A published snapshot retains a lease for its admitted slot. Replacing or clearing
the host's `Arc` cannot mutate externally held bytes or release their charge.
When the last consumer releases a snapshot, its credit can be reused while the
job is active. Terminal cleanup closes free credits; externally retained leases
stay billed until their last release. Existing working codec and final-image
buffers remain accounted separately.
If both slots are externally pinned, the diagnosed boundary produces no new
snapshot. The renderer continues sampling and final work without waiting for an
acknowledgement, failing the final merely because of retention, allocating an
extra slot or inventing a frame. Returning a credit permits a later real pass to
publish again. Final-only export, cancellation and captured identity are unchanged.
Even without pinned consumers, a latest-image client can coalesce observations
when it repaints more slowly than the worker; no latency or unconditional
physical-display guarantee follows from every-pass publication.
## Regression coverage
The source includes regressions for deterministic prefixes and worker quanta,
fresh primary rays, non-power-of-two targets, actual HDR/rough-reflection PNGs,
linear averaging before tone mapping, coverage and unexposed backgrounds,
bounded/cancelled film mutations, and the single cumulative work budget.
Host tests manually advance the worker to the digest/publication boundary. They
hold multiple preview `Arc`s through replacement, cancellation and completion,
check allocation identity and exact pool release, and reject an invalid
checkpoint sequence. Document tests cover offline limits and saved round trips.
Engine tests cover Check/Start equality, cold rejection before HDR capture,
session ownership, exact final export, and retention of the previous completed
image after a progressive job is cancelled. Execution evidence belongs to the
integrated CI receipts; this source handoff does not claim those gates passed.
@@ -0,0 +1,74 @@
# Explicit CPU resource profiles
**Composed-source proposal: integration, consolidated validation and large-scene native acceptance are pending.** The raised Workstation target requires the coordinated CPU accumulation, publication and UI adapters. These envelopes are admission limits, not measured performance or a final-quality certification.
## Intent
A CPU image must not inherit a small interactive-preview ceiling when the owner explicitly asks for a large still or a heavy assembly. Conversely, opening an old file must not silently authorize substantially more memory or work.
`job.options.budget` in a saved `cpu_raytrace` setup, or `raytrace.budget` in a runtime CPU request, selects one of three finite profiles. Omission means `compact`, preserving the previous policy. Unknown names, including `unlimited`, are rejected. The CPU dropdown preserves dimensions and sample count when changing profiles; an incompatible draft remains visible until the user corrects it or explicitly accepts proposed dimensions.
| Envelope | Compact | Studio | Workstation |
|---|---:|---:|---:|
| Maximum side | 4,096 px | 8,192 px | 16,384 px |
| Fixed-sampling pixels | 4,194,304 | 16,777,216 | 67,108,864 |
| Progressive pixels | 1,048,576 | 16,777,216 | 67,108,864 |
| Progressive samples/pixel | 64 | 1,024 | 1,048,576 |
| Total camera samples | 16,777,216 | 4,294,967,296 | 68,719,476,736 |
| Captured triangles | 262,144 | 2,000,000 | 8,000,000 |
| Visible bodies | 16,384 | 65,536 | 262,144 |
| Retained source geometry | 128 MiB | 1 GiB | 4 GiB |
| Complete job admission | 384 MiB | 3 GiB | 12 GiB |
| Cumulative work units | 1,000,000,000 | 1,000,000,000,000 | 16,000,000,000,000 |
Every column is an intersection of limits: a scene that fits the triangle count may still exceed its complete byte estimate. Similarly, a sample count within the per-pixel limit may exceed the total camera-sample or cumulative traversal-work limit. At 1,048,576 SPP, 256 × 256 already reaches Workstation's unchanged 68,719,476,736 camera-sample ceiling; the high target is not permission to use every resolution. Compact 64 and Studio 1024 remain unchanged. No claim is made that all maxima can be reached simultaneously or within a particular time.
Examples of cardinality admission, before geometry and memory are considered: Studio permits 3840 × 2160 at 128 samples/pixel; Workstation permits 7680 × 4320 at 128 samples/pixel. Compact rejects both instead of silently resizing them.
## Example saved intent
```json
{
"name": "CPU studio still",
"set": {
"width": 3840,
"height": 2160,
"job": {
"method": "cpu_raytrace",
"options": {
"budget": "studio",
"primary_samples": 1,
"progressive": { "samples_per_pixel": 128, "seed": 82 }
}
}
}
}
```
Submit this to `render.settings.set`. `render.preflight` and `render.start` accept the resulting named setup. The preflight reply identifies the CPU budget, all of its limits, and the estimated job admission. `render.backends` also lists the profiles without starting a device or allocating an image.
Large intent can be saved and reopened without a render host. Executing Studio or Workstation requires a native 64-bit host. A missing feature, unavailable host, unsupported optical combination or exceeded profile is an error, never a switch to another executor.
## Accounting and responsiveness
The source-capture gate, dimensions, camera-sample bound, BVH construction, film, encoded checkpoints, environment input, retained request and host reservation consume the same selected policy. Ray tracing no longer adds raster projected-triangle lists to its estimate: its own BVH, captured looks and film are charged instead, alongside a conservative pixel/codec allowance.
The native CPU host has a finite 16 GiB logical reservation pool on 64-bit platforms, including retained results and previews. It does not allocate that amount at startup, promise that physical RAM is available, or account for the rest of the CAD application or other processes. Per-job profiles remain smaller. Cooperative and registered GPU host pools retain their original 512 MiB limit; this change is not a GPU-memory expansion.
Fallible allocation, actual vector-capacity checks, checked arithmetic, bounded work quanta, cancellation checks and final-only publication remain required. A failed or cancelled job must release its working reservations and preserve the previous completed result. Progressive publication prepays two reusable snapshot slots plus existing working codec/final capacity, not one PNG per pass. Externally held snapshots keep their leases charged; if both slots are pinned, a diagnosed boundary can be skipped without blocking or failing final work. See [CPU progressive sampling](render-cpu-progressive.md#allocation-and-retained-snapshots).
Ordinary cumulative work caps remain exactly 1e9 / 1e12 / 16e12 for Compact / Studio / Workstation. The presentation allowance is separate and finite: with P output pixels and target H, at most min(P−1,64)+(H−1) early/uniform opportunities are precharged, each at 14 × preview_pixels + 65,538 units, with preview_pixels at most 1024². This allowance is not extra ordinary traversal work, an admission promise, or a display-latency guarantee. This increment does not implement tiled/out-of-core rendering or unbounded preview retention.
## Compatibility and limits
The new pending-format descriptor is `render-cpu-budget`. Old intent has Compact semantics; larger intent is not discarded on reopen. The independent GPU sampling flag remains separate from CPU progressive sampling. Visual material edits still do not change engineering material properties.
This increment does not introduce CPU diffuse global illumination, adaptive sampling, multithreaded transport, arbitrary dielectric geometry, texture displacement or EXR output. The existing optical-combination restrictions remain explicit. Raising an admission ceiling is not a performance optimization or a claim that every large scene is practical yet.
## Prepared regression coverage
Tests cover explicit 4K/8K admission without allocating a large film, BVH cardinality estimates for larger profiles, old/unknown profile handling, offline saved round trips, preservation of incompatible UI drafts, host-pool isolation, arithmetic overflow and linear film accumulation above 64 samples. Their execution belongs to the consolidated batch gate; formatting or static source checks alone do not constitute a passing test run.
## Display is separate from output
The result canvas validates image dimensions against the captured job, not a subsequently edited profile. The exported PNG is never resized or re-encoded for display. If a viewport's texture-side limit or the finite display-cache pixel limit is smaller than the result, only its UI preview is reduced, with an explicit warning and native 100% inspection disabled. Full-resolution tiled inspection remains pending. One displayed completed result may be pinned while a newer job completes, preserving exact export and accounting for its retained memory.
@@ -0,0 +1,185 @@
# CPU controls in the Render workspace
This incremental panel is built on advanced CPU source tree
`6e5db1e64376164878918eb68f1e5b311740afcd`. It prepares the same existing
`render.preflight` and `render.start` commands. It does not add a renderer, material asset or rendering dependency. The subsequent
numeric setup unit persists the portable subset through `RenderSetup.job`; see
[workspace settings](render-workspace.md#settings-and-product-camera).
Choose **CPU ray tracing** in Render. Three collapsible sections provide the
following controls; the existing AA 1/4/16, lighting presets, shadows and exposure
remain available in **Single image** sampling mode.
## Progressive CPU sampling
**CPU sampling mode → CPU progressive** accumulates samples of the existing CPU
integrator. In the coordinated source proposal, **samples per pixel** is bounded
by the selected profile: Compact 64, Studio 1024 or Workstation 1,048,576, together
with the unchanged pixel/camera-sample and other admission intersections. The
separate CPU sampling seed and explicit target are preserved on save/reopen;
Interactive uses those captured values rather than forcing every request to
16/0. The fallback 16/0 applies only without explicit progressive intent. These
changes require integration, validation and native acceptance.
Selecting the mode explicitly chooses one primary sample per pass; returning to
**Single image** restores the AA selector without discarding lights or HDR controls.
This is camera sampling of the existing integrator, not diffuse global illumination,
adaptive sampling or CPU denoising.
The initial progressive path accepts isotropic opaque surfaces and the supported
directional, point and spot lighting. Selected reflections require one reflection
sample. Area lights, LEDs, dielectric overrides and anisotropy must use Single image;
switching modes never silently removes these inputs. Check and Start report an
incompatible combination through the same request validation.
The compatibility Compact profile allows at most 1,048,576 progressive pixels,
dimensions up to 4096, and 16,777,216 pixel × sample evaluations. For example,
1024 × 1024 supports 16 SPP, whereas 64 SPP requires at most 262,144 pixels.
Explicit larger profiles retain their own intersecting limits; see
[CPU resource profiles](render-cpu-resource-profiles.md). Increasing SPP or loading
a setup never changes its dimensions automatically. If needed, the panel displays a
**Use the largest size at this aspect: W × H** action; only clicking it resizes
the draft. Save applies the same numeric limits without requiring a renderer and
leaves invalid drafts intact. Traversal, sampling and image encoding also share
the backend's cumulative work budget.
Normal source publication attempts a provisional snapshot at every complete
nonfinal pass 1, 2, 3, …, followed by the unique final at the requested target. Two
reusable snapshot slots bound retention. If both are externally pinned, the
actual runtime `cpu_preview_retention_skips` counter diagnoses that skipped
boundary while final work continues; it does not fabricate an image or sample.
The current-handle inspection diagnostic uses a real count, including zero, or
null when unavailable/failed; lookup errors are not included, and other reported errors are independent.
Publication is distinct from physical canvas repaint: a fast worker and slower
client can coalesce visible images. A provisional label includes actual SPP and
publication sequence; these need not be equal after a diagnosed skip. Job identity
and captured revision remain unchanged. Checkpoint updates reuse current pan/zoom.
Neither a counter nor the source change proves native 1→2→3→4 display or a latency
bound. Completion replaces the preview with its final image; cancellation or
failure removes the preview and returns to the previous completed
result with the same framing. **Export final PNG** always exports a completed frame,
even while a different provisional image is visible. With no completed frame, export
remains disabled. The UI keeps one decoded provisional texture and metadata, not
additional retained HDR/PNG buffers.
`CpuJob.progressive` persists the selected sample count and seed. Its absence or
`null` keeps Single image mode. Save As, Reload, setup switching and design reopen
preserve this option together with embedded HDR, nonedited numeric fields and the
setup's single exposure. The runtime CPU request nests it under
`raytrace.progressive`; the top-level `progressive: true` continues to select GPU
path tracing.
## CPU controls
| Section | Controls | Runtime limits |
| --- | --- | --- |
| Reflections | Visible body picker and filter, Off / Mirror / Rough, reflection depth and samples | At most 64 exact body names; 1–8 bounces; 1–64 reflection samples. Rough uses each body's existing opaque surface. |
| Environment | None, constant linear RGB radiance, or a checked/embedded Radiance HDR; intensity, HDR rotation and sampling | Intensity 0–64; RGB 0–1; finite rotation within ±1,000,000 radians (displayed as degrees); HDR samples 1/4/16/64. |
| Lights | Preset lighting or custom directional lights; additional point lights | At most eight directional and eight point lights; nonzero directions; linear RGB 0–1 and intensity 0–64. |
Numeric lighting, AA, shadows and constant-environment values are saved with the
active CPU method. Exposure uses the setup's one exposure field. Checked HDR bytes
and their controls can be embedded through the engine's atomic capture command;
body reflection bindings still cause Save to refuse a full job without discarding
those inputs. None of these controls changes a body's physical
material, geometry or mass. Raster CPU and GPU requests omit the CPU panel's options.
Switching methods retains local numeric drafts; Reload or choosing another setup
replaces them with the saved active method. Only the selected method's schema is sent.
## Body identity and validation
The picker lists visible evaluated bodies and narrows long lists with a filter;
it shows at most 256 rows per opening. Empty names, control characters and names
longer than 128 UTF-8 bytes cannot be selected. Duplicate visible names and stale
model evaluation are refused.
A reflection selection records its document pointer, scene revision and the
visible body's ordinal, creator feature and component. Check and Start refuse a
binding after a scene change. **Confirm this body** can refresh the revision only
when the same target still occupies the selected identity. If another body has
reused its name, remove the old selection and select the desired body explicitly.
This prevents a name-only runtime selector from silently following a replacement.
The engine still performs final capture and surface compatibility validation.
CPU reflections do not implement a general layered clear-coat transport model.
The engine rejects a coated body or face selected for an incompatible reflection
path. This panel does not claim diffuse global illumination, caustics or a general
glass renderer.
## Environment capture
**Constant** environment supplies secondary reflected/transmitted radiance. It
is not direct diffuse lighting and does not replace the image background.
**HDR** uses the CPU environment contract: Radiance `.hdr`, 2:1 panorama, at most
2048 × 1024 pixels and 16 MiB of source bytes, with explicit supported sRGB/D65
primaries. EXR and files without those primaries are refused. Selected rough
reflectors with HDR must meet the engine's fully metallic body/face constraints.
The picker uses the application's existing file dialog. A delayed answer is
accepted only by the same document, revision, setup, method and input selection.
Selecting a file runs `render.hdr.inspect`; typed paths require **Check HDR file**.
This checks the full bounded stream without a renderer or document mutation and
records its digest and metadata. Request construction itself does not read files.
**Check**, **Start** and **Save** send the same expected digest, so a changed source
is rejected until an explicit recheck. Cancellation and inspection failure retain
the prior selection. Once a job is captured, later file changes cannot alter its
pixels or export.
**Save Setup** uses `render.settings.capture_hdr` for a checked local source, saving
the immutable bytes and complete setup in one undo step. Only success switches the
panel to **HDR saved inside this design**. Further saves use `render.settings.set`;
Reload, setup switching and design reopen never need the original path. The CPU
HDR's rotation, intensity and sample count are saved separately from its source
ID. Rotation remains in radians internally; drawing the degree editor does not
round-trip or clamp it. A constant environment and HDR are mutually exclusive.
CPU still requires explicit sRGB/D65 primaries; it never inherits the GPU's optional
assumption for an undeclared source.
The last CPU check stores its exact request and revision and displays the captured
HDR dimensions, intensity, rotation, samples and SHA-256. It marks itself stale
when the scene or editable request changes. The active job displays its own
captured HDR descriptor. These UI records retain metadata, not image buffers or
HDR source bytes. Saved HDR bytes belong to the document resource table, not those
view records. An embedded source can be used with temporary reflection bindings
through the same runtime renderer, but the bindings themselves remain unsaveable.
PNG export remains the existing retained-frame export.
## Light units and precedence
Directions point toward a light and are normalized by the runtime; a zero vector
is invalid. Custom directional lighting replaces the preset directions; an empty
custom list deliberately has no directional lights. Selecting a preset clears
that custom list. Point lights are added to the chosen directional setup.
Point positions and distances are world millimetres. The reference distance is
where the specified intensity applies; the minimum distance bounds inverse-square
attenuation and must not exceed the reference. Both distances range from 0.001 to
1,000,000 mm in this panel. Intensities are relative renderer values, not a claim
of lumens, watts or calibrated photometric measurements.
Area lights, their sampling/seed and spot cones remain without dedicated panel
editors, but valid values loaded from a setup are preserved in Save, Check and Start.
Directions retain their original nonzero magnitude; showing a field does not normalize
or clamp it. Emission, surface effects, dielectric bindings and anisotropic faces
remain runtime API capabilities that this panel explicitly refuses to edit. A later
material/optics editor can expose those contracts separately.
## Integration and acceptance
This unit includes EN/ES/JA/ZH strings, request-contract regressions for body
identity and method isolation, environment bounds and light validation, delayed
picker protection, and an extended native UI test that selects a reflection mode,
checks and starts the same request, changes the HDR source after capture and
compares exported PNG bytes with the retained frame. The progressive UI adds
regressions for sequence caching, final publication racing the status read,
cancellation/export retention, explicit resolution adjustment, offline Save/Reload,
hidden values and reopening progressive setups with embedded HDR.
The author checked Rust formatting, locale-key coverage, whitespace and exact
patch replay. No Cargo build, test execution, native launch or visual quality
acceptance was performed for this incremental source unit. The integrator must
run the combined revision's CI and the native UI/render tests before treating
those regressions as passing. CPU controls and the GPU material editor have
separate modules and request builders; both must retain their final admission
guards when mounted together.
@@ -0,0 +1,146 @@
# CPU Interactive preview
The workspace adapter connects `job::interactive` to the Render canvas and the
Interactive card. Select **CPU ray tracing** in Output and use **On** to enable
the provisional native CPU preview. Entering Render or changing stages does not
enable it or start a final image. The registered `render.interactive` command
uses explicit on, pause, resume and off actions.
Interactive requires an available native worker host supporting CPU ray tracing;
it is not the web/cooperative Raster path or a GPU path-tracing preview. An
unsupported method, host or request reports a reason rather than changing
methods or discarding settings. The final renderer's settings, document format
and export registry remain separate.
## Workspace behavior
After On, committed camera, appearance, visibility, lighting and request edits
invalidate the current preview automatically. Capture groups edits after 200 ms
without a newer change; this is a scheduling rule, not a promised display
latency. The card exposes Updating, Refining preview, Sample target reached,
Pause/Resume and Off. A completed Interactive image is still labelled
Provisional preview; reaching its target does not make it a final result.
Pause cancels owned preview work and may retain accepted pixels as a reference.
Edits mark that reference Out of date. Resume uses the latest input identity.
An appearance or lighting edit alone does not prohibit repeated aligned
selection/material editing. Geometry targets require the accepted image's
camera, authored aspect, visibility, evaluated world and placement metadata to
match the current view. A changed camera, hidden body or changed geometry must
not authorize picking or Paint from stale pixels, including after a navigation
button is released. Unknown source pixels also cannot claim geometry targets.
A missing alignment certificate fails closed; painting a retained image does
not certify its geometry.
The image is fitted without stretching; painting and geometry input share its
actual pixel rectangle. Empty letterbox space is not a geometry target.
Navigation and release/Escape handling remain available when geometry input is
blocked. While an enabled preview awaits its current image, the canvas reserves
that route rather than painting the fast Model preview as current CPU pixels.
Off, leaving Render or changing documents disables/cancels the owned preview
context. A manual final temporarily suspends preview capture; it does not
export an Interactive image or cancel the final job. Result has canvas priority.
A failed capture waits for a relevant edit or explicit Resume instead of
starting an unbounded retry loop.
## Preview envelope
In the coordinated source proposal, `cpu_request` clones an immutable final
request and preserves its camera, background, shadows, exposure, lighting,
resources and transport. If that captured request has explicit CPU progressive
intent, its target and seed are retained; they are not replaced by the current
live draft or silently reduced to 16/0. Only an absent progressive intent uses
the existing fallback of 16 SPP and seed 0. One primary and one selected
reflection attempt are used per camera sample. The original final request stays
untouched.
Preview dimensions remain bounded to 1024 pixels along the longest edge,
rounded to the nearest pixel without enlargement. Integer aspect rounding is at
most half a pixel (or one pixel for an extreme aspect). Preserving a high target
does not remove the selected profile's pixel, total camera-sample, geometry,
traversal or memory intersections. Transparent output, another integrator or
unsupported progressive transport returns an error instead of dropping effects.
These changes still require integrated validation and native observation.
Rectangle/LED direct-light inputs, their emitter-sample count and area-pattern
seed survive preview lowering unchanged. Only camera/reflection sampling uses
the preview envelope; dielectric intent is retained for capture and transport
certification, while unsupported progressive combinations, including anisotropy,
still fail explicitly. This is not a promise of general glass support.
See [CPU progressive sampling](render-cpu-progressive.md) and
[CPU resource profiles](render-cpu-resource-profiles.md) for the separate final
request and admission contracts.
The coordinated retention diagnostic is read from the actual current job handle.
A successful status supplies `Some(count)`, including `Some(0)`; an absent handle
or failed status lookup supplies no count (`null` in the inspection reply), not
a fabricated zero. Lookup errors are not included; other reported errors are independent. A nonzero count
reports skipped snapshot boundaries caused by externally retained slots, not
missing samples or a count of physical canvas repaints; see
[CPU progressive publication](render-cpu-progressive.md#preview-publication-and-final-export).
## Exposure and image ownership
The saved setup's common exposure is finite and bounded to -32..32 EV.
With Interactive Off, Model uses that exposure in its fast product preview for
all final-method choices: CPU ray tracing, GPU path tracing and Raster. Editing
it does not require Start or enable the selected final executor. This Model
path still requires its viewport device and retains its current environment
restriction (rotation 0, intensity 1); it is not a promise of Model/final pixel
parity or of every final effect being represented.
Interactive receives exposure through its captured CPU request. Retained Result
and Interactive PNGs return through their own image-display routes before the
live Model exposure is applied. Editing the current draft must not grade those
captured pixels a second time. An explicit Effects/regrade action is a separate
operation. Design's viewport does not inherit product exposure. See
[Scene and Shot editors](render-shot-scene.md) for active versus selected setup
semantics and the saved Exposure control.
## Adapter contract
- Allocate a distinct transient job session for each document's Interactive
controller. Never recreate a controller with the same session while callbacks
from its previous instance can arrive. Do not register its jobs in the engine's
final/export registry. Reaching its captured sample target still produces
provisional content, not an exportable final.
- Increment `VisualRevision.visual_revision` whenever camera, draft, material,
visibility, lighting, HDR/resource, method or output intent changes. Include
changes that leave the document revision unchanged. Capture this counter and
`scene_generation` atomically with the full request and scene. This core does
not infer that identity from a setup name or a partial hash.
- Explicit activation calls `enable`; edits call `edit`. Supply monotonic elapsed
`Duration` values. `capture` issues one ticket after 200 ms without a newer edit.
Do not evaluate geometry or read files every frame just to compare identity.
- Recheck `accepts_capture(ticket)` before expensive capture/admission and after
worker preparation. This avoids preparing an already obsolete request; it does
not replace the mandatory identity checks in `attach` after admission.
- Capture through the existing authoritative engine boundary, prepare the CPU
request, then admit/submit through the installed CPU host using
`CaptureTicket::job_id()`. Pass the resulting handle to `attach`
with the original ticket. Delayed jobs are cancelled, including a wrong serial
or generation in our dedicated preview session. A foreign session is rejected
without cancelling its work, even if its handle arrived through a misrouted
callback. Final jobs must keep their distinct engine session.
Report a failed capture through `capture_failed`; failure waits for an edit or
explicit resume, rather than retrying every frame.
- Read only `current()` to publish checkpoint pixels. The existing host provides
immutable previews, sample counts, sequence and final target bytes. Their job
and revision must remain attached to the displayed image. A copied handle or
retained texture is not permission to display it as current after an edit.
- Pause may retain an immutable checkpoint in the adapter, explicitly labelled
paused and stale after edits. It cancels work. Resume uses the latest revision.
Leave Render or change documents with `disable`; Drop also cancels owned work.
- Before a manual final starts, call `set_final_active(true)`. This cancels only
Interactive work and prevents new capture tickets. Call it with false after the
final finishes; an enabled, unpaused controller then groups the latest edits
again. No method here cancels a final job or exports an image.
## Validation scope
These routes describe the current source contract, including the connected UI;
they are not a statement that native visual acceptance or GPU qualification has
passed on this revision. Core/headless regression coverage does not replace a
supported native build and admitted runtime checks. Pending integration gates,
Model/final numeric parity and the installed application's reported shadow
defect are not declared resolved by this document.
@@ -0,0 +1,151 @@
# Product-image jobs (R4a)
Native progressive opaque PNG rendering is described in [Progressive product images](render-path.md). It registers alongside the CPU executor.
R4a adds bounded CPU preview images to the Render workspace. The installed `builtin` /
`cpu-product` executor supports Preview, Image and PNG. It does not promise refraction,
HDRI, exposure, final mode or EXR; those requests fail explicitly. The subsequent
[opaque PBR consumer](render-opaque-pbr.md) adds opt-in direct-lit surfaces through
the same host. Legacy scalar looks and the Design snapshot renderer retain their
existing shading.
## One command path
`render.preflight` and `render.start` take `setup` (a saved name) OR `settings` (a
RenderSetup object; omitted fields use its documented defaults), plus optional
`transparent_background` and `replace` booleans, both false by default. Without either
setup/settings, the current requested camera is used, or the camera is fitted to the
product. Saving a setup is independent of starting a job. Unknown fields are errors.
Both commands reject stale geometry without settling a live modelling gesture. Finish
the gesture or use the explicit `render.scene` boundary first. Capture uses R3's
authoritative visible meshes, placements and appearances, without selection, edges,
axes, grids, sections or analysis overlays. A cold capture can prepare world geometry
and meshes synchronously; it is not a promise of bounded CAD evaluation latency.
Preflight validates capabilities and estimates admission, but does not reserve a queue
slot or the host memory pool. Start checks those resources again.
Start returns a typed `job: {session, serial, generation}`. Keep all three fields when
calling `render.status`, `render.cancel` or `render.export`. IDs are never accepted by
another document session, scratch copy, or a newly opened/recovered document. Status
does no rendering and never waits for completion. It reports queued, preparing,
running, encoding, cancelling, cancelled, completed or failed, with phase-local
`done/total`, structured job errors and completed frame metadata. Progress restarts
when a phase changes; it is not a time estimate.
The captured `scene_generation` is the session revision at start. Later edits, undo,
camera changes and tab switches do not mutate the snapshot. An image continues to
describe that captured scene; the UI labels a revision mismatch conservatively (view
cache invalidation can also advance a revision). Runtime state is outside the document,
undo, checkpoints and the design format. Closing/replacing a session cancels its work;
the worker cannot publish a cancelled frame. Direct host-side document replacement
preserves the installed image service while allocating fresh job ownership; old IDs
and completed images never cross into the new document. `replace: true` cancels retained active
and pending jobs before submitting the new request. A cancelled generation cannot
publish late. A successful older generation never replaces a newer successful result.
Each document retains at most two live jobs, four recent terminal status records and
one last successful image. Cancellation/failure preserves that image. A new successful
image releases the previous image; old terminal metadata can still report completion,
but it does not promise that its bytes remain exportable. Export requires an explicit
retained completed job ID; it never silently exports a different/newer job.
Native CPU raytracing can separately enable
[progressive camera sampling](render-cpu-progressive.md). A status may then include
`preview: {frame_sequence, samples_per_pixel, frame}`. Its complete-pass PNG is
available through the in-process `JobHandle::preview()` consumer; the JSON status
contains metadata only. The preview keeps the same job and capture identity,
but remains separate from the retained final image and `render.export`.
Cancellation, failure and final publication clear the provisional slot while
preserving the previous successful result when no newer final exists. Each
externally retained preview keeps the lease for its reusable admitted snapshot
slot until release; the composed every-pass policy reserves two slots rather
than one PNG for every pass. Publication may outpace physical client repaint.
The composed CPU source adds runtime `cpu_preview_retention_skips: u32` to job
status. It increments once for a real nonfinal uniform boundary that cannot
publish because both reusable slots remain externally pinned after retiring the
obsolete host snapshot and retrying its credit. Polling does not increment it;
closed pools, in-flight buffers, unrequested feedback or an exhausted optional
feedback quota are not themselves retention skips.
Sampling and final work continue without observer acknowledgements or an extra
snapshot allocation. SPP1/sequence1, SPP2/sequence2, skipped SPP3/count1, then
SPP4/sequence3/count1 is a valid publication history after one slot returns.
Actual producer passes must still be processed in order.
Zero is a value from a real status, not a substitute status after lookup failure.
The separate Interactive inspection diagnostic is nullable when there is no
current handle or its status lookup fails; lookup errors are not included and other reported errors are independent. Neither
form is saved in the design or proves that every snapshot was physically shown.
This is a source proposal pending integrated validation, not a native result.
## Native and browser execution
Each application installs one CPU host, shared by its documents. Native execution uses
one worker and at most two queued inputs across documents; it runs without UI polling.
The browser uses the same incremental task, pumped by UI frames, without threads.
Preparation, stable transparency sorting, clearing, pixel tests and downsampling check
cancellation between small units. A step admits at most 16384 units; PNG encoding
additionally yields after four rows. The UI pumps 1024 units per frame. These are work
bounds, not hard real-time guarantees: allocation, codec compression and OS scheduling
still have platform-dependent latency.
Admission caps output at 4096 per dimension and 4 million pixels; pixel scratch is
estimated at 48 bytes per output pixel (2x supersampling). Other limits: 262144
triangles/face overrides/edge polylines, 128 MiB retained source geometry, 384 MiB total
estimated memory per job, 512 MiB shared host admission including retained PNGs, and
128 million projected pixel tests. The projected-work limit is checked during bounded
preparation and may fail an admitted job. Encoded PNG bytes have an additional
`8 * output_pixels + 65536` cap. Allocator and codec internals are estimates, not an
operating-system memory quota. Limits fail with errors rather than allocating unbounded
buffers. Completed frames keep their memory reservation while bytes are retained.
The CPU path shades in linear light, blends sorted triangle alpha approximately, then
encodes 8-bit sRGB with straight alpha and an sRGB PNG chunk. Transparent shared edges
use a consistent fill rule. Intersecting transparent surfaces and triangle sorting
remain raster approximations. This is not a glass/refraction renderer. Native GPU
preview and CPU export can differ in shading and transparency.
PNG uses the already-transitive Rust `png` crate (MIT OR Apache-2.0), now an explicit
render dependency. No external render engine or third-party art is introduced.
## Export and automation
`render.export` takes `job`, `path` ending in `.png`, and `overwrite` (default false).
The destination is checked against the caller's existing file-access scope before
reading the retained frame or calling either native writer. Disallowed folders and
traversal are refused in both overwrite modes. Native no-clobber export writes/syncs a temporary beside the target and publishes it
with an atomic hard link; an existing destination wins even in a race. Filesystems
without that operation return an error. Explicit overwrite uses the existing atomic
writer without reading or backing up the previous target. Failed writes preserve the completed
image and CAD state. Browser export uses the existing virtual file/download service;
image-export paths or frame payloads are not persisted in the design. Saved HDR
input resources use their separate [document contract](render-hdr-resources.md).
The Render panel provides Check Render Request, Start Render, phase progress,
Cancel Render and Export PNG. Replace existing file is an explicit opt-in. A failed or
cancelled new render leaves the previous successful export available.
Native PNG export in the combined integration uses the document-bound asynchronous
picker from #1114. The requested job ID and overwrite choice are captured before the
dialog opens: cancellation writes nothing, closing the originating document drops
the answer, and an evicted image fails instead of substituting a newer result. A tab
switch does not redirect the export to another document.
Controls and phase messages use stable offline catalog IDs in English, Japanese, Chinese,
German and Korean; command IDs and scenario handles remain unchanged.
```sh
solidcraft-cli render examples/render-studio.json --out product.png --width 800 --height 600
solidcraft-cli render design.sc --setup Studio --out product.png --transparent
```
The CLI follows preflight/start/native wait/export, with a default 120-second wait
limit (`--timeout 1..3600`). Timeout requests cancellation. `--overwrite` is required
to replace an existing target. A persistent headless MCP session installs the same
host: use the ordinary `execute` tool with the five commands and returned job ID.
Closing the CLI/MCP process ends its session; a one-shot `exec render.start` is not a
durable background service. In a browser, leave the app running so frames can pump work.
Validation evidence and responsiveness measurements are recorded in the R4a issue/PR;
passing native tests or a wasm compile does not establish browser visual performance.
@@ -0,0 +1,320 @@
# Persistent render settings
Named setups save common render settings and, optionally, the complete numerical
configuration of one selected image method, including an optional embedded HDR.
Saving does not start a render, apply
the navigation camera or require an installed CPU/GPU executor. `render.preflight`
and `render.start` consume the same saved configuration and still check the current
host, geometry, capabilities and memory limits.
## Commands
```json
{"command":"render.settings.set","params":{"name":"Studio","set":{"width":1600,"height":900,"exposure_ev":1.5}}}
{"command":"render.settings.get","params":{"name":"Studio"}}
{"command":"render.settings.get","params":{}}
```
`set` creates a named setup from defaults or replaces supplied top-level fields in an
existing setup. A supplied `camera` or `job` replaces the whole value; it is not a recursive
patch. Omitted fields retain their values. `job: null` explicitly clears the job and
restores the legacy request protocol. Unknown fields (including camera/job fields),
invalid types and invalid values fail before document mutation. A new empty `set`
saves the defaults; setting an existing setup to identical values is a no-op,
preserving redo history and revision.
Each effective edit is one undo step and marks the document dirty. There is no delete
or rename command in this slice.
Named `get` returns `{name, setup}` or an error for a missing name. Without a name,
it returns `{setups, defaults}`. Reads do not evaluate the model or change history.
`render.lights.list {setup: "Studio"}` returns a uniform `{lights: [...]}` read
model without applying or saving anything. An unsaved client draft can instead
pass `{settings: <complete RenderSetup>}`; `{}` inspects the default setup.
Neither form selects a UI shot. Unknown parameters, null selectors, both selectors,
missing setup names and invalid settings refuse without mutation or evaluation.
CPU directional/point/spot/rectangle sources and GPU sun/rectangle sources expose
`id`, `kind`, `name`, `name_key`, `number`, `implicit`, `intensity`, `colour` and
their world-space geometry. Background and environment illumination are separate
from this source list. Implicit fixed studios and CPU presets are expanded;
explicit empty lists remain empty. GPU sky/HDR suppresses its implicit studio.
Light IDs use the kind and zero-based source slot (`directional:0`, `point:0`,
`spot:1`, `area:0`); point and spot share indices in the punctual list. IDs survive
numerical edits and repeated reads, but changing kind, reordering/removing lights
or replacing a rig can change them. These are setup-local addresses, not durable
document identities. Unnamed lights display Key, Fill, Rim, then Light 4, etc.;
clients translate `name_key`, substituting `number` for later lights. Names are
not persisted by this command.
Colour is linear RGB. CPU colour/intensity retain their saved values. GPU RGB
radiance is factored into its largest channel as intensity and normalized colour
(black uses intensity zero and white colour). Their product recovers radiance;
no photometric equivalence between methods is implied. All rectangle edges are
full side vectors in millimetres, including GPU half-edges multiplied by two.
Directional vectors point towards a source; spot axes point from it. The optional
directional `angular_radius_rad` identifies a finite GPU sun.
`render.lights.add`, `.set`, `.duplicate` and `.remove` edit a named setup in one
undo step. They accept `name`, `id` except for add, optional complete `settings`
as an unsaved starting point, and optional `expected_revision`. Add/set accept
`set` with `kind`, `intensity_ev`, `temperature_k`, `softness`, `azimuth_deg`,
`elevation_deg`, `distance_mm`, `size_mm`, `aim_at`, `width_mm`, `height_mm`,
`position_mm`, `direction`, `edge_u_mm`, `edge_v_mm`, `radiance`, `colour`,
`reference_distance_mm` and `minimum_distance_mm`. These lower into the existing
light fields; there is no new saved light metadata. Temperature is an original
three-band, 6500 K white-balanced Planck tint approximation stored as linear RGB.
Area softness changes emitter size; GPU Sun softness changes angular radius.
Hard CPU directional and point/spot sources refuse unsupported emitter softness.
CPU admits 8 directional, 8 point/spot and 4 areas; GPU admits one Sun and four
areas. GPU Point/Spot controls and the legacy three-directional GPU studio editor
remain unavailable with reasons, rather than silently losing light sources.
`render.lights.solo {id?, solo}` and `render.lights.mute {id, mute}` validate and
echo view requests. Enabling solo requires an id; disabling solo clears it.
The UI also verifies that the address exists in its current lighting draft.
`SolveApp::run` applies these replies to per-document `ViewState.lights`, never
to a design or undo history. Shot changes clear this transient scope. Saving,
undoing and reopening settings retain the unfiltered numerical setup.
`render_workspace_light::filter_request` filters copied settings at both
`image_request` and `SolveApp::run`'s Check/Render boundary. Explicit sources keep
their geometry and have zero intensity/radiance while off. Raster and the legacy
GPU studio carry three optional `studio_weights` in the captured `ImageRequest`;
they are finite 0..1 runtime values, never fields of `RenderSetup`. CPU raster
uses them in `studio::shade_weighted`; the GPU path uses its captured uniform.
CPU ray tracing and explicit GPU rigs refuse these fixed-studio weights.
The selectable Lights group runs `view.render_select {kind: "lighting"}` and opens
Lighting: Light source, Shadows and sampling, then Budget. Its + still adds a
light. CPU presets require review and consent before replacing directional lights;
Custom materialises their existing values. GPU budgets show one Sun and four
Areas; CPU eight directional and eight point/spot plus four Areas. Counts are
read-only sliders. Unsupported controls stay faded with a reason. No rig identity
is saved, so there is no Rig row.
Browser eyes and solo actions run the same view commands. A selected light mounts
`render_workspace_light::editor` in the Inspector's Lighting page. Without a
selected light, that page calls the same group editor. Light has a name/type
header, Area/Point/Sun segments, intensity, temperature and softness; Position;
Shape for areas; Falloff for points; and Behaviour (Solo, Mute, Duplicate, Delete).
Distances displayed as subject-size multiples lower to millimetres. Width U and
Height V are full side lengths (GPU storage uses half-edges). Independent vector
edits preserve the other side. Radiance and temperature lower to existing linear
RGB fields. Sun directions remain world vectors. Every edit is bounded and finite,
with the renderer validating the complete candidate. Opening an editor
does not apply or save anything. Edits run the four light commands; Place by
highlight stays disabled with its viewport-picking reason. The live product view
receives bounded analytic light samples in `Frame.product_lights`; both PBR and
non-PBR/transparent batches use them. This is an unshadowed preview, with area
emitters sampled at their centre and constant ambient illumination. HDR transport
and full emitter sampling remain the image renderer's responsibility.
| Field | Default | Saved contract |
|---|---|---|
| `backend` | `builtin` | Valid R1 backend ID, at most 64 ASCII bytes; unavailable IDs survive reopen |
| `mode` | `preview` | R1 `preview` / `final` mode; availability checked by a future render request |
| `camera` | Existing `Camera::default()` | Snapshot of target, yaw, pitch, roll, distance, fov and up; mm/radians, existing Z-up default |
| `width`, `height` | 1024, 768 | Positive, each at most 4096; product at most 4,194,304 pixels |
| `format` | `png` | R1 output format (`png` / `exr`); saving EXR does not add an encoder |
| `exposure_ev` | 0 | One exposure authority: Raster accepts -32 through 32; CPU raytrace accepts -32 through 32; GPU path accepts -32 through 32. Legacy setups retain -32 through 32. |
| `environment_rotation` | 0 | Legacy finite radians, magnitude at most 1,000,000. A typed `job` requires 0. |
| `environment_intensity` | 1 | Legacy finite value, 0 through 100. A typed `job` requires 1. |
| `background` | [236, 240, 245] | Three sRGB byte values; display backplate, independent of illumination |
| `job` | absent | Optional typed active `raster`, `cpu_raytrace` or `gpu_path` configuration; absent/null keeps the legacy protocol |
Camera target coordinates and positive distance are bounded to magnitude 1e9 mm;
angles to 1e6 radians. FOV is finite, `0 <= fov < pi`; zero means orthographic in
the existing camera model. Both existing camera up axes are retained. Setup names
are trimmed, nonempty, at most 128 UTF-8 bytes, without control characters. A document
has at most 32 setups. Validation also runs during document deserialization.
The raster product-image executor (`render.preflight` / `render.start` without `progressive`)
applies the existing `exposure_ev` to shaded product colour, preserving EV0 exactly.
PBR and explicit/weighted studio paths scale linear radiance by 2^EV before their
single Reinhard map and sRGB encoding. The plain historical scalar shader already
returns clamped display-linear shading here: it is scaled before its original
encoding without adding Reinhard or recovering clipped highlights. Backplate,
alpha, framing and geometry remain unchanged. `ignored_controls` still reports
unsupported legacy environment controls, but never lists applied exposure.
CPU and GPU keep their existing exposure authorities; the Raster-only resolved
request scalar refuses other producers. Model preview is a separate UI/GPU path.
## Complete numerical job intent
`job` is tagged by `method`. It saves the active method, rather than separate CPU
and GPU drafts. All numbers use the existing renderer contracts: world distances
are millimetres, angles are radians and light colours/radiances are linear RGB.
| Method | Saved fields | Main limits and defaults |
|---|---|---|
| `raster` | `transparent_background`, optional `lights` | Transparency defaults to false. Omitted/null lights retain the original fixed studio; `lights: []` is explicitly dark. At most eight hard directional sources; exposure uses the existing common field and raytrace controls remain unsupported. |
| `cpu_raytrace` | `options`: optional `progressive`, `primary_samples`, `preset`, `lights`, `punctual_lights`, `area_lights`, `area_samples`, `seed`, `shadows`, constant `environment`, embedded `hdr` | Primary samples 1/4/16 (default 1); shadows true; optional progressive/lists/preset/environment/HDR absent. At most 8 directional, 8 point/spot and 4 rectangular lights; progressive has the narrower contract below. |
| `gpu_path` | `transparent_background`, `options`: `samples`, `max_depth`, `seed`, `tone_map`, `denoise`, `lens`, `lighting`, sky `environment`, embedded `hdr` | Samples 1..4096 (default 64), depth 1..16 (default 8), seed u32 (default 0), Reinhard tone map, denoise false, optional values absent |
Raster sources use `{direction:[x,y,z], color:[linear r,g,b], intensity:number}`.
Directions point towards the source, are finite/nonzero and bounded by 1e9 per
component; linear RGB is 0..1 and relative intensity is 0..64. Saved values are
not normalized or display-encoded. Existing `render.lights.*` editing commands
persist directional edits in the Raster job. Point/spot/area and finite-disk sun
controls remain unsupported, including softness, position, falloff and radiance
edits. This is schematic opaque direct lighting and scalar alpha blending, with
no shadows, HDRI, physical glass or indirect transport.
A saved explicit Raster rig is authoritative: a simultaneous runtime
`raster_lights` key, including null, refuses instead of overriding saved intent.
Visibility filters a rendering copy; saving/reopening retains the authored rig.
The new saved field uses a pending design-format marker, without manual changes
to shared format numbers. Legacy Raster jobs omit the field unchanged.
CPU `preset` and explicit `lights` are mutually exclusive. An omitted/null light
list remains unspecified; `lights: []` explicitly removes the default directional
lights. Point lights retain their optional spot cone, its world emission axis and
both half angles. Rectangular lights retain full side vectors, sample count and
seed; `area_samples` and `seed` require a nonempty rectangular-light list. Area
samples are 1/4/16/64. Lists are bounded while deserializing and are never truncated.
The CPU constant environment retains `{color, intensity}` independently of the
backplate. See [CPU light union](render-light-union.md) for the spatial and light
validation contracts.
CPU `progressive: {samples_per_pixel, seed}` stores bounded camera accumulation
using the existing CPU transport. An absent/null value preserves fixed AA; an
empty object defaults to 16 samples and seed 0. The seed is u32 and
`primary_samples` must be 1. In the coordinated source proposal, per-pixel targets
are 1..64 for omitted/explicit Compact, 1..1024 for Studio and 1..1,048,576 for
explicit Workstation. Each remains subject to its profile's unchanged dimensions,
pixels, total camera-sample and other admission limits; see
[CPU resource profiles](render-cpu-resource-profiles.md). The compatibility
Compact limits remain 1,048,576 progressive pixels and 16,777,216 total camera
samples. Saving validates the selected intersection without a render host;
reopen preserves the explicit target, seed and budget rather than clamping intent.
Snapshots, checkpoint leases and the runtime retention-skip counter are not
saved fields. These source changes await integrated validation/native acceptance.
Area/LED direct lights retain the existing four
shared rectangle slots, emitter-sample counts and power normalization. Dielectric
and anisotropic-face overrides remain refused; the fixed CPU route retains them.
Embedded HDR and one setup exposure remain compatible. See
[CPU progressive sampling](render-cpu-progressive.md) for reflection limits,
work admission and provisional/final publication. The top-level runtime
`progressive: true` continues to select GPU.
GPU `lighting` retains the complete RGB ambient radiance, optional sun and at most
four rectangular lights. Omitted/null lighting keeps the renderer's legacy studio;
an explicit all-zero lighting object means a black studio. Those values are not
interchangeable. `lens` retains aperture radius and axial focus distance; nonzero
aperture requires a perspective camera. An explicit zero-aperture lens remains
explicit. Tone mapping and denoising retain their existing meanings and do not
create new executor capabilities.
The portable procedural GPU `environment` is:
```json
{"kind":"sky","gradient":{"zenith":[0.16,0.32,0.7],"horizon":[0.8,0.9,1],"ground":[0.12,0.1,0.08]},"rotation_rad":0,"intensity":1}
```
Gradient entries are finite linear RGB in 0..1,000,000; rotation is finite within
±1,000,000 radians; intensity is 0..100. Omitted gradient/rotation/intensity use the
shown defaults. The original procedural gradient is not a calibrated atmosphere.
An environment replaces the constant ambient-light term; it does not replace the
display background. See [environment rendering](render-environment.md),
[thin lens](render-thin-lens.md) and [studio lighting](render-studio-lighting.md).
An embedded HDR uses the separate `options.hdr` field and cannot coexist with a
constant CPU environment or a GPU sky. It references immutable bytes in
`render.resources`, not a file name. [Saved HDR resources](render-hdr-resources.md)
documents atomic file capture, CPU/GPU colour policies, strict container hydration
and the offline save/reopen contract. Optional `hdr` absent/null means no HDR;
when an HDR object is supplied, its resource and controls are required.
`RenderSetup.exposure_ev` is the only saved EV. CPU lowering copies it into the
runtime `raytrace.exposure_ev` and resets the legacy common-settings EV to zero;
GPU lowering uses it in `JobOptions`. CPU/GPU `options.exposure_ev` is rejected.
The two legacy common environment fields must stay at 0/1 when `job` is present;
the method's typed environment owns those values. Existing legacy values are
preserved, and a conflicting conversion fails instead of clearing them.
### Save, check and start
```json
{"command":"render.settings.set","params":{"name":"CPU studio","set":{"width":1600,"height":900,"exposure_ev":1,"job":{"method":"cpu_raytrace","options":{"primary_samples":4,"preset":"warm_cool","shadows":true}}}}}
{"command":"render.preflight","params":{"setup":"CPU studio"}}
{"command":"render.start","params":{"setup":"CPU studio","replace":true}}
{"command":"render.settings.set","params":{"name":"GPU studio","set":{"width":1600,"height":900,"exposure_ev":0.5,"job":{"method":"gpu_path","options":{"samples":256,"max_depth":8,"seed":42,"tone_map":"aces_fitted","lighting":{"environment":[0.1,0.2,0.3],"area_lights":[]},"environment":{"kind":"sky","intensity":0.5}}}}}}
{"command":"render.preflight","params":{"setup":"GPU studio"}}
```
An inline `{"settings": full_setup}` has the same semantics as a saved `setup` name.
The engine resolves the typed job **before** choosing CPU or GPU dispatch. A saved
`gpu_path` method requires the `gpu-path` executor; another executor announcing
progressive sampling cannot replace it. A missing or unsupported host blocks
Check/Start while leaving the saved intent intact.
For a complete job, additional request fields are `replace` and optional transient
`studio_weights` for a fixed studio. Parallel
runtime controls such as `progressive`, `integrator`, `raytrace`, `lens`,
`environment` or `transparent_background` fail, including explicit null/false
values. They cannot silently override a setup. For legacy `job` absent/null, the
existing runtime request API remains available; it has no inferred CPU/GPU method.
### Explicit portability boundary
External HDR paths, texture maps, GPU dielectric/clear-coat/texture body bindings and CPU
reflection, anisotropy, emission, surface-effect and dielectric bindings are not
part of this saved job format. Their fields are rejected, even when an unsupported
list is empty. Runtime requests can still use those existing features with an
inline setup whose `job` is null. Saving a complete setup must not discard them or
turn a current body name/ordinal into a persistent identity. HDR bytes are portable
through `render.settings.capture_hdr`; portable maps and durable body/face bindings
still require separate contracts. Runtime requests can reference an existing HDR
resource while supplying temporary bindings, without persisting those bindings.
No captured scene revision, worker, device, image result, `JobId`, host availability
or external path is serialized. Reproducible input configuration does not promise
bit-identical pixels across devices or renderer versions.
## Persistence and evaluation
Named setups live in `render: {setups: {name: setup}, resources?: {sha256: resource}}`;
empty render state is omitted.
The optional numerical job adds the `render-job-intent` pending format descriptor.
Embedded HDR adds its own `render-hdr-resources` descriptor.
The optional CPU sampling field adds `render-cpu-progressive`.
No historical format number or migration step is rewritten. Older designs need no
job transformation: an absent job keeps their common settings and runtime API.
Pending builds without the descriptor refuse the newer design instead of silently
losing its saved options. Plain JSON, design containers and document autosave
snapshots carry all HDR bytes. A command-only crash replay before a new checkpoint
still needs the source path recorded by `capture_hdr`; it must match the recorded
digest. This unit does not make that journal self-contained.
The engine avoids geometry evaluation only after proving that the document differs
solely in validated render settings, with unchanged active sketch and pending moves.
The proof compares the complete document after normalizing the render field, so mixed
geometry/appearance/placement edits take the usual conservative refresh path. It uses
a document clone/comparison, not a constant-time or whole-application speedup claim.
Unchanged render pointers short-circuit the check for normal modelling commands.
Render-only edits, undo/redo and checkpoint restore preserve model state, its stale
marker, cached tessellation and the prepared world state. A stale live-drag result never
becomes authoritative through a settings edit; the next model-reading command still
settles it normally. Revision advances for consumers that track document changes.
Geometry, physical materials and appearances retain their existing representations;
the setup stores image configuration, not material assignments.
No new third-party dependency or asset is introduced. `doc` depends on the existing
pure `render` crate for its shared camera and R1 identifiers, within the L2 → L1 rule.
### Saved CPU dielectric policy
CPU `job.options.dielectric_transport` accepts `legacy_bounded` or `strict_tir`.
Missing/default values retain Legacy and are omitted on serialization. The UI
edits that CPU field and preserves it on Save, reopen, load and request capture;
there is no common RenderSetup policy field or implicit renderer/profile change.
The format records this new meaning through its own pending change. It does not
make captured body identities or temporary optical/material bindings portable.
Strict transport continues deterministic internal glass reflections and errors
on an unresolved positive non-TIR depth tail. Unsupported selected opaque
reflections, effects and geometry remain explicit refusals, with authored intent
preserved. The ordinary command/host validation still applies to each captured
request; Check is not a promise of successful tracing or a memory reservation.
File diff suppressed because it is too large. Load diff
@@ -0,0 +1,229 @@
{
"status": "SOURCE_PRESERVATION_C27_POSTFORMAT_BUILD_FAILED_ALL_SELECTED_TESTS_UNRUN",
"base": "Exact per-file before RAW bindings below, not arbitrary main or the earlier nine-file snapshot. Preserve unrelated files.",
"before_source_manifest_sha256": "2f39172dd42414588fb0c88cb23d30c2d5f626592ab3d4632b032701e85edbf1",
"after_source_manifest_sha256": "a7b088eef563cbba4bfc5f2c26cf2d02ac6e855088710a072fdff35f889c1551",
"files": [
{
"path": "assets/locales/pending/cpu-progressive-passes.json",
"before_sha256": null,
"before_bytes": null,
"after_sha256": "7d11a688edad617ae6da92e8460f8833e121167ddb1b296001807f585e7b8c12",
"after_bytes": 619,
"formatted_in_actual_C27": false
},
{
"path": "crates/render/src/film_primary.rs",
"before_sha256": "2c8b7cf8b1d6aff1d58f4137b05973467b23072c2caff9467256606058fb8f88",
"before_bytes": 8361,
"after_sha256": "d65f9fda36674199aac47ef9c393d59fe59d193addbb7423e324f0795211d1c5",
"after_bytes": 8123,
"formatted_in_actual_C27": false
},
{
"path": "crates/render/src/film_tests.rs",
"before_sha256": "3fc4f5251f04f63a2a43a1f141fdccd3f66c50d3d8d42eff77754d21c4bdb2b7",
"before_bytes": 20416,
"after_sha256": "7e184b0c71f73bdeda036930c3e5a6a775a448b779283fde46b32c65ab3e9f20",
"after_bytes": 29879,
"formatted_in_actual_C27": true
},
{
"path": "crates/render/src/job/cpu_budget.rs",
"before_sha256": "7756fedf76658a1eedd0c0194aa98141d33464c0f7df85fe86f9e255fd8b8ce2",
"before_bytes": 7771,
"after_sha256": "e02df70cd48a5116a42363431839c0c4d6f25f041e761f7ce01c04dc998a8aca",
"after_bytes": 7776,
"formatted_in_actual_C27": false
},
{
"path": "crates/render/src/job/host.rs",
"before_sha256": "58147bb99311a07182a75e9e28aeb7f1aca752dff43724234225715479b741f2",
"before_bytes": 122246,
"after_sha256": "f775f4e458947b2c402fe97f10b320f7c7f4a9060cf502b5a69975e006eec71e",
"after_bytes": 131474,
"formatted_in_actual_C27": true
},
{
"path": "crates/render/src/job/host_tests.rs",
"before_sha256": "c46cddeafe1816f0c479a9c68482ff86ccd8e124c2f5fc1bb7cd6e3509ef7f8e",
"before_bytes": 106536,
"after_sha256": "f159bd988beb8055b7d6e80a89eef5ba1e967e982c97d5480b80c93d19509ef0",
"after_bytes": 119544,
"formatted_in_actual_C27": true
},
{
"path": "crates/render/src/job/interactive.rs",
"before_sha256": "5fb7062276adfdc22d1fa651750119feb90870b31d12fb0fc0b852c4b430468d",
"before_bytes": 11135,
"after_sha256": "97395da5b097d9283ac080e197f6de612b6123d9a90396e1850ca911d6ca5812",
"after_bytes": 14389,
"formatted_in_actual_C27": true
},
{
"path": "crates/render/src/job/mod.rs",
"before_sha256": "87c5b59cf171009c3f3261e7d7a7691f84fc3e9ddd25f8458e6b1098e1a45543",
"before_bytes": 82216,
"after_sha256": "ad442c55f9a3edeeac359ca4c91c2dc5028bee36b981f6953e6399daf65c7c12",
"after_bytes": 84674,
"formatted_in_actual_C27": true
},
{
"path": "crates/render/src/raytrace/environment_image_tests.rs",
"before_sha256": "9ee820799d6da59f8518197116984035d0292b86db4bbecb01135529590d1f53",
"before_bytes": 14628,
"after_sha256": "42442aaa4bcdda016b4349e096fd389e731df13683dbef9938925298432912b9",
"after_bytes": 14637,
"formatted_in_actual_C27": false
},
{
"path": "crates/render/src/raytrace/image.rs",
"before_sha256": "d833890ff3fde61b22993b2a736a0914c6675a8d810b2f396d0b611ef66f51e4",
"before_bytes": 124736,
"after_sha256": "4e8f63765ca35f305e3caa0946fceba90573be243717bd08b54deeb948f59326",
"after_bytes": 126260,
"formatted_in_actual_C27": true
},
{
"path": "crates/render/src/raytrace/image_tests.rs",
"before_sha256": "8af684984fce86ee3d8b8eff35c6a70efd88b0b9b7bbfefd42d082584bc9aa91",
"before_bytes": 173377,
"after_sha256": "5e6724dfe01a583b880862e24a2bfada40052bda09388e977f28f70f55029f89",
"after_bytes": 173358,
"formatted_in_actual_C27": false
},
{
"path": "crates/render/src/raytrace/mod.rs",
"before_sha256": "d7f8ed95a60384d1e8f896ec0637af39682778adf4546c646104ae22ab53fbb8",
"before_bytes": 18244,
"after_sha256": "cf1a6ebf707d86552bdb62bb94b80910eca1709682c8e7133c1ae54ce1af4c15",
"after_bytes": 18040,
"formatted_in_actual_C27": false
},
{
"path": "crates/render/src/raytrace/primary_aa_tests.rs",
"before_sha256": "693af2028d9446f95b61b002644649d5c9a945a049ec019508849712be06ea7e",
"before_bytes": 91756,
"after_sha256": "9366a35fa85e3b04eca01438da697979a1be4528fbc57a21d13da4b69aa175fc",
"after_bytes": 98436,
"formatted_in_actual_C27": true
},
{
"path": "crates/render/src/raytrace/progressive.rs",
"before_sha256": "8ee8fd60c78d93d02ab3b15270b27491bd993d5fc4e0e36217f8653c4881993a",
"before_bytes": 4252,
"after_sha256": "04b0431ba2b06c910ab884bdcd2fe7945b8211acc6527f4006fcc35b415c19d3",
"after_bytes": 4252,
"formatted_in_actual_C27": false
},
{
"path": "crates/render/src/raytrace/tests.rs",
"before_sha256": "2a105d16f476821e15962c6014d3b8fa8e124447ba36a8ee1d393bb2715d8e79",
"before_bytes": 20569,
"after_sha256": "a47fd554d0cd504d64237de7e160e89f89f53181eed4e30a9e0092ee7869fec7",
"after_bytes": 22825,
"formatted_in_actual_C27": true
},
{
"path": "crates/ui-egui/src/render_workspace.rs",
"before_sha256": "6262d926d6e3dae4d6ed92fee6f429b413cf1de9f9185da2701cd351e5b20ab1",
"before_bytes": 108186,
"after_sha256": "1434d0b576ab7c8a94ca7f23b9f0bb617f755509cd6f16bfafb3a86cfed05263",
"after_bytes": 111146,
"formatted_in_actual_C27": true
},
{
"path": "crates/ui-egui/src/render_workspace_cpu.rs",
"before_sha256": "3a06929c32104559374f62f4dd5134333c785345e4ba62762445f587a722daf9",
"before_bytes": 42638,
"after_sha256": "fd6de0f8121dc4d1bfce308c376901f65e2d920b68a756c38a25f82679db64ad",
"after_bytes": 42703,
"formatted_in_actual_C27": true
},
{
"path": "crates/ui-egui/src/render_workspace_interactive.rs",
"before_sha256": "41dfccef77b9079af801bcfa3998dadc4976e20e7b1000f2666e1c75a3cf3332",
"before_bytes": 56174,
"after_sha256": "b0ecc5211491343015ca3b69749d707bcafd9826c3a7e90d9fc3cce89ade9d9d",
"after_bytes": 57748,
"formatted_in_actual_C27": false
},
{
"path": "crates/ui-egui/src/render_workspace_tests.rs",
"before_sha256": "e7ff1b00bc5462db698096712965cb47f4177682bdb39ac0b6850d9c26710535",
"before_bytes": 619102,
"after_sha256": "28ddafe4a8f133c522ddf6f1e0eaaaf70f954d7b8acdb7cca44aabef9a512e47",
"after_bytes": 634699,
"formatted_in_actual_C27": true
},
{
"path": "docs/render-cpu-progressive.md",
"before_sha256": "d5eb9a24058ae465529539768a3885cd14e38f2de14597e2eecb64ae5a099821",
"before_bytes": 10324,
"after_sha256": "8bbd70ac09e49585ad266d44d5c4034cae811e9e266a54b7979a202db20d81aa",
"after_bytes": 12920,
"formatted_in_actual_C27": false
},
{
"path": "docs/render-cpu-resource-profiles.md",
"before_sha256": "b7c0a7101dba8906dbdc40994539dc558a97e8d32f8b363eea4ec83459e7a7b8",
"before_bytes": 6149,
"after_sha256": "acd230a198874f627df5d2e191a1c471e8dde744e4b7b3fad27618ac464e0063",
"after_bytes": 7218,
"formatted_in_actual_C27": false
},
{
"path": "docs/render-cpu-workspace.md",
"before_sha256": "75e77c82e266f9b58eba8e1a09bc27d3ade505394ad9c34cb1d583bae098fe8e",
"before_bytes": 10769,
"after_sha256": "f87351e1b28849e74a5fb7e6027caeac724eb9665c7a0d135ac3ff25d589b39f",
"after_bytes": 12121,
"formatted_in_actual_C27": false
},
{
"path": "docs/render-interactive.md",
"before_sha256": "f98decbcdb5d91568e103c794a0b785b31d127d6dc439eb8911270534b13be82",
"before_bytes": 8333,
"after_sha256": "6ee032d7e595e7402d235d45cc6719f3ec0e2309680e3ae87cea4baef122a58e",
"after_bytes": 9354,
"formatted_in_actual_C27": false
},
{
"path": "docs/render-jobs.md",
"before_sha256": "c54c1e0d6376874faefc9b2f64ae21ea2658006fae557c8c048b0f0fb9282b81",
"before_bytes": 8826,
"after_sha256": "f07479ae20c57baa025809c298a8adc005e96f28a3f9ad05a78233406bc5cc8b",
"after_bytes": 10187,
"formatted_in_actual_C27": false
},
{
"path": "docs/render-settings.md",
"before_sha256": "fee45ded12b0b4f62765b06e05ff4d2cdbe9a28b1cd2588f3f18165797c3c1d0",
"before_bytes": 21700,
"after_sha256": "6887fb62faf5e82731ba9849f76445cd66cdf1539cc81f054db2068b3359276d",
"after_bytes": 22284,
"formatted_in_actual_C27": false
}
],
"selected_paths": 25,
"actual_formatter_changed_paths": 11,
"C27_result": {
"formatter_exit": 0,
"format_check_exit": 0,
"combined_build_exit": 101,
"coded_error": "E0308",
"location": "crates/render/src/job/host.rs:734",
"meaning": "A compile-time aggregate metadata-size bound is false; exact layout bytes were not inferred and the bound was not relaxed",
"native_selected": 982,
"native_executed": 0,
"native_passed": 0,
"native_failed": 0,
"native_unrun": 982,
"inventories_executed": 0,
"qualified_five_library_artifact_set": false,
"full_CI_or_native_acceptance": false
},
"supersedes_for_continuation": "dbc6041ba7059ec30b11fa72b5d1abd59f5b104a nine-file high-pass/UI source snapshot; earlier files remain historical alternatives, not patches to stack blindly",
"producer_host_fix": "Private successor pending, not included in this exact failed-source snapshot",
"default_change_process": "Unresolved before production readiness; this preservation does not waive a preference/default rule"
}